Swift运算子`subscript` [] [英] Swift operator `subscript` []

查看:116
本文介绍了Swift运算子`subscript` []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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的元素1array?

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆