关于数组和字典的下标不再说了,下面举例说明类型的下标定义和使用
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"
下标像一个方法,参数是下标值,返回值是下标对应的值。上例的subscript的函数体实际是一个get方法,因为没有set方法,所以省略了,所以是一个只读下标定义。
与数组和字典不同,类型的下标可以是多个值,像函数的多个参数,类型可以随意定义,返回值也可以是多个值,下例是一个类型下标的应用实例
struct Matrix {
let rows: Int, columns: Int
var grid: Double[]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
//初始化了一个全0.0的二维数组,但是用一维表示的
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")
//(row * columns) + column表示了该元素在一维数组中的位置,返回该元素的值
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
//(row * columns) + column表示了该元素在一维数组中的位置,然后赋予新值
grid[(row * columns) + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
//赋值后变为下面的2*2数组
/*
0.0 1.5
3.2 0.0
*/
let someValue = matrix[2, 2]
//(2,2)是越界的