classDoubleDimensionalArray { 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屬性賦值