- 下標簡單使用
struct TimesTable {
var muti = 1
subscript(index:Int) -> Int{
return index * muti
}
}
var timesTable = TimesTable(muti: 3)
print(timesTable[8])
複製代碼
- 下標用於訪問數組字典
- dict[key]?= nil是爲了賦值nil
- dict[key]= nil是爲了刪除key-value鍵值對
var dict = ["one": 1, "two": 2, "three": 3]
dict["four"] = 4
print(dict)
dict["three"] = nil
print(dict)
複製代碼
- 多個下標用法
- subscript支持子類重寫
class Matrix {
var rows: Int, cols:Int
var grid: [Double]
init(rows: Int, cols: Int) {
self.rows = rows
self.cols = cols
grid = Array(repeating: 0.0, count: rows * cols)
}
func isInRange(row: Int, col: Int) -> Bool {
return row >= 0 && row < self.rows && col >= 0 && col < self.cols
}
//subscript不存在類類型,支持子類重寫
subscript(row: Int, col: Int) -> Double {
get {
return grid[row * self.cols + col]
}
set {
grid[row * self.cols + col] = newValue
}
}
}
class Test: Matrix{
override subscript(row: Int, col: Int) -> Double {
get {
assert(isInRange(row: row, col: col),"越界")
return grid[row * self.cols + col]
}
set {
assert(isInRange(row: row, col: col),"越界")
grid[row * self.cols + col] = newValue
}
}
}
var a = Test(rows: 3, cols: 3)
a[0,0] = 1
a[0,2] = 2
a[2,0] = 3
a[2,2] = 4
print("a[2,0] = \(a[2,0])")
//a[2,0] = 3.0
複製代碼
- swift5.1新增類類型下標
- 一樣的static示例類型下標變成了類類型下標,並子類不能重寫父類。
- 一樣的class示例類型下標變成了類類型下標,並子類能重寫父類。
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
class subscript(n: Int) -> Planet {
return Planet(rawValue: n)!
}
}
let mars = Planet[4]
print(mars)
複製代碼