0
0
Swiftprogramming~5 mins

Guard let for early exit in Swift

Choose your learning style9 modes available
Introduction

Use guard let to check if a value exists and stop the function early if it doesn't. It helps keep your code clean and easy to read.

When you want to make sure a value is not nil before continuing.
When you want to exit a function early if a condition is not met.
When you want to avoid deep nesting of if statements.
When you want to safely unwrap optionals in a simple way.
Syntax
Swift
guard let constantName = optionalValue else {
    // code to run if optionalValue is nil
    return // or break or throw
}

The guard let statement unwraps an optional value.

If the optional is nil, the code inside else runs and you must exit the current scope.

Examples
This function uses guard let to check if name has a value. If not, it prints a message and exits early.
Swift
func greet(name: String?) {
    guard let unwrappedName = name else {
        print("No name provided.")
        return
    }
    print("Hello, \(unwrappedName)!")
}
Here, guard let tries to convert a string to an integer. If it fails, the program exits early.
Swift
guard let age = Int(input) else {
    print("Invalid age")
    return
}
print("Age is \(age)")
Sample Program

This program defines a function that uses guard let to check if the username exists. It prints a welcome message if it does, or an error if it doesn't.

Swift
func printUsername(_ username: String?) {
    guard let name = username else {
        print("Username is missing.")
        return
    }
    print("Welcome, \(name)!")
}

printUsername(nil)
printUsername("Alice")
OutputSuccess
Important Notes

You must exit the current scope inside the else block of guard. This can be return, break, or throw.

guard let helps keep your main code path less nested and easier to read.

Summary

guard let unwraps optionals and exits early if nil.

It keeps code clean by avoiding deep nesting.

Always exit the scope inside the else block.