返回
Swift的下标(subscripts译文)
IOS
2023-09-12 03:00:44
数组和集合的访问
下标是一种使用数组、集合和序列成员元素的简洁方式,可以简化访问接口和复杂性。举个例子,若要访问数组中的元素,可以直接使用下标来访问:
var array = [1, 2, 3]
print(array[0]) // 输出 1
上述代码首先声明了一个数组array
,其中包含三个元素1、2和3,然后使用下标[0]
访问第一个元素,最后使用print()
函数输出结果1。
类型的多个下标
同一个类型可以定义多个下标,每个下标都针对不同的访问需求。例如,以下代码为Point
类型定义了两个下标:
struct Point {
var x: Int
var y: Int
subscript(index: Int) -> Int {
get {
switch index {
case 0: return x
case 1: return y
default: fatalError("Index out of bounds")
}
}
set {
switch index {
case 0: x = newValue
case 1: y = newValue
default: fatalError("Index out of bounds")
}
}
}
subscript(axis: String) -> Int {
get {
switch axis {
case "x": return x
case "y": return y
default: fatalError("Invalid axis")
}
}
set {
switch axis {
case "x": x = newValue
case "y": y = newValue
default: fatalError("Invalid axis")
}
}
}
}
上面的代码中,第一个下标[index:]
使用整数参数index
,可以访问或设置x
和y
的值,具体由index
的值决定。第二个下标[axis:]
使用字符串参数axis
,可以访问或设置x
和y
的值,具体由axis
的值决定。
参数名称和类型
下标的参数可以是任何类型,包括元组。例如,以下代码为Grid
类型定义了一个下标,该下标的参数是元组(Int, Int)
:
struct Grid {
var values: [[Int]]
subscript(row: Int, column: Int) -> Int {
get {
return values[row][column]
}
set {
values[row][column] = newValue
}
}
}
上面的代码中,下标[row:, column:]
的参数是元组(Int, Int)
,可以访问或设置Grid
中的任何元素。
getter和setter
下标可以具有getter
和setter
方法,以便能够读取和写入相应的值。例如,以下代码为Point
类型定义了一个只读下标,即它只具有getter
方法:
struct Point {
var x: Int
var y: Int
subscript(index: Int) -> Int {
get {
switch index {
case 0: return x
case 1: return y
default: fatalError("Index out of bounds")
}
}
}
}
上面的代码中,下标[index:]
只具有getter
方法,因此它只能用于读取x
和y
的值。
返回值类型
下标的返回值类型可以是任何类型,包括元组。例如,以下代码为Point
类型定义了一个下标,该下标的返回值类型是元组(Int, Int)
:
struct Point {
var x: Int
var y: Int
subscript(index: Int) -> (Int, Int) {
get {
switch index {
case 0: return (x, y)
default: fatalError("Index out of bounds")
}
}
}
}
上面的代码中,下标[index:]
的返回值类型是元组(Int, Int)
,因此它可以同时返回x
和y
的值。
更多使用示例:
- 获取
Array
的第一个元素:
let firstElement = array[0]
- 设置
Array
的第一个元素:
array[0] = 10
- 获取
Dictionary
的键为“name”的元素:
let name = dictionary["name"]
- 设置
Dictionary
的键为“name”的元素:
dictionary["name"] = "John"
- 获取
Set
中第一个元素:
let firstElement = set.first
- 向
Set
中添加元素:
set.insert("newElement")
- 从
Set
中删除元素:
set.remove("oldElement")