Loops In Swift

Loops are a fundamental concept in programming. They allow us to do repetitive tasks easily and in a readable manner.

In Swift we have the for-in with collections and ranges, the conditional while loop and repeat while loops.

Loops are a critical concept to understand for any developer.

For Loops With Ranges In Swift

The syntax for loops in Swift is not too difficult:

for n in 1...5 {
   print(n)
}

The above loop will print 1 to 5. For loops in Swift always have the for and in keyword. The above example uses a closed range, 1...5. Using a closed ranged like this allows us to run code a fixed number of times.

You can also use the range operator 1..<5. This will print 1 to 4.

To count by two or more, we can use stride:

for n in stride(from: 0, to: 10, by: 2) {
	print(n)
}

If you want stride to be inclusive of the last number, use the keyword through instead of to:

for n in stride(from: 0, through: 10, by: 20) {
	print(n)
}

To count backwards, use .reversed():

for n in (1...5).reversed() {
	print(n)
}

For Loops With Collections

For Loops With Arrays

You can loop over an array using the for in loop:

let names = ["Eddy", "Jen", "Angela", "Arthur", "Matthew"] 
for name in names {
    print(name)
}

The above example will just print all the names out. This is a really simple example, however we can do something more useful with for loops.

Let’s say we have an array of student scores and we need to find the average. First we need to calculate the sum:

let scores = [80.9, 90.9, 75.5, 71.2, 65.0] 
for score in scores {
    var sum = 0.0
    sum = sum + score
}
print(sum)

The above code has a couple of errors. First off, since we define the var sum inside our for loop, it cannot be accessed outside of the for loop (outside of the curly brackets {}).

Let’s move the sum variable declaration outside:

var sum = 0.0
let scores = [80.9, 90.9, 75.5, 71.2, 65.0] 
for score in scores {
    sum = sum + score
}
print(sum)

We can also simplify sum = sum + score to just sum += score. Finally, let’s divide the sum by the count of scores to get the average.

var sum = 0.0
let scores = [80.9, 90.9, 75.5, 71.2, 65.0] 
for score in scores {
    sum += score
}
print(sum/Double(scores.count))

Note that I had to cast scores.count into a Double, since we cannot divide a Double by an Int.

Using Array Indices

Another way to solve the above problem is to use array indices. This usually isn’t recommended as it’s harder to read and can possibly introduce a Index out of range error if done incorrectly.

To use array indices simply use a closed ranged for loop with the end of the range being the array count.

for i in 0..<scores.count {
    sum += scores[i]
}

Be sure to use the ..< operator here and to start from 0. Arrays indices start at 0.

Enumeration

What if we want to access both the array index and the value of the array? Luckily Swift comes with a built in function to do this, it’s called enumeration:

let scores: [Double] = [80.9, 90.9, 75.5, 71.2, 65.0]
for (i, score) in scores.enumerated() {
    print("\(i): \(score)")
}

This outputs:

0: 80.9
1: 90.9
2: 75.5
3: 71.2
4: 65.0

The function enumerated() puts the index in the variable i and the value in the variable score. This is useful when you need to know both the index and the value.

Example

So how would you use loops in a real-world example? Let’s say the user has entered some invalid data and we need to disable all the buttons on the screen.

Here’s a way we could do it with loops:

var buttons = [nextButton, backButton, moreInfoButton]
for button in buttons {
    button.isEnabled = false
}

For Loop With Dictionaries

You can also use for loops to loop through keys and values in dictionaries.

let ages = ["Eddy": 25, "Angela": 27, "Arthur": 28, "Ben": 22] 
for (name, age) in ages {
    print("\(name) is \(age)")
}

This results in:

Arthur is 28
Angela is 27
Eddy is 25
Ben is 22

Conditional While Loops

While Loops

While loops are great for loops that need to run until a certain condition is met. The syntax is simple:

var n = 0
while n < 10 {
    print(n)
}

The above loop will compile, however there is a huge problem with it. It never terminates! That means the loop will run forever until your computer crashes.

It is never a good idea to run a loop that won’t end. This will cause your app to stall or worse, crash.

We can fix the loop by adding one to n in each iteration:

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

Note that although in the above example we are comparing integers, while loops can have any kind of condition:

while (someCondition == true) {
    // do stuff
}

Repeat While Loops

There’s one other syntax for conditional loops and that’s the repeat while loops. They work almost exactly the same, except that the condition is checked after the loop has run.

repeat {
    // do stuff
} while (someCondition == true)

Note that repeat while loops always run at least once.

Higher Order Functions Instead Of Loops

Although loops are a great way of doing repetitive tasks, there are higher order functions such as map, filter and reduce.

These higher order functions allow us to perform tasks with less code and in an efficient manner. They are an alternative to using loops in certain cases.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts