The guard Statement
guard is like a bouncer at the door: if a condition isn't met, the code leaves immediately instead of continuing further inside.
In this page:
Basic guard Syntax
A guard statement checks a condition and, if it's false, runs the else block -- which must exit the current scope, commonly with return.
Example: Basic guard Syntax
func describe(age: Int) {
guard age >= 0 else {
print("Invalid age")
return
}
print("Age is \(age)")
}
describe(age: 25)
describe(age: -5)
Login to try C/C++/Java/PHP code in the editor
guard for Early Exit Validation
guard is idiomatic for validating multiple conditions early in a function, keeping the main logic unindented and easy to follow.
Note: Multiple conditions can be comma-separated in one guard, all must be true to pass.
Example: guard for Early Exit Validation
func processScore(_ score: Int) {
guard score >= 0, score <= 100 else {
print("Score out of range")
return
}
print("Valid score: \(score)")
}
processScore(150)
processScore(85)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that a
guardblock'selseclause MUST exit the current scope (viareturn,break,continue, orthrow) -- Swift enforces this at compile time. - Using
guardfor the main happy-path logic instead of for validating and exiting early;guardis meant for early exits,iffor branching. - Not realizing that variables bound in
guard letremain available for the REST of the enclosing scope, unlike anif letbinding which is scoped to its own block.
Chapter Summary
guardchecks a condition and requires anelseblock that exits scope if the condition fails.- It's typically used for early-exit validation at the top of a function.
- Values unwrapped via
guard letremain usable for the rest of the function, improving readability over nestedif let. - The Swift compiler enforces that the
elsebranch of aguardmust leave the current scope.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: