Swift operator `subscript` []

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

    class Container {
        private var list = [Any]()
        subscript(_ index: Int) -> Int? {
           get {
                guard index < list.count else { return nil }
                return list[index]
          }
           set(newValue){
              guard let unwrappedElement = newValue else { return }
              list.insert(unwrappedElement, at: index)
           }
        }
    }
    

    Here we are using subscripts with optional type to handle index out of range.

提交回复
热议问题