skip to content

Early Exits and Loops

guard forces an early exit, switch never falls through by default, and if and switch can be expressions. Interviewers check guard-first style, loop forms and the order defer blocks run in.

on this pageshow

explore

questions

6

In Swift, how does a guard statement differ from an if statement, and why must guard's else branch exit the enclosing scope?

level: juniorimportance: must knowfreq 78%

answer

  1. happy path stays unindented
  2. else is not optional
  3. bindings outlive the statement
  4. return, break, continue, throw, or Never

basics

~20 s

A guard runs its else branch when its condition fails, and that branch must leave the enclosing scope through return, break, continue, throw or a call that never returns. Values the condition binds stay usable for the rest of the scope.

solid answer

~50 s

`guard condition else { ... }` is a precondition check: when the condition is false the `else` block runs, and that block must transfer control out of the scope that contains the `guard` - `return`, `break` or `continue` inside a loop, `throw`, or a call to a function that returns `Never`, such as `fatalError(_:)`. If the block can reach its closing brace, the build fails with "'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope". Because the exit is guaranteed, a name the condition binds (`guard let email = form.email`) is available, unwrapped, for the rest of the enclosing scope, while an `if let` binding lives only inside its braces. The style payoff is a flat function: every failed check leaves at the top, and the happy path runs unindented below instead of inside nested `if` blocks.

code

swift · 30 lines
swift
struct SignUpForm {
    var email: String?
    var password: String
    var age: Int?
}

struct Account {
    let email: String
    let age: Int
}

func makeAccount(from form: SignUpForm) -> Account? {
    guard let email = form.email, email.contains("@") else {
        print("rejected: missing or malformed email")
        return nil
    }
    guard form.password.count >= 12 else {
        print("rejected: password shorter than 12 characters")
        return nil
    }
    guard let age = form.age, age >= 16 else {
        print("rejected: age missing or under 16")
        return nil
    }
    // email and age are in scope and non-optional here
    return Account(email: email, age: age)
}

let form = SignUpForm(email: "[email protected]", password: "short", age: 30)
_ = makeAccount(from: form) // prints the password rejection

go deeper

for a junior

Recall that guard's else is mandatory and must leave the scope with return, break, continue, throw or a Never call, and that its bindings stay usable afterwards.

for a middle

Explain why the compiler can let guard bindings outlive the statement, and show guard-first style turning nested ifs into a flat list of early exits.

for a senior

Show judgement about where guard reads better than if, and choose the right exit for the context: continue in loops, throw or return in functions, fatalError only for broken invariants.

for a principal

Frame guard-first as a readability convention a team can agree on in review, and know when a forced early exit would obscure logic where both branches continue.

## What `guard` is A `guard` statement checks a condition that must hold for the rest of the code to make sense, and leaves the current scope when it does not. Its form is fixed: ```swift guard condition else { // runs only when the condition is false // must leave the enclosing scope } ``` The condition is a comma-separated **condition list**, the same kind `if` and `while` accept: Boolean expressions, optional bindings such as `let email = form.email`, `case` patterns and `#available` checks. All of them must succeed for execution to continue past the `guard`. The `else` keyword and its block are **required** - unlike `if`, there is no form without them. ## The exit rule the compiler enforces The reference manual states the rule plainly: the `else` clause must either call a function whose return type is `Never` or transfer control outside the guard statement's enclosing scope. In practice that leaves five ways to end it: 1. `return` - leaves the function, method, closure or getter. 2. `break` - leaves the enclosing loop, `switch` or labeled statement. 3. `continue` - ends the current pass of the enclosing loop. 4. `throw` - propagates an error to the caller. 5. A call to a `Never`-returning function such as `fatalError(_:)` or `preconditionFailure(_:)`. The `else` block may do other work first - log, record a metric, set a flag - as long as its last reachable statement is one of these. If any path through it can reach the closing brace, the build fails: ```plaintext error: 'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope ``` The choice of exit must also make sense where the `guard` sits. Directly in a function body, `break` fails with "'break' is only allowed inside a loop, if, do, or switch" and `continue` fails with "'continue' is only allowed inside a loop". Inside a `for` loop, `guard item.isValid else { continue }` skips one element and `guard ... else { break }` stops the loop. ## Why the bindings outlive the statement Because the compiler has proved that execution only continues past a `guard` when every condition held, anything the condition list binds is in scope - and non-optional - **for the rest of the enclosing scope**. That is the decisive difference from `if let`: | | `if let x = optional { ... }` | `guard let x = optional else { ... }` | |---|---|---| | Where `x` is visible | only inside the `if` braces | everywhere after the `guard` in the same scope | | What the failure branch must do | anything, including nothing | leave the scope | | Natural use | an optional extra step | a precondition the rest of the scope depends on | (How optional binding and the `guard let x` shorthand work is covered in the Swift lesson on optionals; here the point is only the scope.) ## Guard-first style: a sign-up validator A sign-up form shows why reviewers ask for guards at the top of a function. Each check rejects one bad input and leaves; what survives reaches the bottom with every value already unwrapped: ```swift func makeAccount(from form: SignUpForm) -> Account? { guard let email = form.email, email.contains("@") else { print("rejected: missing or malformed email") return nil } guard form.password.count >= 12 else { print("rejected: password shorter than 12 characters") return nil } guard let age = form.age, age >= 16 else { print("rejected: age missing or under 16") return nil } return Account(email: email, age: age) } ``` Written with nested `if` statements, the same logic indents three levels and pushes the account creation into the innermost block, with each rejection message far from the check that produced it. With `guard`, each rule and its rejection sit together, and adding a fourth rule is one more block at the same indentation. ## When `if` is still the right tool - **Both outcomes continue.** If the false case is not a reason to stop - an optional discount, a cache that may be empty - an `if` says so; a `guard` would force an artificial exit. - **The binding is needed only briefly.** An `if let` keeps a name out of the rest of the scope. - **The condition is the interesting case.** Wrapping the main behaviour in `guard !condition else { ...main work...; return }` inverts the reader's expectations. ## Mistakes interviewers listen for - Treating `guard` as an `if` with the condition negated and forgetting the exit, then being surprised by the compile error. - Believing a `guard let` binding is visible only inside the `else` block - it is the opposite: the `else` block is the one place the binding does not exist. - Using `break` to leave a function from a `guard` at the top of a function body, where there is no loop to break out of. - Ending the `else` with a log line and nothing else, expecting the function to carry on.

  • Can a guard's else block call fatalError instead of returning, and when is that appropriate?
    Yes. `fatalError(_:)` returns `Never`, so the compiler accepts it as the end of the `else` block; execution can never fall through. It suits a broken invariant that indicates a programmer error - a resource the app bundle must contain - not a bad user input, where returning or throwing lets the caller recover.
  • Inside a for-in loop, what do break and continue do when they end a guard's else block?
    `continue` ends the current pass, so the loop moves to its next element - the usual way to skip an invalid item. `break` ends the loop itself and execution resumes after it. Both satisfy the exit rule because they leave the loop body, which is the guard's enclosing scope.

A guard is a door check that must turn a failing visitor away, not just warn them. Everyone who gets past the door is known to have passed every check, so the rooms inside can rely on it.

  • guard is just an if with the condition negated, so the else may do anything
  • A guard let binding is only visible inside the else block
  • Printing an error in the else block is enough to satisfy guard
  • guard can only unwrap optionals, not test Boolean conditions
  • break is the way to leave a function from a guard
open as a page

In Swift, when does a defer block run, and in what order do several defer blocks in the same scope execute?

level: middleimportance: must knowfreq 60%

basics

~20 s

A defer block runs when control leaves the scope it was declared in, by return, break, continue, a thrown error or reaching the closing brace. Several defer blocks in one scope run in reverse order: the last one written runs first.

open as a page

Swift has no C-style for loop, so how do you write counted, stepped, filtered and run-at-least-once loops instead?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Swift loops with for-in over a sequence: a range to count, stride(from:to:by:) or stride(from:through:by:) to step, and a where clause to skip passes. while checks before each pass; repeat-while checks after, so its body runs at least once.

open as a page

In Swift, why does a switch case never run into the next case by default, and what exactly does the fallthrough keyword do?

level: middleimportance: should knowfreq 40%

basics

~20 s

A Swift switch ends as soon as the first matching case body finishes, so no break is needed. fallthrough opts in: control jumps straight into the next case's body without checking that case's pattern or where clause.

open as a page

In Swift, how do you leave an inner and an outer loop at once, and what does an unlabeled break inside a switch end?

level: middleimportance: should knowfreq 45%

basics

~20 s

Label the outer loop and write break with that label to leave every nested loop at once. An unlabeled break ends only the innermost loop or switch, so in a switch inside a loop the loop carries on.

open as a page

Since Swift 5.9 lets if and switch produce values, why does `let delay = if retrying { 0 } else { 1.5 }` fail to compile, and what rules apply?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Swift type-checks each branch of an if or switch expression on its own, so 0 becomes Int and 1.5 becomes Double, and the compiler reports mismatching branch types. Supplying the type, as in let delay: Double, fixes it.

open as a page