Not only should you initialize both the array and the subarrays before you can assign any values, but also each length of the array must be greater than the index position you are trying to set.
This is because Swift does not initialize Subarrays for you, and does not increase the length of the array when assigning the index.
For example, the following code will not be executed:
var a = [Int]() a[0] = 1 // fatal error: Index out of range
Instead, you can initialize the array with the number of elements you want to hold, filling it with the default value, for example, zero:
var a = Array(repeating: 0, count: 100) a[0] = 1
To create a matrix from 100 to 100, initialized to 0 values:
var a = Array(repeating: Array(repeating: 0, count: 100), count: 100) a[0][0] = 1
If you do not want to specify the initial size for your matrix, you can do this as follows:
var a = [[Int]]() a.append([]) a[0].append(1)
source share