下標(biāo)(subscript)
使用subscript可以給任意類型(枚舉勺拣、結(jié)構(gòu)體、類)增加下標(biāo)功能垦细,有些地方也翻譯為:下標(biāo)腳本
subscript的語(yǔ)法類似于實(shí)例方法捺典、計(jì)算屬性,本質(zhì)就是方法(函數(shù))
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) // 11.1
print(p.y) // 22.2
print(p[0]) // 11.1
print(p[1]) // 22.2
- subscript中定義的返回值類型決定了
□ get方法的返回值類型 □ set方法中newValue的類型
- subscript可以接受多個(gè)參數(shù)大州,并且類型任意
下標(biāo)的細(xì)節(jié)1
- subscript可以沒(méi)有set方法续语,但必須要有g(shù)et方法
class Point {
var x = 0.0, y = 0.0
subscript(index: Int) -> Double {
get {
if index == 0 {
return x
} else if index == 1 {
return y
}
return 0
}
}
}
- 如果只有g(shù)et方法,可以省略get
class Point {
var x = 0.0, y = 0.0
subscript(index: Int) -> Double {
if index == 0 {
return x
} else if index == 1 {
return y
}
return 0
}
}
下標(biāo)的細(xì)節(jié)2
- 可以設(shè)置參數(shù)標(biāo)簽
class Point {
var x = 0.0, y = 0.0
subscript(index i: Int) -> Double {
if i == 0 {
return x
} else if i == 1 {
return y
}
return 0
}
}
var p = Point()
p.y = 22.2
print(p[index: 1]) // 22.2
- 下標(biāo)可以是類型方法
class Sum {
static subscript(v1: Int, v2: Int) -> Int {
return v1 + v2
}
}
print(Sum[10, 20]) // 30
推導(dǎo)細(xì)節(jié):
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) // 11.1
print(p.y) // 22.2
print(p[0]) // 11.1
print(p[1]) // 22.2
斷點(diǎn)22 查看匯編分析:
結(jié)構(gòu)體摧茴、類作為返回值對(duì)比
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 = 22
// Point(x: 11, y: 22)
print(pm[0])
// Point(x: 11, y: 22)
print(pm.point)
struct Point {
var x = 0, y = 0
}
class PointManager {
var point = Point()
subscript(index: Int) -> Point {
// set { point = newValue }
get { point }
}
}
var pm = PointManager() // 如果不寫(xiě)set方法是會(huì)報(bào)錯(cuò)的
pm[0].x = 11 Cannot assign to property: subscript is get-only
pm[0].y = 22 Cannot assign to property: subscript is get-only
pm[0].x = 11 等價(jià)于 pm[0] = Point(x: 11, y: pm[0].y)
返回值類型時(shí)候绵载,如果是struct修飾,需要寫(xiě)set方法苛白。如果是類類型修飾(修改指針指向空間)娃豹,需要set方法。
接受多個(gè)參數(shù)的下標(biāo)
class Grid {
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 grid = Grid()
grid[0, 1] = 77
grid[1, 2] = 88
grid[2, 0] = 99
print(grid.data)