下标(subscript)
使用subscript可以给任意类型(枚举、结构体、类)增加下标功能,有些地方也称为下标脚本。
subscript的语法类似于实例方法、计算属性、本质就是方法(函数)
class Point {
var x = 0.0, y = 0.0
subscript(index: Int) -> Double {
set {
if index == 0 {
x = newValue
} else if index == 1 {
y = newValue
}
}
get {
if index == 0 {
return x
} else if index == 1 {
return y
}
return 0
}
}
}
var p = Point()
p[0] = 11.1
p[1] = 22.2
print(p.x)
print(p.y)
print(p[0])
print(p[1])
subscript中定义的返回值类型决定了
get方法的返回值。set方法中newValue的值
subscript可以接受多个参数,并且类型任意。subscript可以没有set方法,但必须要有get方法。- 如果只有
get方法, 可能省略get subscript可以设置参数标签。(其中,参数标签不能省略)
class Point {
var x = 0.0, y = 0.0
subscript(index i: Int) -> Double {
set {
if i == 0 {
x = newValue
} else if i == 1 {
y = newValue
}
}
get {
if i == 0 {
return x
} else if i == 1 {
return y
}
return 0
}
}
}
var p = Point()
p[index:0] = 11.1
p[index:1] = 22.2
print(p.x)
print(p.y)
print(p[index: 0])
print(p[index: 1])
- 下标也可以是类型方法:
class Sum {
static subscript(v1: Int, v2: Int) -> Int {
return v1 + v2
}
}
print(Sum[10, 20])
结构体、类作为返回值的对比
- 结构体:覆盖原有的内存
struct Point {
var x = 0, y = 0
}
class PointManager {
var point = Point()
subscript(index: Int) -> Point {
set {
point = newValue
}
get {
point
}
}
}
var pm = PointManager()
// Point(x:11, y: 22)
pm[0].x = 11
// Point(x:11, y: 12)
pm[0].y = 12
print(pm[0].x)
print(pm[0].y)
- 类: 拿到指针地址进行赋值
class Point {
var x = 0, y = 0
}
class PointManager {
var point = Point()
subscript(index: Int) -> Point {
get {
point
}
}
}
var pm = PointManager()
pm[0].x = 11
pm[0].y = 12
print(pm[0].x)
print(pm[0].y)
接收多个参数的下标
class Gird {
var data = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
];
subscript(row: Int, column: Int) -> Int {
set {
guard row >= 0 && row < 3 && column >= 0 && column < 3 else {
return
}
data[row][column] = newValue;
}
get {
guard row >= 0 && row < 3 && column >= 0 && column < 3 else {
return 0
}
return data[row][column]
}
}
}
var gird = Gird()
gird[0,1] = 77
gird[1,2] = 88
print(gird.data)