Reputation: 163
I want to change subscript coordinates in an Array of Arrays [[Int]] in order to be able to address each value in a way similar to a spreadsheet, so assigning values, formulas across cells, etc.
Currently to address each value I need to subscript like table[2][1] = 12 or similar. I would like to subscript like a spreadsheet table[a][2] = 12, so that I can adapt long and complicated formulas in bigger speadsheets to similar tables using the same system used in spreadsheets.
The question is: how to change the subscript system in an efficient way? I send a simplified example to ilustrate the point
class ViewController: UIViewController {
var table = [[0, 1, 2, 3],
[1, 32, 44, 25],
[2, 12, 66, 43],
[3, 3, 4, 5]]
override func viewDidLoad() {
super.viewDidLoad()
print(table[2][1]) // 12
table[1][1] = 100
table[3][3] = table[1][1] * table[3][1] * 10
print(table[3][3])
printArray(table: table, j: 3)
}
// MARK: - Function
func printArray(table: [[Int]], j:Int) {
for i in 0...j {
print(table[i])
}
}
}
Upvotes: 0
Views: 380
Reputation: 10199
The closest solution I found is to use enums, like here:
enum Column:Int {
case a
case b
case c
// and so on
}
extension Array {
subscript(col:Column) -> Element {
get {
return self[col.rawValue]
}
set(newValue) {
self[col.rawValue] = newValue
}
}
}
var table = [[0, 1, 2, 3],
[1, 32, 44, 25],
[2, 12, 66, 43],
[3, 3, 4, 5]]
table[.a][2] = 12
let val = table[.a][2]
print (val)
Nevertheless, there are two little drawbacks:
Column
enum.table[5][.c]
and table[.a][.b]
will also be allowed - so you could access the rows via letter, not only the columnsUpvotes: 2