0Pricing
Swift Academy · Lesson

guard let for Early Exit

Unwrap and exit early on failure to reduce nesting.

guard let for Early Exit is a free Swift Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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")

Value Lives On

Because guard exits on failure, the compiler knows the value exists afterward. You use it normally in the rest of the function.

func length(of text: String?) {
    guard let text else { return }
    let count = text.count
    print(count)
}
length("hello")

The else Must Exit

The else block of a guard must leave the current scope: return, break, continue, or throw. This is enforced by the compiler.

func process(_ value: Int?) {
    guard let value else {
        return
    }
    print("Processing \(value)")
}
process(99)

Shorthand guard let

Like if let, guard supports shorthand: guard let name else { ... } when names match.

func show(_ name: String?) {
    guard let name else {
        print("missing")
        return
    }
    print(name)
}
show("Kai")

Flat Happy Path

The big win of guard is a flat, readable happy path. Compare nested if let pyramids with a series of guards.

func register(name: String?, age: Int?) {
    guard let name else { return }
    guard let age else { return }
    print("\(name) is \(age)")
}
register(name: "Mia", age: 28)

Guarding Plain Conditions

Guard works with any Bool condition, not just optionals. guard count > 0 else { return } bails out early.

func divide(_ a: Int, by b: Int) {
    guard b != 0 else {
        print("Cannot divide by zero")
        return
    }
    print(a / b)
}
divide(10, by: 2)
divide(10, by: 0)

Guard in Loops

Inside a loop, a guard can continue to skip an iteration when data is missing.

let inputs = ["1", "x", "3"]
for item in inputs {
    guard let n = Int(item) else { continue }
    print(n * 10)
}

Multiple Bindings in One Guard

A single guard can unwrap several optionals, separated by commas. All must succeed to proceed.

func combine(_ a: String?, _ b: String?) {
    guard let a, let b else { return }
    print(a + b)
}
combine("foo", "bar")

Guard With where-like Checks

You can add Boolean conditions after a binding with a comma to refine when the guard passes.

func validate(_ text: String?) {
    guard let text, !text.isEmpty else {
        print("invalid")
        return
    }
    print("ok: \(text)")
}
validate("")
validate("hi")

When to Choose guard

Use guard for preconditions at the top of a function, and if let when you only need the value briefly inside a branch.

func area(width: Int?, height: Int?) -> Int {
    guard let width, let height else { return 0 }
    return width * height
}
print(area(width: 3, height: 4))

Quick Check

Test guard let.

Recap: guard let for Early Exit

guard let value else { return } unwraps an optional and keeps the value in scope afterward. Its else block must exit, which keeps your happy path flat and readable.

func f(_ x: Int?) {
    guard let x else { return }
    print(x)
}
f(5)

Frequently asked questions

Is the “guard let for Early Exit” lesson free?

Yes — the full text of “guard let for Early Exit” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “guard let for Early Exit”?

Unwrap and exit early on failure to reduce nesting. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “guard let for Early Exit” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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