《从零开始学Swift》学习笔记(Day 46)——下标重写
原创文章,欢迎转载。转载请注明:关东升的博客
下标是一种特殊属性。子类属性重写是重写属性的getter和setter访问器,对下标的重写也是重写下标的getter和setter访问器。
下面看一个示例:
class DoubleDimensionalArray {
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)
}
subscript(row: Int, col: Int) -> Int { //定义下标
get {
return grid[(row * columns) + col]
}
set {
grid[(row * columns) + col] = newValue
}
} //定义下标
}
class SquareMatrix: DoubleDimensionalArray {
override subscript(row: Int, col: Int) -> Int { //重写父类下标
get {
return super.grid[(row * columns) + col]
}
set {
super.grid[(row * columns) + col] = newValue * newValue
}
}
}
var ary2 = SquareMatrix(rows: 5, columns: 5)
for var i = 0; i < 5; i++ {
for var j = 0; j < 5; j++ {
ary2[i,j] = i + j
}
}
for var i = 0; i < 5; i++ {
for var j = 0; j < 5; j++ {
print("\t\t \(ary2[i,j])")
}
print("\n")
}
其中super.grid[(row * columns) + col]语句中使用super调用父类的grid属性。
其中super.grid[(row * columns) + col] = newValue * newValue语句是给父类的grid属性赋值。