问题描述
我是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` []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!