What does guard buy you beyond if?

1.2.4 · L1 · Interview

Predict first

Does this compile?

func check(_ x: Int) {
    guard x > 0 else {
        print("negative")
    }
    print(x)
}
  • Yes
  • No

Mental model. It turns a pyramid of nested ifs into a checklist at the top of the function.

Three things: early exit, less nesting, and definite binding. After a guard, the bound values are non-optional for the remainder of the scope, so the happy path reads flat.

It is also a signal to the reader: “everything below here has already been validated.”

A guard body must leave the scope (return, throw, break, or a Never call). That rule is what makes the code after it safe.

Common traps

  • “guard compiles differently from if.” It does not — it is control flow sugar plus a compiler-enforced exit requirement.
  • “guard cannot use try?.” It can: guard let x = try? f() else { return } is valid.

They might follow up with

  • Can a guard body fall through? No — the compiler requires the else block to leave the scope.
  • When is if let the better choice? When both branches are equally interesting, e.g. showing a placeholder vs. the real content.

Related questions

  • 1.2.3 if let vs guard let vs ?? vs force unwrap — when is each one OK?

← if let vs guard let vs ?? vs force unwrap — when is each one OK?   What is the difference between if case, guard case, and switch on an… →