-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubscript implementation
45 lines (37 loc) · 1.17 KB
/
subscript implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// subscript implementation
struct multiple{
var num: Int = 1
subscript(index: Int) -> Int{
return index * num
}
}
var newTable = multiple(num: 3)
print("3 six times is: \(newTable[6]) ")
// subscript options
struct Matrix{
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int){
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func isIndexValid(row: Int, column: Int) -> Bool{
return rows >= 0 && row < rows && columns >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get{
assert(isIndexValid(row: row, column: column), "the index is out of range")
return grid[(row * column) + column]
}
set{
assert(isIndexValid(row: row, column: column), "the index is out of range")
grid[(row * column) + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 3)
matrix[0,1] = 1.5
matrix[1,0] = 1.3
// An assertion is triggered if you try to access a subscript that’s outside of the matrix bounds:
// let someMatrix = matrix[2,2]