Swift operator `subscript` []

后端 未结 6 690
野性不改
野性不改 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:54

    It looks like there are 2 questions here.

    1. How can I enable subscripting on my own custom class?

    To enable subscripting on your class Container you need to implement the subscript computed property like this.

    class Container {
        private var list : [Any] = [] // I made this private
    
        subscript(index:Int) -> Any {
            get {
                return list[index]
            }
            set(newElm) {
                list.insert(newElm, atIndex: index)
            }
        }
    }
    

    Now you can use it this way.

    var container = Container()
    container[0] = "Star Trek"
    container[1] = "Star Trek TNG"
    container[2] = "Star Trek DS9"
    container[3] = "Star Trek VOY"
    
    container[1] // "Star Trek TNG"
    

    2. Can I access one element of Container that supports subscripting writing something like data[1][2]?

    If we use your example no, you cannot. Because data[1] returns something of type Any. And you cannot subscript Any.

    But if you add a cast it becomes possible

    var container = Container()
    container[0] = ["Enterprise", "Defiant", "Voyager"]
    (container[0] as! [String])[2] // > "Voyager"
    

提交回复
热议问题