Another important function in Swift programming is “For”. The goal of this function is to iterate over a range of numbers, characters in a strings or values in an array.
So let’s first use the “for” function in an array.
Basically, we created a variable “pet” that will pick each value from the array “animals” and then we output the value of the variable “pet”. And the function “for” will move from array index to another.
We can also move by 2, so for example, only get the values of the 1st item, then the 3rd, the fifth and so on. To do so, we need to use the “stride” function.
The stride function
So let’s take a look and explain what we just did
So we created a variable “i” that will increase (“stride“) from the value of 0 until it reaches the size of our array animals (animals.count), and we have decided to increment the “i” value by 2 each time.
Another way that we can iterate an array would be to use the 3 points “…” which indicates the beginning and the ending of the iteration. We use “animals.count-1” because an array start at the index 0 (Swift: Arrays). So the number of values in an array will always be higher by 1 with respect to the index of the last value.
So you are probably wondering now, how do you decrease the value? Well, we use the “.reversed()” function
The reversed function
Using the reversed function will allow us to output the values from the last to first.