Mikhail Sein Mikhail Sein - 21 days ago 9
Swift Question

Swift 3 2d array of Int

It's actually a very simple question, but after an hour I can not solve my problem.

I need to create a 2d array of Int.

var arr = [[Int]]()
var arr : [[Int]] = []

tried to change value :

arr[x][y] = 1

fatal error: Index out of range

Should I use APPEND or I need specify the size of the array?

I'm confused..


It's not simple really. The line:

var arr : [[Int]] = []

Creates a variable of type Array of Array of Int and initially the array is empty. You need to populate this like any other other array in Swift.

Let's step back to a single array:

var row : [Int] = []

You now have an empty array. You can't just do:

row[6] = 10

You first have to add 7 values to the array before you can access the value at index 6 (the 7th value).

With your array of arrays, you need to fill in the outer array with a whole set of inner arrays. And each of those inner arrays need to be filled out with the proper number of values.

Here is one simple way to initialize your array of arrays assuming you want a pre-filled matrix with every value set to 0.

var matrix : [[Int]] = Array(repeating: Array(repeating: 0, count: 10), count: 10)

The outer count represents the number of rows and the inner count represents the number of columns. Adjust each as needed.

Now you can access any cell in the matrix:

matrix[x][y] = 1 // where x and y are from 0 to rows-1/columns-1