0
0
Swiftprogramming~5 mins

Guard for early exit pattern in Swift

Choose your learning style9 modes available
Introduction

The guard statement helps you check conditions early and stop the function if something is wrong. It keeps your code clean and easy to read.

When you want to check if a value exists before continuing.
When you want to stop a function early if a condition is not met.
When you want to avoid deep nesting of if statements.
When you want to make your code easier to understand by handling errors or invalid data upfront.
Syntax
Swift
guard condition else {
    // code to run if condition is false
    return // or throw or break
}

The condition must be true to continue past the guard.

The else block must exit the current scope (like return, break, or throw).

Examples
This checks if optionalName has a value. If not, it exits the function early.
Swift
guard let name = optionalName else {
    return
}
This checks if age is at least 18. If not, it prints a message and exits early.
Swift
guard age >= 18 else {
    print("Must be 18 or older")
    return
}
Sample Program

This function uses guard to check if the name exists. If not, it stops early and prints a message. Otherwise, it greets the user.

Swift
func greetUser(name: String?) {
    guard let userName = name else {
        print("No name provided. Exiting.")
        return
    }
    print("Hello, \(userName)!")
}

greetUser(name: nil)
greetUser(name: "Alice")
OutputSuccess
Important Notes

Use guard to keep your main code path clear and avoid nested ifs.

Always make sure the else block exits the current scope.

Summary

Guard checks a condition and exits early if false.

It helps keep code simple and readable.

Use guard to handle errors or missing data upfront.