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:
Syntax
func name(param: Type) {
guard condition else {
// must exit: return, break, continue or throw
return
}
// continue when condition is true
}
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
// Define the function `describe` taking `age`
func describe(age: Int) {
guard age >= 0 else {
// Print "Invalid age" to the console
print("Invalid age")
return
}
// Print "Age is \(age)" to the console
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
// Define the function `processScore` taking `score`
func processScore(_ score: Int) {
guard score >= 0, score <= 100 else {
// Print "Score out of range" to the console
print("Score out of range")
return
}
// Print "Valid score: \(score)" to the console
print("Valid score: \(score)")
}
processScore(150)
processScore(85)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: