// * * * * * Subscript * * * * *
// similar to subscript to Array, Dictionary, Class/Struct/Enum can have too
// ???? what's the diff from function, I can replace subscript with func
struct IcanMultiply {
var base:Int
subscript(number:Int) ->Int{
return number *base
}
}
var someInt = IcanMultiply(base:3)
someInt[4]
struct Matrix {
let rows,columns :Int
var grid : [Double]
init(row:Int,column:Int){
rows = row
columns = column
grid = Array(repeating:0.0,count:row*column)
}
func isValidIndex(row:Int,column:Int) ->Bool{
return row>=0&&row<rows&&column>=0&&column<columns
}
subscript(row:Int,column:Int) ->Double{
get{
assert(isValidIndex(row: row, column: column),"index out bound")
return grid[row*columns+column]
}
set{
assert(isValidIndex(row: row, column: column),"index out bound")
grid[row*columns+column]=newValue
}
}
}
var someMatrix = Matrix(row:2, column: 2)
print(someMatrix.grid.count)
print(someMatrix.grid[0])
print(someMatrix[0,0])
//print(someMatrix[2,2])//assertion failed: index out bound:
someMatrix[0,0]=2.8
print(someMatrix[0,0])
when you using Subscript/Computed property, the getter and setter are used only when getting the value from the property or setting the value for the property, they will not be called in the same time. so there is no orderring problem.