0Pricing
Swift Academy · Lesson

guard let for Early Exit

Unwrap and exit early on failure to reduce nesting.

The Idea of guard

guard checks a condition and, if it fails, exits the current scope. It is built for early exits that keep the happy path unindented.

func greet(_ name: String?) {
    guard let name else {
        print("No name")
        return
    }
    print("Hello, \(name)")
}
greet("Ada")
greet(nil)

guard let Syntax

Write guard let value = optional else { return }. Unlike if let, the unwrapped value stays in scope after the guard.

func double(_ text: String) {
    guard let n = Int(text) else {
        print("Not a number")
        return
    }
    print(n * 2)
}
double("8")
double("x")

All lessons in this course

  1. if let and Shorthand Binding
  2. guard let for Early Exit
  3. Binding Multiple Optionals
  4. Optional Pattern in switch and for
← Back to Swift Academy