← Back to Swift Course | Chapter 3: Control Flow | Lesson 2 of 8

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.

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

markup
func describe(age: Int) {
    guard age >= 0 else {
        print("Invalid age")
        return
    }
    print("Age is \(age)")
}
describe(age: 25)
describe(age: -5)

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

markup
func processScore(_ score: Int) {
    guard score >= 0, score <= 100 else {
        print("Score out of range")
        return
    }
    print("Valid score: \(score)")
}
processScore(150)
processScore(85)
Common Mistakes
  1. Forgetting that a guard block's else clause MUST exit the current scope (via return, break, continue, or throw) -- Swift enforces this at compile time.
  2. Using guard for the main happy-path logic instead of for validating and exiting early; guard is meant for early exits, if for branching.
  3. Not realizing that variables bound in guard let remain available for the REST of the enclosing scope, unlike an if let binding which is scoped to its own block.
Chapter Summary
  • guard checks a condition and requires an else block 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 let remain usable for the rest of the function, improving readability over nested if let.
  • The Swift compiler enforces that the else branch of a guard must leave the current scope.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.