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

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
func printUppercased(_ text: String?) {
    guard let text = text else {
        print("No text provided")
        return
    }
    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
func describe(name: String?, age: Int?) {
    guard let name = name, let age = age else {
        print("Missing information")
        return
    }
    print("\(name) is \(age) years old")
}
describe(name: "Kim", age: 28)
describe(name: nil, age: 28)
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.