What does guard buy you beyond if?
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
- “
guardcompiles differently fromif.” It does not — it is control flow sugar plus a compiler-enforced exit requirement. - “
guardcannot usetry?.” It can:guard let x = try? f() else { return }is valid.
They might follow up with
- Can a
guardbody fall through? No — the compiler requires the else block to leave the scope. - When is
if letthe 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… →