Sometimes accessing a 2D array can become confusing or inefficient. A subscript (as part of a class) can validate access to a 2D array with similar calling syntax.
class WorldMap {
var storage = [[Int]]()
init() {
// Create a 100 by 100 two-dimensional array.
// ... Use append calls.
for _ in 0..<100 {
var subArray = [Int]()
for _ in 0..<100 {
subArray.append(0)
}
storage.append(subArray)
}
}
subscript(row: Int, column: Int) -> Int {
get {
// This could validate arguments.
return storage[row][column]
}
set {
// This could also validate.
storage[row][column] = newValue
}
}
}
// Create our class and use its subscript.
// ... This modifies its two-dimensional Int array.
var world = WorldMap()
world[0, 5] = 100
// Set.
world[9, 9] = 120
world[99, 99] = world[0, 5]
print(world[0, 0])
// Get.
print(world[0, 5])
print(world[9, 9])
print(world[99, 99])
0
100
120
100