1. 什么是下标
在 Swift 中,下标(Subscript) 是一种可以像访问数组、字典那样,用方括号 [] 快速读写集合、序列或自定义类型内部元素的语法糖。它本质上是一个特殊的访问器方法,让类型支持 instance[key] 这种写法。
例如我们熟悉的数组和字典:
swift
let numbers = [10, 20, 30]
print(numbers[1]) // 20
var dict = ["name": "Tom"]
print(dict["name"]!) // Tom
这些能力并不是编译器硬编码的,而是通过为类型定义 subscript 实现的。我们也可以为自己的类型定义下标,从而获得同样的访问体验。
2. 下标的基本语法
下标使用 subscript 关键字声明,语法结构如下:
swift
subscript(index: Int) -> Element {
get {
// 返回对应元素
}
set(newValue) {
// 设置对应元素
}
}
要点说明:
- 下标可以只有
get,此时为只读下标; - 同时提供
get和set时为读写下标; - 只读下标可以省略
get关键字,直接写返回表达式; set中的newValue名称可以省略,Swift 默认使用newValue。
3. 只读下标示例
下面定义一个简单的只读下标,用于按索引读取数组元素:
swift
struct SimpleArray<T> {
private var storage: [T] = []
init(_ elements: [T]) {
storage = elements
}
subscript(index: Int) -> T {
return storage[index]
}
}
let arr = SimpleArray([1, 2, 3])
print(arr[0]) // 1
这里省略了 get,因为只读下标只需要返回一个值。
4. 读写下标示例
如果需要支持修改,就要同时实现 get 和 set:
swift
struct MutableArray<T> {
private var storage: [T] = []
init(_ elements: [T]) {
storage = elements
}
subscript(index: Int) -> T {
get {
return storage[index]
}
set {
storage[index] = newValue
}
}
}
var arr = MutableArray([1, 2, 3])
arr[1] = 20
print(arr[1]) // 20
注意:set 中直接使用 newValue 即可,无需显式声明参数名。
5. 多维下标
下标可以接收多个参数,用逗号分隔,从而实现类似二维数组的访问方式:
swift
struct Matrix {
private var rows: [[Int]]
init(rows: [[Int]]) {
self.rows = rows
}
subscript(row: Int, column: Int) -> Int {
get {
return rows[row][column]
}
set {
rows[row][column] = newValue
}
}
}
var matrix = Matrix(rows: [[1, 2], [3, 4]])
print(matrix[0, 1]) // 2
matrix[1, 0] = 30
print(matrix[1, 0]) // 30
多维下标让矩阵、网格等数据结构的使用更加直观。
6. 带标签的下标参数
Swift 允许为下标参数添加外部标签,提升可读性:
swift
struct Grid {
private var data: [Int] = Array(repeating: 0, count: 100)
subscript(row row: Int, column column: Int) -> Int {
get {
return data[row * 10 + column]
}
set {
data[row * 10 + column] = newValue
}
}
}
var grid = Grid()
grid[row: 2, column: 3] = 5
print(grid[row: 2, column: 3]) // 5
带标签的下标在参数含义不直观时尤其有用。
7. 下标与类型下标
除了实例下标,Swift 还支持类型下标 ,使用 static subscript 声明,通过类型本身访问:
swift
enum Weekday: Int {
case monday = 1, tuesday, wednesday, thursday, friday
static subscript(index: Int) -> Weekday? {
return Weekday(rawValue: index)
}
}
if let day = Weekday[3] {
print(day) // wednesday
}
类型下标常用于枚举、配置表等场景,让类型本身具备类似集合的访问能力。
8. 下标与协议
协议中可以声明下标要求,遵循协议的类型必须实现对应下标:
swift
protocol Indexable {
associatedtype Element
subscript(index: Int) -> Element { get }
}
struct IntList: Indexable {
private let values = [1, 2, 3]
subscript(index: Int) -> Int {
return values[index]
}
}
协议中的下标只声明签名,具体实现由遵循类型提供。
9. 下标与泛型
下标同样可以结合泛型使用,让访问逻辑更灵活:
swift
struct SafeArray<T> {
private var storage: [T]
init(_ elements: [T]) {
storage = elements
}
subscript(index: Int) -> T? {
guard index >= 0, index < storage.count else {
return nil
}
return storage[index]
}
}
let safe = SafeArray([1, 2, 3])
print(safe[5] as Any) // nil
通过返回可选值,可以实现越界安全的访问方式。
10. 使用注意事项
- 越界检查:自定义下标不会自动做边界检查,需要自行处理,否则可能触发运行时崩溃;
- 性能:下标应尽量保持轻量,避免在其中执行复杂逻辑;
- 语义清晰:下标参数含义不明确时,建议使用带标签的参数;
- 读写分离:只读场景优先使用只读下标,减少不必要的可变性;
- 与属性区分:下标用于按索引访问,普通属性用于描述对象状态,二者职责不同。
11. 总结
Swift 下标是一种让类型支持方括号访问的语法机制,既可以是只读的,也可以是读写的;既支持多参数、带标签参数,也支持类型下标、协议要求和泛型结合。合理使用下标,可以让自定义类型的使用体验更接近原生集合,代码更简洁、更符合直觉。