With special syntax in Swift, we create multidimensional arrays. We nest brackets—2 or more levels of nesting can be used. An initialization syntax is also available.
Once created, we can access elements within our nested lists. Each position (X and Y) is accessed, and the cell's contents is returned.
This program creates a two-dimensional array of Ints. This is an array of arrays—each row can have a different length.
// Part 1: create a two-dimensional array with nested brackets. let points: [[Int]] = [[10, 20], [30, 40]] // Part 2: access all individual elements. print(points[0][0]) print(points[0][1]) print(points[1][0]) print(points[1][1])10 20 30 40
For
-loopHere we see a loop over a 2D array. This is a jagged array, but it uses the same syntax as a rectangular one—they are the same.
for
-loop over all indexes in the arrays. We nest the loops to access all elements.print()
to write data to the console with trailing newlines. We create a string
for each line.// Create a constant, jagged array. let units: [[Int]] = [[100, 200, 300], [400, 500], [600]] // Loop over array and all nested arrays. for x in 0..<units.count { var line = "" for y in 0..<units[x].count { line += String(units[x][y]) line += " " } print(line) }100 200 300 400 500 600
String
array, appendWe can create an empty 2D array and append subarrays to it. This approach is more versatile at creation-time. Here we create a dynamic 2D string
array.
// An empty 2D string array. var codes = [[String]]() // Create first string array. // ... Append it to the codes 2D array. var row1 = [String]() row1.append("C1") row1.append("A1") codes.append(row1) // Create the second string array row. var row2 = [String]() row2.append("T2") row2.append("S2") codes.append(row2) // Display our 2D string array. print(codes)[["C1", "A1"], ["T2", "S2"]]
Swift supports 3D arrays in the same way as 2D arrays. We nest square brackets in the type. Here we create a three-dimensional array of Ints.
// Create a three-dimensional array. // ... The outer array contains two arrays. // ... Those two arrays both contain two arrays. // ... The inner arrays have two values each. let parts: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] for a in 0..<parts.count { // Print index of first dimension. print("Outer = \(a)") // Display inner two arrays. for b in 0..<parts[a].count { var line = "" for c in 0..<parts[a][b].count { line += String(parts[a][b][c]) } print(line) } print("") }Outer = 0 12 34 Outer = 1 56 78
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.
Subscript()
accepts a row and column Int
. We call the get and set accessors with two Int
arguments (like a method).WorldMap
class
and its subscript function. We set values in the storage array and then read them.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
An array of dictionaries uses syntax similar to that of a 2D array. We use nested square brackets. A dictionary provides more versatility in lookups.
Often 2D data structures can be represented in other ways—with dictionaries or sparse arrays. The best (fastest) approach depends on the program and its data.