原創(chuàng)文章鸠澈,歡迎轉(zhuǎn)載柱告。轉(zhuǎn)載請注明:關(guān)東升的博客
下標(biāo)是一種特殊屬性。子類屬性重寫是重寫屬性的getter和setter訪問器笑陈,對下標(biāo)的重寫也是重寫下標(biāo)的getter和setter訪問器际度。
下面看一個(gè)示例:
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 {?//定義下標(biāo)
???????
??????? get {
??????????? return grid[(row * columns) + col]
??????? }???????
??????? set {
??????????? grid[(row * columns) + col] = newValue
??????? }
??? }????????//定義下標(biāo)???
}
class SquareMatrix: DoubleDimensionalArray {???
??? override subscript(row: Int, col: Int) -> Int {?//重寫父類下標(biāo)???????
??????? 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調(diào)用父類的grid屬性。
其中super.grid[(row * columns) + col] = newValue * newValue語句是給父類的grid屬性賦值涵妥。