Swift运算子`subscript` []

编程入门 行业动态 更新时间:2024-10-21 16:20:54
本文介绍了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的元素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` []

本文发布于:2023-10-14 22:19:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492377.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   subscript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!