Menu
Coddy logo textTech

Guard Let

Part of the Fundamentals section of Coddy's Swift journey — lesson 13 of 86.

While if let unwraps an optional and runs code when a value exists, guard let takes the opposite approach — it exits early when a value is missing. This is especially useful inside functions where you want to handle the "bad" case first and keep the main logic clean.

func greet(name: String?) {
    guard let unwrappedName = name else {
        print("No name provided")
        return
    }
    print("Hello, \(unwrappedName)!")
}

greet(name: "Taylor") // Hello, Taylor!
greet(name: nil)      // No name provided

The guard let statement checks if name has a value. If it doesn't, the else block runs and the function exits with return. If the optional contains a value, it's unwrapped into unwrappedName — and here's the key difference from if let: the unwrapped variable remains available for the rest of the function, not just inside a block.

This "early exit" pattern keeps your code readable by handling error cases upfront, so the main logic isn't nested inside multiple if statements.

challenge icon

Challenge

Easy
Write a function validateAge that takes an optional age parameter and uses guard let to safely unwrap it.

If the age is nil, return "Invalid age". Otherwise, return "Age: [value]" where [value] is the unwrapped age.

Parameters:

  • age (Int?): An optional integer representing a person's age

Returns: A string — either "Invalid age" if the input is nil, or "Age: [value]" with the unwrapped value.

Example: If age is 25, return "Age: 25". If age is nil, return "Invalid age".

Try it yourself

func validateAge(age: Int) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals