6️⃣Loops

Fall 2023 | Vin Bui

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.

Looping over a fixed number of times

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.

for i in 1...10 {
    print(i)
}

In a couple of these examples, we used i as the loop variable. This is a common convention used by programmers, but we can name it whatever we want.

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.

for _ in 1...10 {
    print("Hello Vin and Richie")
}

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.

for _ in 1..<10 {
    print("Hello Vin and Richie")
}

The print statement is very useful for debugging purposes. The user will not be seeing the output when using the app. It is only for the programmer.

Looping over arrays

Swift provides a nice way to loop over the elements of an array using the for-in loop.

var staff = ["Vin", "Richie", "Tiffany", "Jennifer", "Antoinette", "Elvis"]
for person in staff {
    print(person)
}

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:

var staff = ["Vin", "Richie", "Tiffany", "Jennifer", "Antoinette", "Elvis"]
for i in 0..<staff.count {
    print(staff[i])
}

We can also nest for loops inside of other for loops!

While Loops

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.

var i = 0
while i < 10 {
    print(i)
    i += 1
}

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:

var i = 0
while i < 10 {
    print(i)
    // i += 1 commented out
}

We can use break or continue to stop/continue the loop but we it is not recommended.

Last updated