我是Swift的初学者,对操作员不了解.
I am beginner with the Swift having no advance knowledge with operators.
我有以下课程
class Container { var list: [Any] = []; }我想实现运算符subscript []以便从list访问数据.
I want to implement the operator subscript [] in order to access the data from list.
我需要这样的东西:
var data: Container = Container() var value = data[5] // also data[5] = 5我还希望能够编写如下内容:
Also I want to be able to write something like this:
data[1][2]是否可能考虑来自Container的元素1是array?
Is it possible considering that element 1 from Container is an array?
感谢您的帮助.
推荐答案这里似乎有2个问题.
要在类Container上启用subscripting,您需要实现这样的subscript计算属性.
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.我可以访问Container的一个元素,该元素支持下标编写data[1][2]之类的内容吗?
如果我们使用您的示例否,则不能.因为data[1]返回的类型为Any.而且不能下标Any.
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"更多推荐
Swift运算子`subscript` []
发布评论