Home
Swift
2D Array Examples
This page was last reviewed on Aug 16, 2023.
Dot Net Perls
2D array. 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.
Shows a 2d array
Once created, we can access elements within our nested lists. Each position (X and Y) is accessed, and the cell's contents is returned.
Array
First example. This program creates a two-dimensional array of Ints. This is an array of arrays—each row can have a different length.
Part 1 We nest levels of brackets to indicate an array of arrays. This example shows the initializer syntax for a 2D array.
Part 2 Here we access 4 individual elements in the points array by specifying 2 separate indexes for each one.
Shows a 2d array
// 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-loop. Here 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.
Start We iterate with a for-loop over all indexes in the arrays. We nest the loops to access all elements.
for
Also We use print() to write data to the console with trailing newlines. We create a string for each line.
print
// 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, append. We 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.
Start We create two empty "row" arrays and append two elements each to them. Then we append those arrays to the "codes" array.
Tip If you are unsure how large the 2D array needs to be, using logic that appends rows dynamically is a good choice.
// 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"]]
3D array. 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.
Warning Often complex arrays like 3D arrays can be rewritten to use dictionaries. This approach can also be more efficient at runtime.
// 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
Subscript. 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.
Start We initialize the storage array to be 100 by 100 elements. We do this by appending arrays filled with zeros.
Next Subscript() accepts a row and column Int. We call the get and set accessors with two Int arguments (like a method).
Subscript
Finally We use the 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
Array of dictionaries. 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.
Array, Dictionary
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 16, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.