While Loops in Swift: A Complete Guide

In Swift, you can use a while loop to repeat actions as long as a condition is true.

For example, let’s use a while loop to calculate the sum from 0 to 10:

var sum = 0
var i = 0

while i <= 10 {
    sum = sum + i
    i = i + 1
}

print(sum)

Output:

55

Here the loop stops only after the value of i is greater than 10.

In this guide, you learn how to use a while loop.

In this chapter, you will also learn what is the difference between a for loop and a while loop.

More importantly, you learn when you should use a for loop and when to use a while loop.

Let’s jump in!

While Loops in Swift

In Swift programming, it is useful to be able to repeat actions as long as a condition is true.

For example, you can keep the mic recording as long as a user is holding down the recording button.

To repeat actions as far as a condition holds, you need to use a while loop.

Let’s start by taking a look at the syntax of the while loop in Swift.

Syntax

In Swift, the while loop follows this syntax:

while condition {
    // actions
    // update condition
}

In this code construct:

  1. The while keyword marks the beginning of a loop.
  2. condition is a boolean value that is either true or false.
  3. If the condition is true, the code inside of the curly brackets is executed.
  4. Inside the code block, the condition (or things that may affect the condition) is updated.
  5. When the condition becomes false, the loop ends.

That is enough for the theory.

To truly understand what you just saw, you need to see (and play with) some examples.

Example 1: Count Numbers with a While Loop

As a first example, let’s print numbers from 1 to 5 using a while loop:

var i = 1

while i <= 5 {
    print(i)
    i = i + 1
}

If you run this piece of code, you are going to see numbers from 1 to 5 being printed into the console:

1
2
3
4
5

The idea of this while loop is simple: Print the variable i and add 1 to it until the value reaches 5.

Let’s take a closer look at the while loop:

  • A variable i is created before the while loop. It is set to 1 because we want the numbers to start from 1.
  • The condition in this while loop is i <= 5. In other words, the loop continues as long as the variable i is less than or equal to 5.
  • Inside the for loop you:
    • Print the value of the variable i.
    • Increment i for the next iteration. If you don’t the loop would continue forever.

The last bullet point is important.

You need to update the condition inside the while loop.

Otherwise, the loop just continues forever.

Let’s talk about these infinite loops and what you can do to avoid them.

Infinite Loops in Swift

Updating the looping condition is important in a while loop.

If you forget to update the looping condition, you are going to face an endless loop that stalls your program.

This is because if the condition is always true, the loop does not know when to stop. Because of this, the loop continues forever.

For example, here is a classic example of an infinite loop in Swift:

var i = 1

while i <= 5 {
    print(i)
}

This code causes an endless loop because you forgot to update the value of i at the end of each iteration.

This causes the condition i <= 5 to always be 1 <= 5 which is always true.

If your app runs into code like this, it will crash as all the processing power goes to keep up the endless loop.

And no, your device is not going to break because of an endless loop. But encountering an infinite loop is frustrating for both the end-users and developers. So be careful not to cause one!

Let’s go back to while loops. In particular, let’s see another useful example.

Example 2: Skip Numbers with a While Loop

Let’s create a while loop that prints every 3rd number between 0 and 20.

Here is how it looks in code:

var i = 0

while i <= 20 {
    print(i)
    i = i + 3
}

Output:

0
3
6
9
12
15
18

Tip of the Day: Use a += b instead of a = a + b

In the while loop examples, you updated the counter variable like this:

i = i + 1

This expression increments the original value of variable i by 1.

However, because this is such a common operation to do, there is a shorthand for it.

It is called the addition assignment operator (+=).

As the name suggests, the addition assignment operator (+=) combines the addition (+) and the assignment (=) into a single operator.

Instead of writing i = i + 1, you can use the addition assignment operator like this:

i += 1

By the way, the same idea applies to all the other basic math operators in Swift.

For example:

i += 1 // adds 1 to the original value
i -= 1 // subtracts 1 from the original value.
i *= 2 // multiplies the original value by 2
i /= 2 // divides the original value by 2

Now that you have a basic understanding of while loops in Swift, let’s discuss the differences between for and while loops.

While Loop vs For Loop in Swift: Which One Should I Use?

Thus far you have seen a bunch of examples of while loops in Swift.

But so far, each task could have been accomplished using a for loop. Furthermore, a for loop would have been more intuitive and taken fewer lines of code.

So what is the difference? Why should you ever use a while loop?

The difference between a for loop and a while loop is:

  • For loop iterates over a predetermined range of values, such as from 0 to 10.
  • While loop iterates as long as a condition is true.

Also, all for loops can be written as while loops but not all while loops can be written as a for loop!

So which one should I use?

Loosely speaking, use a for loop as much as possible. Only use a while loop only if you cannot get the job done with a for loop.

  1. A for loop is “safer” than a while loop because there is no risk of an infinite loop.
  2. The for loops also tend to be shorter and more readable than while loops.

Before wrapping up, let’s move on to a less common variant of a while loop called the repeat-while loop.

Repeat-While Loops in Swift

Sometimes when looping, you want to perform an action at least once no matter what.

With a regular while loop, the loop statements are only executed if a condition is met.

However, there is a variant of a while loop called a repeat-while loop. This loop type lets you run the looping statements at least once before starting a while loop.

The syntax of a repeat-while loop is:

repeat {
   // actions
} while condition

The repeat block is always executed at least once, even if the condition is false, to begin with.

Let’s see an example.

var number = -5

repeat {
    print(number)
    number -= 10
} while (number > 0)

Output:

-5

Here the number is printed out even though the looping condition is false, to begin with.

If you used a regular while loop instead, the number would not be printed out:

var num = -5

while num > 0 {
    print(num)
    num -= 1
}

To take home, if you want to repeat a looping action at least once, use a repeat-while loop.

A repeat-while loop is not too common. But it belongs to the basics of Swift, so it had to be included in this series.

Thus far you have learned how to use a while loop to repeat code until a condition is no longer true.

You have also seen some basic examples.

In addition, you learned about the repeat-while loop that allows you to run looping statements at least once regardless of whether the condition is true or not.

Finally, let’s practice while looping with a bunch of useful examples.

Examples: While Loops in Action

The best way to learn is by examples.

Here are some demonstrative and useful examples of different scenarios of using a while loop in Swift.

Example 1: Condition with String Comparison

In the previous examples, the looping condition had to do with numbers.

However, the condition can be anything else as long as it evaluates to true or false.

For instance, let’s make the condition compare strings:

var label = "teen"
var age = 13

while label == "teen" {
    print("You are a teen")
    if age == 20 {
        label = "adult"
        print("You became an adult")
    }
    age += 1
}

Output:

You are a teen
You are a teen
You are a teen
You are a teen
You are a teen
You are a teen
You are a teen
You are a teen
You became an adult

Here the loop continues as long as the label is equal to “teen”.

Inside the loop:

  • We check if the age is 20.
  • If it is not, we increment the age by 1.
  • If the age is 20, we change the label to “adult”, which stops the entire loop.

This is an example of a while loop that cannot be converted into a for loop. This is because we are not looping through a range of values. Instead, we are looping as long as a condition is true.

Example 2: Compound Interest Calculator

Let’s build a compound interest calculator using a while loop.

Here is the investment info:

  1. The initial investment is $1500.00.
  2. The annual interest rate is 7%.
  3. In addition to this, you deposit $200.00 annually at the end of each compounding period.

The task is to calculate the amount of money the savings account has in 10 years.

Here is how it looks in the code:

// Info about the investment
let interest = 1.07
let yearly = 200.00
let nYears = 10

// Initial investment
var total = 1500.00

// Compound interest
var year = 1
while year <= 10 {
    total = 1.07 * total + yearly
    year += 1
}

print(total)

Output:

5714.016628190251

Example 3: Find a Target Number

This is a slightly more advanced example, but it greatly demonstrates how to use a while loop in a situation where you cannot use a for loop.

In this example, you have a target number 3 that you are searching for.

You use a random number generator to generate random numbers between 1 and 5 until you find the target number.

Here is how it looks in the code:

let target = 3
var targetFound = false

while !targetFound {
    let randomNumber = Int.random(in: 1...5)
    print("Random number is", randomNumber)

    if randomNumber == target {Next chapter: Functions in Swift
        targetFound = true
        print("Target number found!")
    }
}

Example output:

Random number is 4
Random number is 3
Target number found!

Let’s examine this piece of code:

  1. In the first line, we specify a target number of 3.
  2. In the second line, we create a boolean variable targetFound that tells whether we have found the target or not.
  3. In the fourth line, we start a while loop that runs until the target is found. The condition !targetFound means “not targetFound”, which means “not false”, which means “true”.
  4. Inside the loop, we generate a new random number and print it out.
  5. Then we check if the random number is the target.
    • If it is not, the loop continues.
    • But if it is the target, we set the targetFound to true, which turns !targetFound into false and stops the loop.

This completes the guide on while loops in Swift.

Conclusion

In this chapter, you learned what is a while loop in Swift.

To recap, a while loop lets you repeat code until a condition is no longer met.

This is different than a for loop, which always runs a predetermined number of iterations before stopping.

As a rule of thumb, prefer for loops over while loops. You should only use while loops if you cannot get the job done with a for loop.

Scroll to Top