Swift 3 2d Int Array

This is actually a very simple question, but after an hour I can’t solve my problem.

I need to create a 2d array of Int.

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

tried to change the value:

 arr[x][y] = 1 

fatal error: index out of range

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

I'm confused..

+6
source share
3 answers

It is not simple. Line:

 var arr : [[Int]] = [] 

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

Let's go back to one array:

 var row : [Int] = [] 

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

 row[6] = 10 

First you need to add 7 values ​​to the array before you can access the value at index 6 (7th value).

With an array of arrays, you need to populate the external array with a whole set of internal arrays. And each of these internal arrays must be filled with an appropriate number of values.

Here is one simple way to initialize an array of arrays, assuming you want a pre-populated matrix with each value set to 0.

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

The external counter represents the number of rows, and the internal counter represents the number of columns. Adjust each as necessary.

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 
+17
source

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 // a == [1, 0, 0, 0...] 

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) 
+1
source

Use a dictionary instead of an array.

According to your requirement, you can use arrayOfDict or dictOfDict. With a fast 4 forward, we can set a default value.

 var arrayOfDict = [[Int: Int]]() arrayOfDict[i][j, default: 0] arrayOfDict[i][j] = 0 var dictOfDict = [Int: [Int: Int]]() dictOfDict[i, default: [0: 0]][j, default: 0] dictOfDict[i][j] = 0 
0
source

All Articles