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

标签 ios swift

标题几乎解释了这个问题,我想做这样的事情: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/

相关文章:

ios - 当应用程序重新启动到后台时,是否会调度主队列?

ios - UIButtons 未显示在 UIScrollView 中

swift - 显示 uitableview 后更改 UITableViewCell 高度

ios - Reveal UIViewController,普通模式

javascript - 尝试注册 RCTBridgeModule 类 RCTFileReaderModule

ios - 关闭然后打开后如何在后台重新连接BLE设备?

ios - 如何在 iOS swift 中获取点击点(坐标)

swift - 在 Swift 中将处理程序传递给 UICollectionView 单元格

ios - 如何导致模型更新以快速触发另一个 Controller 中的更新

cocoa - Swift 字符串和 cocoa 绑定(bind) : placeholder string is not displayed