Start learning free

LESSON 124 OF 415 · WHILE LOOPS & FOR LOOPS

The For Loop in Swift: for-in Over a Range

Lesson Read the full explanation

There is a more powerful way to use the for loop in Swift.

For loops can be declared with a variable and a range to iterate over:

for variable in range {
	instruction1
	instruction2
	...
}

Let's break down each component:

  • The variable takes on each successive value in the range, starting from the first value. It is set up automatically before the loop begins.

  • The range defines the sequence of values the loop iterates over. The loop continues as long as there are remaining values in the range.

  • After each iteration the variable automatically advances to the next value in the range, prior to the next check.


Example:

for i in 0..<4 {
	print("Hello world!")
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The range starts at 0. The loop variable i is initialized to 0 so the loop starts counting from 0.

  • The range is 0..<4, meaning the loop will run as long as the iterator variable, i, is less than 4.

  • After each iteration i automatically advances to the next value. This means that after running the code inside {}, i will get increased by 1.


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

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 4 true? <=> Is 0 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i advances => i = 1

2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i advances => i = 2

3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i advances => i = 3

4. Fourth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i advances => i = 4

5. Fifth iteration:
	a. Is i < 4 true? <=> Is 4 < 4 true? No.
	b. Exit the loop.

Assignment

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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · WHILE LOOPS & FOR LOOPS

    The For Loop in Swift, explained

    What the for-in loop does

    Swift has no C-style for (int i = 0; i < 4; i++) loop. Its for loop always goes through the values of a sequence, and a range is the simplest sequence to loop over:

    for variable in range {
        instruction1
        instruction2
    }
    

    On each pass the loop sets variable to the next value of the range and runs the body. When the range runs out, the loop ends. You never declare the variable yourself and you never increment it: Swift creates it for each pass and moves to the next value on its own. Inside the body it is a constant, so assigning to it is a compile-time error.

    Ranges: ..< and ...

    Swift has two range operators:

    • 0..<4 is a half-open range. It starts at 0 and stops before 4, so it holds 0, 1, 2 and 3.
    • 0...4 is a closed range. It includes both ends, so it holds 0, 1, 2, 3 and 4.

    The half-open form is the usual choice for counting a number of repetitions, because 0..<n runs exactly n times.

    for i in 0..<4 {
        print("Hello world!")
    }
    

    This prints Hello world! on four lines. The loop does these steps:

    1. Take the first value of the range: i is 0. Run the body.
    2. Take the next value: i is 1. Run the body.
    3. Do the same for 2 and 3.
    4. The range has no more values, so the loop ends.

    The body ran four times, once for each of 0, 1, 2 and 3. The loop variable i is only visible inside the loop.

    Ignoring the variable with _

    The example above never uses i. When you only want to repeat something, write an underscore in its place:

    for _ in 0..<4 {
        print("Hello world!")
    }
    

    The underscore tells Swift, and the reader, that no name is needed. It also avoids the warning Swift can give about a loop variable that is never read.

    The exercise: print a sentence five times

    The task is to print I promise to learn coding. five times. It is built in two steps.

    1. Write an empty loop over 0..<5. A half-open range from 0 holds exactly five values, so the body runs five times. Use _ because the message doesn't depend on the index.
    2. Put the print call inside the braces. The body runs once per value, so one print line gives five lines of output.
    for _ in 0..<5 {
        print("I promise to learn coding.")
    }
    

    Common mistakes

    • Using 0...5 by accident. The closed range holds six values, so the message is printed six times.
    • Forgetting the braces. Unlike some languages, Swift requires braces around a loop body, even for a single statement.
    • Trying to change the loop variable. Writing i += 1 inside the loop is an error because i is a constant. To change how the loop moves, change the range.
    • Using a closed range that runs backwards. A range like 5...1 has its start above its end, which isn't a valid range, and the program crashes at run time. Counting down needs stride or reversed().
    • Writing a C-style loop. for (i = 0; i < 5; i++) doesn't compile in Swift.

    Key takeaways

    • for variable in range runs the body once for each value in the range.
    • Swift creates the loop variable and advances it for you.
    • a..<b excludes b, and a...b includes it.
    • 0..<n repeats a block exactly n times.
    • Use _ when you don't need the value.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free