類(lèi)、結(jié)構(gòu)體、枚舉可以定義下標(biāo)
import UIKit
// 只讀下標(biāo)
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
console log 如下

只讀下標(biāo).png
下標(biāo)實(shí)例
// 下標(biāo)實(shí)例
struct Matrix {
let rows:Int, columns: Int
var grid: [Int]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < self.rows && column >= 0 && column < self.columns
}
subscript(row: Int, column: Int) -> Int {
get {
assert(indexIsValid(row, column: column), "Index out of range")
return grid[row * columns + column]
}
set {
assert(indexIsValid(row, column: column), "Index out of range")
grid[row * columns + column] = newValue
}
}
}
var matrix = Matrix(rows: 3, columns: 3)
matrix[0, 0] = 1992
matrix[1, 1] = 85
matrix[2, 2] = 520
let someValue = matrix[0, 2]
print("第一行第三列值是\(someValue)")
print("三行三列值")
var tempIndex = 0
for indexValue in matrix.grid {
tempIndex += 1
print("\(indexValue)", terminator: "")
if tempIndex % 3 == 0 {
print("")
} else {
print(",", terminator: "")
}
}
console log 如下

下標(biāo)實(shí)例.png