Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 146 ยท Control Flow

break, continue and Labels

Learn how Swift changes the flow of loops and switches - break, continue, labeled statements, fallthrough, return and defer - with runnable examples and real errors.

Normally a program runs one statement after another, and a loop repeats its body until its condition fails. Control transfer statements change that order. They let you leave a loop early, skip one pass, jump out of two nested loops at once, or run a cleanup block when a scope ends. Swift has five of them: continue, break, fallthrough, return and throw. A related feature, defer, schedules code to run when the current scope exits, however it exits.

This lesson uses them in loops and switch statements, shows why labels are Swift's clean answer to "get me out of both loops", and explains the places where Swift differs from C and Java. If you have not seen loops yet, read Loops first; switch is covered in switch.

continue: skip to the next pass

continue ends the current pass of a loop and starts the next one. The rest of the body is skipped, but the loop itself keeps going.

Swift continue skips one pass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The same effect is possible with a where clause on the loop (for r in readings where r != -999.0), which is neater when the test is a single condition. continue shines when the body needs several checks before the real work, because each check can bail out with one line instead of adding another level of nesting.

break: leave the loop

break ends the whole loop immediately. Execution continues with the first statement after the loop.

Swift break stops the search

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Before you write a loop that searches, check whether a standard-library method already does it: first(where:), contains(where:), firstIndex(of:), allSatisfy(_:). They state the intent in one line and cannot have an off-by-one mistake. Reach for break when the loop does something richer than finding a value.

break and continue are statements, not functions, and they only affect the nearest enclosing loop (or switch). Inside a closure passed to forEach, they are not available at all; a return there leaves only the closure for the current element. That is one more reason to prefer for-in for loops that need early exit.

Labels: leaving nested loops

What if the loop you want to leave is not the innermost one? In many languages you set a flag variable and check it after every inner loop. Swift lets you put a label in front of a loop and then name that label in break or continue.

Swift Labeled break and continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The label is a name followed by a colon, placed before for, while, repeat (and also if, switch and do, see below). break search leaves the outer loop. continue outer skips the rest of the inner loop and the rest of the current outer pass and starts the next outer pass. Name labels after what the loop is doing (search, rows, retry) so the jump reads like a sentence.

If you name a label that does not exist, the compiler rejects the program:

Swift An unknown label (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is main.swift:3:15: error: cannot find label 'outer' in scope. Labels must be visible from the statement that uses them: you can only jump outward to an enclosing statement, never into a loop or sideways to another one.

Labels on other statements

A labeled if or do block can also be left early with break label. It is rare, but it is a tidy way to leave a block when the early exit is found deep inside it:

Swift Breaking out of a labeled if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

An unlabeled break is not allowed inside an if, because the compiler would not know whether you meant the if or an outer loop. That is why the label is required there.

break and switch

A Swift switch runs only the matching case and then leaves, so you never need break at the end of a case as in C. A case cannot be empty either; if you really want a case to do nothing, write break:

Swift break inside switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You also use break to leave a case early, after some work has started, just as in a loop. Inside a loop, an unlabeled break placed in a switch leaves the switch, not the loop. This surprises many newcomers. To stop the loop from inside the switch, label the loop and write break loopName.

Swift Stopping a loop from a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With the label, the last "step" never runs. Replace break session with a plain break and the final command is processed as well. The label turns a hidden trap into explicit intent.

fallthrough

Swift's switch does not fall into the next case. If you do want that, the fallthrough keyword transfers control to the body of the next case, without checking its pattern:

Swift fallthrough

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Because the next case's pattern is not tested, fallthrough cannot be used to move into a case that binds variables. It is rarely the best design: a collection of ranges, a loop over thresholds or a computed value usually reads better. Use it sparingly.

return and throw

return leaves the current function (optionally with a value). Inside a loop it stops the loop and the function together, which makes it the usual way to write "find and give back" functions:

Swift return from inside a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

throw also leaves the function, but with an error that the caller must handle; see Error Handling. guard statements, which must exit their scope using one of these statements, are the subject of the next lesson, guard and Early Exit.

defer: cleanup that always runs

A defer block does not run where you write it. It runs when the enclosing scope ends, no matter how: normal completion, return, break, continue or a thrown error. Several defer blocks run in the reverse of the order in which they appear.

Swift defer and loop exits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The inner defer runs at the end of every pass, including the pass that used continue and the one that used return. The outer defer runs when the function exits, so "close log" prints last. This pairing of "do" and "undo" next to each other makes it hard to forget the cleanup when someone adds an early exit later. defer and Cleanup goes deeper (ordering, errors, and what defer must not do).

Pitfalls

  • Unlabeled break in a switch inside a loop leaves the switch only. Label the loop when you want to leave it.
  • continue in a while loop jumps back to the condition check. If the line that moves the condition forward (i += 1) comes after the continue, the loop never ends. Update the counter before continue, or use a for-in loop where the sequence advances by itself.
  • Labels that are too clever. More than one or two labels in a function is a sign that the logic should be split into smaller functions, where a plain return does the job.
  • fallthrough does not test the next pattern, unlike most mental models of "continue matching".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does continue do inside a for-in loop?

    continue only ends the current iteration. The loop proceeds with the next element.
  2. 2. A switch sits inside a for loop and one case contains a plain break. What does it leave?

    An unlabeled break leaves the innermost loop or switch, which here is the switch. Label the loop and use break label to leave it.
  3. 3. How do you leave two nested loops at once?

    Swift has labeled statements: outer: for ... and then break outer from inside the inner loop.
  4. 4. When does the code in a defer block run?

    defer runs at the end of its scope on every exit path: normal end, return, break, continue or throw.
  5. 5. What does fallthrough do in a switch case?

    Swift cases do not fall through by default. fallthrough explicitly continues into the next case's body, skipping its pattern test.

Summary

  • continue skips to the next pass of a loop; break leaves the nearest loop or switch.
  • Put a label in front of a statement (outer: for ...) and use break outer or continue outer to jump out of nested loops.
  • A plain break inside a switch leaves the switch, not an enclosing loop; label the loop to leave it.
  • Cases never fall through by default; fallthrough enters the next case's body without testing its pattern.
  • return and throw leave the whole function; defer runs cleanup when its scope exits, on every path.
  • Prefer standard-library helpers such as first(where:) over hand-written search loops.

Next: guard and Early Exit