子脚本 (Subscripts)
定义在类、结构体和枚举中,表示访问对象、集合或序列的快捷方式,不需要再调用实例的特定的赋值和访问方法
定义在类、结构体和枚举中,表示访问对象、集合或序列的快捷方式,不需要再调用实例的特定的赋值和访问方法
1.语法
子脚本允许通过在实例后面的方括号传入一个或多个索引值来对实例进行访问和操作,使用 subscript 关键字,显示声明传入的参数和返回的类型//newValue的类型必须和脚本定义的返回类型相同
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
// 如果是只读属性,就是只有getter方法,那原get代码块可直接写在subscript中
subscript(index: Int) -> Int {
// return an appropriate subscript value here
}
//以下例子定义一个结构体,用来展示传入整数的n倍
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
println("six times three is \(threeTimesTable[6])")
// prints "six times three is 18"
2.用法
通常用来访问集合,列表或序列中的元素var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2
3.选项
子脚本允许任意数量的参数,并且参数类型没有限制,一个类或结构体可使用多个子脚本的实现,根据传入的参数进行区分,称为子脚本的重载struct Matrix {
let rows: Int, columns: Int
var grid: Double[]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
let someValue = matrix[2, 2]
// this triggers an assert, because [2, 2] is outside of the matrix bounds