Most Common Mistake with Arrays in Swift
Prerequisites
Please make sure you watch first the following prerequisite videos:
So what is the most common mistake when working with arrays? Let’s discuss…
The problem most beginner programers have is the fact the arrays are value-type in Swift, and not reference-type. But what does it mean, exactly?
It means that we need to be careful when assigning elements from an array to separate variables. Their values get copied, not referenced. So, in this example, when we assign the element at index 1 to a new variable, let’s call it element, the new variable gets a copy of the element at index 1.
Now when we change the variable’s value, its value gets changed indeed, but the original array element at index 1 is not changed at all. In order to fix this, we need to change the element in the array directly, and not just a copy of it.
This is easy to remember, but most of the time we work with arrays of complex elements. Let’s consider this example: an array called people, an array of a custom struct of our own called Person. And let’s have a function somewhere that takes a single Person struct, and returns some status (another custom struct), by fetching it from the internet.
If we loop over the indices of the array like this, we will have a bug. That’s because each time the loop body is executed, we will have a person variable that will be a copy of an array element, and not a reference to the original element in the array. When we change this person’s status, the copy will be changed, but the original array will remain unchanged.
So this last line of code will need to be changed. There is no point in changing the copy. We will need to change the original element in the array instead, based on its index. So people[index].status gets a new status for that person.
And there you have it. Avoid this common mistake when working with arrays in Swift, a mistake that stems from the fact that arrays are value-type. When looping over arrays, remember that assigning an element to a new variable makes a copy of that element, so changing that copy alone will not do any good. We need to remember to update directly each element in the array, and thus staying bug-free.