Loops
Fall 2023 | Vin Bui
Last updated
Was this helpful?
Fall 2023 | Vin Bui
Last updated
Was this helpful?
When we want to repeat a code a certain number of times in Swift, we can either copy and paste the code or even better, we can use loops. There are two main loops in Swift: a for loop and a while loop.
Let’s say we wanted to print out the numbers 1..10
. In Swift, we can use the closed range operator (...
) which is three periods in a row.
The variable i
is known as a loop variable which is a variable that lives within the scope and lifetime of the loop. For every iteration, the value of i
will change. Now, what if we didn’t need to use i
and just wanted to print "Hello Vin and Richie"
10 times? We could still use for i in 1...10
; however, it would be better to use an underscore (_
) instead.
Why is ...
called a closed range operator? Well, that’s because there is also an open range operator (..<
). The difference between these two is that the closed range operator is inclusive whereas the open range operator is not. The following code will only be executed 9 times. It goes up to but not including 10.
Swift provides a nice way to loop over the elements of an array using the for-in loop.
In this code, the loop variable is person
. For every iteration of this loop, the value of person
will be the value of every element inside of the array staff
, in order.
Instead of looping over the element of the array, we could have looped over the indices of the array. The following code is equivalent:
If we don’t know exactly how many times to repeat a block of code, but do know that we want to repeat it while a condition is true, then we can use a while loop.
The above code will print out the value of i
and increment the value of i
by 1 while i < 10
evaluates to true
.
However, be very careful when using while loops because we can create an infinite loop. In the code below, the value of i
never changes and will always be less than 10. In this case, there will be an infinite loop: