Working with Multidimensional Arrays
You learned an array is just a sequence of values and that the values must share the same data type. For instance, you may have an array that contains test scores.
var testScores = [ 50.0, 98.5, 26.0, 78.5]
You previously learned that each element of the array is found at a specific index. The first index is zero.
print(testScores[0]) // prints 50.0
A multidimensional array expands the array to contain both rows and columns. Now, instead of an array containing the scores for one person, it can now contain the test scores for the entire class.
var testScores = [
[ 50.0, 98.5, 26.0, 78.5],
[ 21.0, 84.0, 77.0, 99.0],
[ 88.2, 82.0, 92.0, 80.0],
]
You can see see that there are multiple arrays separated by commas as well as contained by brackets. Each array is seated at its on index starting at zero. This means the first array is at the zero index, the second is at the first index, and the third is at the second index.
To access a value, you provide two brackets.
print(testScores[0,0]) // 50.0
print(testScores[1,3]) // 99.0
print(testScores[2,0]) // 88.2
You can keep expanding your arrays to add additional dimensions. For now, just stick with two. Additional dimensions add complexity and it is easy to become confused.
Looping through arrays in SwiftUI
Earlier in the course, you learned how to loop through an array using a regular for loop. This still works in plain old swift code, but in SwiftUI, you need to use the ForEach loop.
ForEach requires two things. First, it needs a range to loop through. Then you need to provide it an id. This id lets SwiftUI identify each iteration of the loop.
Here’s an example:
ForEach(0..<testScores.count, id: \.self) counter in {
}
In this case, the loop iterates through the size of the area. You will still need to manage the current position. This id allows SwiftUI to keep track of each iteration of the array.
Notice the counter variable. This variable keeps track of the current iteration in the loop. It’s called counter but you can call it anything you like. It’s just a temporary variable. After the loop, the variable is gone.