Start learning free

LESSON 157 OF 415 · LOOPING OVER ARRAY INDICES

Continue in For Loops in Swift

Lesson Read the full explanation

With the continue statement we can stop the current iteration of the loop, and continue with the next.

When Swift hits continue, it skips (not execute) any code left, and jumps directly to the next iteration instead.

In this example, we will not let anyone inside a bar if their age is less than 21:

let ages = [10, 30, 21, 19, 25]

for age in ages {
	if age < 21 {
		continue
	}
	print("Someone of age \(age) entered the bar.")
}

The output of this program is:

Someone of age 30 entered the bar.
Someone of age 21 entered the bar.
Someone of age 25 entered the bar.

As you can see, our program doesn't print for ages 10 and 19.

Here's what happens during this loop:

1. First iteration:
	a. age = 10
	b. Is age < 21? Yes:
	    continue => Go directly to the next age

2. Second iteration:
	a. age = 30
	b. Is age < 21? No.
	c. print

3. Third iteration:
	a. age = 21
	b. Is age < 21? No.
	c. print

4. Fourth iteration:
	a. age = 19
	b. Is age < 21? Yes:
	    continue => Go directly to the next age

5. Fifth iteration:
	a. age = 25
	b. Is age < 21? No.
	c. print

Assignment
Let's allow only the people with height at least 170 into the arena.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · LOOPING OVER ARRAY INDICES

    Continue In For Loops in Swift, explained

    What continue does

    The continue statement ends the current iteration of a loop and jumps to the next one. Any code below it in the body is skipped for that iteration, but the loop itself keeps running. Compare break, which ends the whole loop.

    It is useful for filtering: test whether an element should be ignored, and if so, skip it.

    An example

    This loop lets people into a bar only if they are at least 21:

    let ages = [10, 30, 21, 19, 25]
    
    for age in ages {
        if age < 21 {
            continue
        }
        print("Someone of age \(age) entered the bar.")
    }
    
    Someone of age 30 entered the bar.
    Someone of age 21 entered the bar.
    Someone of age 25 entered the bar.
    

    For ages 10 and 19 the condition is true, continue runs, and the print below is skipped. For 30, 21 and 25 the condition is false, so the body runs to the end. Notice that 21 is allowed in, because the test is age < 21, which is false for 21.

    Skipping with guard

    Here is the same idea with guard, summing only the non-negative numbers:

    let nums = [3, -1, 4, -5, 9]
    var total = 0
    for n in nums {
        guard n >= 0 else { continue }
        total += n
    }
    print(total)
    

    It prints 16, which is 3 + 4 + 9. The two negative numbers hit continue and never reach total += n. Notice that a guard states the condition to keep (n >= 0), while the if form in the bar example states the condition to skip.

    Swift details

    • Same shape as break. Both go inside an if inside the loop body. Only their effect differs.
    • Labels work too. In nested loops, continue applies to the innermost loop. continue outer, with a labeled outer loop, skips to the next iteration of that outer loop.
    • Braces are required. The body of an if needs braces even for a single statement, and the condition needs no parentheses.
    • guard is a common alternative. guard n >= 0 else { continue } skips negative numbers and keeps the rest of the body unindented. A guard body must leave the current scope, and continue does.
    • Be careful in while loops. continue jumps straight back to the condition. If the statement that changes the counter sits below the continue, it is skipped and the loop may never end. Put the update before the continue.

    The exercise

    Only people with a height of at least 170 may enter the arena. The code starts with:

    let heights = [180, 139, 174, 190, 162]
    
    1. Loop over the heights. for height in heights visits each person in turn.
    2. Skip the short ones. Inside the loop, if height < 170 { continue }. At least 170 means 170 itself passes, so the test is strictly less than.
    3. Print the rest. Below the if, print(height) runs only for heights that were not skipped.
    let heights = [180, 139, 174, 190, 162]
    
    for height in heights {
        if height < 170 {
            continue
        }
        print(height)
    }
    

    The output is:

    180
    174
    190
    

    Common mistakes

    • Using <=. height <= 170 would turn away a person who is exactly 170.
    • Printing before the check. Every height is printed, because the print happens before continue can skip anything.
    • Confusing it with break. With break, the first short person (139) would end the loop and only 180 would print.

    Key takeaways

    • continue skips the rest of the current iteration and moves to the next one.
    • Write the test for what to skip, then the code for what to keep.
    • In while loops, update the counter before any continue.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free