← Back to Swift Course | Chapter 5: Optionals | Lesson 5 of 8

guard let Unwrapping

guard let checks that a value exists, and if it doesn't, the function leaves right away instead of trying to continue without it.
Syntax
swift
func name(param: Type?) {
    guard let unwrapped = param else {
        return
    }
    // use unwrapped
}

Basic guard let

guard let unwraps an optional and, if it fails, executes the else block which must leave the current scope, commonly via return.

Example: Basic guard let

markup
// Define the function `printUppercased` taking `text`
func printUppercased(_ text: String?) {
    // Unwrap `text` into `text`, or bail out via the else branch
    guard let text = text else {
        // Print "No text provided" to the console
        print("No text provided")
        return
    }
    // Print `text.uppercased()` to the console
    print(text.uppercased())
}
printUppercased("hello")
printUppercased(nil)

Chaining Multiple guard let Unwraps

Multiple optionals can be unwrapped in a single guard let, all separated by commas, keeping validation logic compact at the top of a function.

Example: Chaining Multiple guard let Unwraps

markup
// Define the function `describe` taking `name`, `age`
func describe(name: String?, age: Int?) {
    // Unwrap `name, let age = age` into `name`, or bail out via the else branch
    guard let name = name, let age = age else {
        // Print "Missing information" to the console
        print("Missing information")
        return
    }
    // Print "\(name) is \(age) years old" to the console
    print("\(name) is \(age) years old")
}
describe(name: "Kim", age: 28)
describe(name: nil, age: 28)
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 guard let's else branch must exit the current scope, just like a plain guard.
  2. Using guard let for a value only needed briefly inside a small block, where if let would keep the scope tighter.
  3. Not taking advantage of guard let's biggest benefit -- the unwrapped constant stays available for the rest of the function, avoiding nested indentation.
Chapter Summary
  • guard let value = optional else { return } unwraps or exits the current scope.
  • This keeps the "happy path" code unindented and easy to read.
  • The unwrapped constant remains usable for the rest of the enclosing function.
  • guard let is preferred over if let when a missing value should stop execution early.
🔒

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.