- 输入参数能够为任意类型,Subscripts 能够返回任意类型
- 能够使用多变参数,但是不能使用输入输出参数和默认参数值
- 一个类和结构体能够提供许多下标实现
- 定义多个 Subcripts 被称为 Subscripts overloading
// 和计算属性用法相似
subscript(index: Int) -> Int {
get {
}
set(newValue) {
}
}
Usage
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
Dictionary
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2
numberOfLegs["spider"] = nil // 移除 key
numberOfLegs["bird"] // return Optional
Multiple Parameter
struct Martix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsVaild(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && rolumn >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsVaild(row: row, colum: colum), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsVaild(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
网友评论