← 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.
Syntax
swift
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

markup
// 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)

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
// 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)
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
  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.