Swift operator `subscript` []

后端 未结 6 661
野性不改
野性不改 2020-12-31 01:01

I am beginner with the Swift having no advance knowledge with operators.

I have the following class

class Container {
   var list: [Any]         


        
6条回答
  •  伪装坚强ぢ
    2020-12-31 01:36

    It sounds like you are looking for subscripts. You can make subscripts for your own type like the following example:

    class Container {
        var list = [["Hello", "World"], ["Foo", "Bar"]]
    
        subscript(index: Int) -> [String] {
            get {
                return list[index]
            }
            set {
                list.insert(newValue, atIndex: index)
            }
        }
    }
    

    The above example works with the double [ ] only because I know that we are going to return an Array. Here the Array contain Strings as an example, but you could of course swap in your own type

    var container = Container()
    
    container[0][0] = "Stack"
    container[0][1] = "Overflow"
    
    print(container[0][0]) // "Stack"
    print(container[1][1]) // "Bar"
    

提交回复
热议问题