gpt4 book ai didi

ios - 我可以在 Swift 中使用静态下标吗?

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:15 26 4
gpt4 key购买 nike

标题几乎解释了这个问题,我想做这样的事情:MyStruct[123] 而无需调用函数 (MyStruct.doSomething(123)) 或创建实例 (MyStruct()[123])。将它放在类或结构上就可以了。

最佳答案

因为 Swift 5.1 静态和类下标是可能的 ( Proposal SE-0254 )。它们被称为 type subscripts .

所以现在可以这样做了:

struct MyStruct {
static var values = ["a", "b", "c"]
static subscript(index: Int) -> String {
values[index]
}
}

print(MyStruct[2]) // prints c

关于ios - 我可以在 Swift 中使用静态下标吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35609191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com