Swift 下标脚本
封面图
•
2025-10-23
•
Swift
1
0
0
0
在 Swift 中,**下标脚本(Subscript)** 是一种用于访问集合、序列或列表中元素的语法。它类似于数组或字典的索引方式,但你可以自定义自己的下标脚本来实现更灵活的数据访问方式。 --- ## 📌 一、什么是下标脚本? 下标脚本是类、结构体或枚举中的一种特殊方法,允许你使用类似数组的方式访问对象中的元素。 例如: ```swift let array = [1, 2, 3] print(array[0]) // 使用下标访问数组的第一个元素 let dict = ["name": "Alice"] print(dict["name"]) // 使用下标访问字典的值 ``` Swift 的 `Array` 和 `Dictionary` 都内置了下标脚本。 --- ## 📌 二、自定义下标脚本 你可以为自己的类型定义下标脚本。语法如下: ```swift subscript(index: IndexType) -> ElementType { get { // 返回指定索引的元素 } set { // 设置指定索引的元素 } } ``` ### 示例:自定义一个简单的集合 ```swift struct MyCollection { private var data: [Int] = [10, 20, 30] subscript(index: Int) -> Int { get { return data[index] } set { data[index] = newValue } } } let collection = MyCollection() print(collection[0]) // 输出 10 collection[1] = 50 print(collection[1]) // 输出 50 ``` --- ## 📌 三、支持多个参数的下标脚本 Swift 允许你定义带有多个参数的下标脚本。 ```swift struct Matrix { var elements: [[Double]] = [ [1, 2], [3, 4] ] subscript(row: Int, column: Int) -> Double { get { return elements[row][column] } set { elements[row][column] = newValue } } } let matrix = Matrix() print(matrix[0, 1]) // 输出 2 matrix[1, 0] = 10 print(matrix[1, 0]) // 输出 10 ``` --- ## 📌 四、只读下标脚本(没有 `set`) 如果你只需要读取数据,可以只定义 `get` 方法: ```swift struct Info { let name: String = "Alice" let age: Int = 25 subscript(key: String) -> Any? { get { switch key { case "name": return name case "age": return age default: return nil } } } } let info = Info() print(info["name"] as! String) // 输出 "Alice" ``` --- ## 📌 五、注意事项 - 下标脚本不能有参数标签。 - 下标脚本不能有可变参数(variadic parameters)。 - 下标脚本必须返回一个值(除非是 `Void`,但通常不会这样用)。 --- ## ✅ 总结 | 特性 | 描述 | |------|------| | 用途 | 提供类似数组的访问方式 | | 语法 | `subscript(index: Type) -> Type { ... }` | | 可读写 | 可以只定义 `get` 或同时定义 `get` 和 `set` | | 多参数 | 支持多个参数 | | 类型 | 可用于类、结构体、枚举 | --- 如果你有具体的应用场景,比如自定义一个缓存系统、二维数组、或者字符串索引等,我可以帮你设计一个具体的下标脚本示例 😊
上一篇:
Swift 类
下一篇:
Swift 继承
标题录入,一次不能超过6条
返回顶部
留言
留言
评论