๐ŸŽ“ A1Learner
๐Ÿ”

Swift Nested Arrays

A nested array is an array whose values are themselves arrays. Rows of a grid fit this shape well, with one inner array per row.

A grid stored as arrays inside an array

The outer brackets hold two inner arrays. Printing the whole grid shows both rows in one line.

let grid = [[1, 2, 3], [4, 5, 6]]
print(grid)
print(grid.count)
print(grid[0].count)

Reading one cell with two indexes

The two reads here pick the first value of the first row and the last value of the second row. Each read prints a single number.

let grid = [[1, 2, 3], [4, 5, 6]]
print(grid[0][0])
print(grid[1][2])

Printing a grid row by row

Printing the row on each pass shows its values as a list on one line. Three passes give three lines for the three rows.

let grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in grid {
    print(row)
}

Adding up each row with nested loops

The outer loop takes one row at a time. The inner loop adds every value in that row to a row total.

let grid = [[1, 2, 3], [10, 20]]
for row in grid {
    var total = 0
    for value in row {
        total += value
    }
    print(total)
}

Example

let grid = [[2, 4], [6, 8], [10, 12]]
print(grid[2][1])
var total = 0
for value in grid[1] {
    total += value
}
print(total)
print(grid.count)

Key points

  • Each inner array is one value inside the outer array.
  • Write a nested array with an array literal inside another array literal.
  • Use .count on the outer array to count its inner arrays.
  • Use .count on one inner array to count the values in that row.
  • Two indexes written one after the other pick a single value, the row index first.

In this example, the first line stores a grid with three rows of two numbers. The second line prints the value at row 2, column 1, which is 12. The loop then adds the values of row 1, 6 and 8, into total. The next line prints total as 14, and the last line prints the count of rows as 3.

Note

Every inner array in a grid can hold a different number of values.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

A grid holds [[1, 2], [3, 4]]. What does grid[1][0] give?