Learn Courses My Dashboard

2 dimensionat arrays

Can someone explain how to declare a 2 dimensional array and how to populate a few entries. Google was not useful.

A two-dimensional array is just an Array of Arrays:

let arr: [[Int]] = [[0,1,2], [10,20,30], [200,300,400]]
print(arr[1][0]) //10

An intriguing alternative is this Matrix struct given in the Swift Language Guide:

struct Matrix {
    let rows: Int, columns: Int
    var grid: [Double]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: 0.0, count: rows * columns)
    }
    func indexIsValid(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Double {
        get {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

You access its elements like so:

matrix[0, 1] = 1.5
matrix[1, 0] = 3.2