How to LOOP over arrays in Swift?
Prerequisites
Please make sure you watch first the following prerequisite videos:
So how can we loop over an array in Swift? Let’s discuss…
First of all, looping is a term describing the execution of a piece of code for each and every element in an array. The trick here is to write this piece of code one time, and let the processor deal with executing it, repeatedly, for each element in the array. And there are a few different ways we can achieve this.
The most common way to loop over an array is with a for-loop. It executes a closure for each element in the array, in sequential order. The closure is enclosed in curly brackets. Inside this closure, we get access to one element from the array, but each time it is a different element. Keep in mind this closure is written only once, but executed multiple times, one time for each element in the array.
Another way of looping over an array is to call the forEach function on the array itself. This function takes a very similar closure and the result is identical. A printout of all the elements in the array. The difference is that inside this forEach closure we cannot use statements like break and continue.
There is a third way to loop over an array, using once again a for-loop, not over the elements of the array, but rather over the array’s indices. And in this case, in order to access each element in the array, we need to use the index we get each time the closure is executed. The result will be identical.
A final way to do looping over arrays deals with looping over something called an enumerated sequence. This is a sequence of pairs, and each pair contains an index and an array element. Which means inside our loop closure, we get access to both of these at the same time.
And there you have it: looping over arrays in 4 different ways. The most common is the for-loop, of course, so familiar to all programming languages. But there are a few other ways, like the forEach function that arrays can execute, for-loops over the indices of an array instead of over the elements themselves, and the rarely used loop of an enumerated sequence of pairs, where each pair contains and index and the element at that index.