Confused about matrix and subscript results

Hi,

I have this code below and I don't understand the results I am getting and why...

struct Grid {
    let grid = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16],
    ]
    
    subscript(row: Int, col: Int) -> Int? {
        let number = grid[col][row]
        return number
    }
}

var test = Grid()
test[3, 2] // results in 12


let grid2 = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],
]

grid2[0][1] // results in 2

var grid3: [[Int]] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

grid3[1][2]

First grid results in 12 as intended, but I don't understand why.
Why doesn't test[3, 2] select object nr 3 in this array and value nr 2? Instead it works as column/row selection.

But in grid2, grid2[0][1] selects object nr 0 and value nr 1, which is different to the first example.

I hope you get my point. :blush:

let number = grid[col][row]

col and row are flipped there. Try…

let number = grid[row][col]

And rest your weary eyes :face_with_monocle:

3 Likes

If you write that the lines ([1, 2, 3, 4], etc) are "columns" rather than "rows", so you are selecting column 2's row 3. And if the lines are "rows" access them with grid[row][col].