Start learning free

LESSON 120 OF 415 · WHILE LOOPS & FOR LOOPS

The While Loop in Swift

Lesson Read the full explanation

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while condition {
	instruction1
	instruction2
	...
}

Let's check an example:

var count = 1
while count <= 5 {
	print("I made a mistake")
	count += 1
}
print("Finished!")

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 2

2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 3

3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 4

4. Fourth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes.
	b. print("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 6

6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No.
	b. Terminate the loop.


7. print("Finished!"); => Output: Finished!

Pro Tip:

A while loop is essentially an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · WHILE LOOPS & FOR LOOPS

    The While Loop in Swift, explained

    What a while loop does

    A while loop repeats a block of code as long as a condition is true. Use it when you know the rule for stopping but not necessarily how many passes it takes.

    while condition {
        instruction1
        instruction2
    }
    

    Swift needs no parentheses around the condition, but the braces are required, even for a single statement. The condition must be a Bool: Swift does not treat numbers as true or false.

    An example, step by step

    var count = 1
    while count <= 5 {
        print("I made a mistake")
        count += 1
    }
    print("Finished!")
    

    The output is the sentence five times, then Finished!. This is the sequence the computer follows:

    1. It creates count with the value 1.
    2. It checks count <= 5. Since 1 <= 5 is true, it runs the body: it prints the sentence and makes count 2.
    3. It checks the condition again, with 2, 3, 4 and 5 in turn. Each time the condition is true, so the body prints and increases count.
    4. After the fifth pass, count is 6. The condition 6 <= 5 is false, so the loop ends.
    5. The flow continues after the closing brace and prints Finished!.

    The condition is checked before every pass, including the first. If it is false from the start, the body never runs. A while loop is like an if statement that jumps back to the condition after each run.

    The three parts of a counting loop

    • Initialisation. The variable is created before the loop: var count = 1.
    • Condition. The loop keeps going while it is true: count <= 5.
    • Update. Something in the body moves the variable toward making the condition false: count += 1.

    If the update is missing, the condition never becomes false and the loop is infinite. Swift has no ++ operator, so you increase a variable with += 1. The counter must be declared with var, since a let constant can't be changed.

    The exercise

    The assignment is to print "I promise to learn coding." five times with a loop.

    1. Declare the counter. Write var counter = 1.
    2. Write the loop. while counter <= 5 { runs for the values 1, 2, 3, 4 and 5, so five times.
    3. Print inside the body with print("I promise to learn coding.").
    4. Update the counter with counter += 1, still inside the braces.
    var counter = 1
    while counter <= 5 {
        print("I promise to learn coding.")
        counter += 1
    }
    

    When the condition is false at the start

    Because the check comes first, a while loop can run zero times. If count started at 10 in the example above, 10 <= 5 would be false, the body would be skipped, and only Finished! would print. That is useful: code that handles a list of items does nothing when there are none.

    Common mistakes

    • Forgetting the update. counter stays 1 and the loop never ends.
    • Off by one. With counter < 5 the loop runs for 1 to 4, which is four passes. Starting at 1, use <= to run five times.
    • Using let. The compiler rejects counter += 1 on a constant.
    • Writing counter++. The compiler reports that the operator does not exist and suggests += 1.
    • Putting the update after the loop. It would run once, too late to matter.

    Key takeaways

    • A while loop checks its condition before every pass and stops when it is false.
    • A counting loop needs an initial value, a condition and an update.
    • Use var and += 1 in Swift.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free