Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 146 ยท Control Flow

guard and Early Exit

Learn Swift guard statements - guard let, guard conditions, mandatory exits, binding scope and how guard flattens nested if-let pyramids with runnable examples.

Some functions can do their job only if certain conditions hold: the input is not empty, the number parses, the file name is valid. The beginner's way to write this is a pyramid of nested if statements, with the real work buried at the deepest level and the error handling scattered at the bottom. The Swift way is to state the requirements first, at the top, and leave the function as soon as one is not met. That is early exit, and the statement made for it is guard.

A guard statement has a condition and an else block. If the condition is true, the program simply continues after the guard. If it is false, the else block runs, and that block must leave the current scope: with return, throw, break, continue, or a call to a function that never returns, such as fatalError. The compiler checks this rule. This lesson shows how guard works, why the bindings it creates are visible after it, and when if is still the better tool.

From nesting to guard

Here is a function that builds a greeting from an optional name and an optional age, first with if let, then with guard.

Swift The pyramid and the flat version

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.

Both functions behave identically. In the flat version each requirement sits on one line, directly next to the message for what goes wrong, and the successful path runs straight down the left margin with no indentation. The reader can see the "happy path" without scrolling through error branches. This style is sometimes called the golden path rule: keep the main flow at the left edge.

guard let and the scope of the binding

guard let name else { ... } is shorthand (Swift 5.7) for guard let name = name else { ... }. It unwraps the optional and, crucially, the new constant lives on after the guard, in the rest of the enclosing scope. With if let, the constant exists only inside the braces of the if.

Swift Where the binding is visible

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.

After the first guard, value is a non-optional Double for the rest of the function. This is the main reason guard let exists: the unwrapped value stays available without another level of braces. See Optionals for the full set of ways to unwrap.

The else block must exit

The compiler does not allow a guard whose else block can fall through to the code below. Without that guarantee, the code after the guard could run with the requirement unmet, and the whole safety argument would collapse.

Swift A guard that does not exit (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 compiler stops with error: 'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope. Add return 0 (or change the function to return Int? and return nil, or make it throws) and the code compiles. Which exit is right depends on the function: return a default, return nil, throw an error, or, for a bug in the program rather than bad input, stop with fatalError.

Several conditions in one guard

A guard condition list can combine boolean tests and optional bindings, separated by commas. All must succeed. Later items can use bindings made by earlier ones:

Swift Combining conditions

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 conditions are checked left to right and evaluation stops at the first failure, so quantity > 0 never runs when quantity is nil. The downside of a combined guard is that the else branch no longer knows which condition failed. If the user needs to be told exactly what is wrong, use separate guards, one message each.

The last example in the function, if let code = order.couponCode, code == "SAVE10", is a place where if is right: the coupon is optional and its absence is not an error. Use guard for requirements, if for choices.

guard in loops

Inside a loop, the else block can use continue or break to leave the current pass or the loop. This keeps loop bodies as flat as functions:

Swift guard with 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.

Notice that each guard targets one problem and gives one useful message. Compare that with nesting three if statements inside the loop. The flat version is also easier to extend, for example by adding a third check.

guard with throws

In functions that can throw (see Error Handling), a failed guard usually turns into a thrown error, which lets the caller decide what to do:

Swift guard and throw

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 function body reads like a list of rules. Anyone adding a rule adds one line.

When to use if instead

guard is not a replacement for if. Prefer if or if let when:

  • Both branches are normal. If neither outcome is an error or an abnormal case ("is it Tuesday?"), a plain if/else expresses the symmetry better.
  • The value is only needed in one place. A binding used for a single statement does not need to live on after it.
  • You want an expression. Since Swift 5.9, if can produce a value (let label = if score > 50 { "pass" } else { "fail" }); guard cannot. See if and else.

A rule of thumb: if you find yourself writing an if whose else branch is only return, or an if let that wraps the entire rest of the function, convert it to guard.

guard and top-level code

In main.swift you can use guard at the top level too, but there is no function to return from, so the usual exits are exit(1), fatalError("...") or, inside a loop, continue/break. Because the exit must leave the scope, wrapping work in a function is generally cleaner, and that is also easier to test.

A guard whose else calls fatalError or preconditionFailure documents an assumption: "this must be true or the program is broken". Use it for programmer errors, never for bad user input, which should produce a recoverable result such as nil or a thrown error. See Assertions and Preconditions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must the else block of a guard statement do?

    The compiler requires that the else block cannot fall through, so code after the guard only runs when the condition held.
  2. 2. Where is a constant created by guard let x = ... visible?

    That is the point of guard let: the unwrapped value remains available after the guard, without extra nesting.
  3. 3. Which line is the shorthand for guard let name = name else { return }?

    Since Swift 5.7 you can write guard let name else, which unwraps and shadows the optional with the same name.
  4. 4. In which case is if a better choice than guard?

    guard is for requirements and abnormal cases. For two normal branches, if/else (or an if expression) says what you mean.
  5. 5. Inside a for loop, which exit is typical in a guard's else block when you only want to skip the current element?

    continue leaves the current pass and starts the next, so the bad element is skipped and the loop goes on.

Summary

  • guard condition else { exit } checks a requirement and leaves the scope when it is not met; the else block must not fall through.
  • Bindings made by guard let stay visible after the statement, which flattens nested if let pyramids and keeps the main path at the left margin.
  • A condition list can mix boolean tests and bindings, evaluated left to right; use separate guards when each failure needs its own message.
  • In loops, guard plus continue or break keeps the body flat; in throwing functions, guard plus throw reads like a list of rules.
  • Use if when both branches are ordinary, when the binding is needed only inside the block, or when you want an if expression.

Next: Optionals