Swift Arrays: Multidimensional
Swift Arrays: Multidimensional
Use nested arrays to represent 2D (or higher) structures such as matrices and grids.
2D Arrays
Store rows as arrays inside an outer array, then index as grid[row][col] to access items.
Example
var grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(grid[0][1]) // 2
for row in grid {
print(row)
}
Update a Cell
Change a value by indexing into the specific row and column.
Example
var grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
grid[1][1] = 99
print(grid[1]) // [4, 99, 6]
print(grid[1][1]) // 99