Guard Statement in Swift

Guard Statement in Swift

In Swift, guard is a control flow statement used for early exit from a block of code if a certain condition is not met. It helps improve code readability by reducing the nesting levels compared to using if-else statements for error handling and conditional checks.

💡
guard provides a way to gracefully exit a scope if conditions are not met.

The basic syntax of guard is as follows:

guard condition else {
    // statements to execute if condition is not met
    // this block must exit the current scope
}

Here's how guard in Swift works:

  • If the condition evaluates to true, the code execution continues normally after the guard statement.
  • If the condition evaluates to false, the code inside the else block is executed.
  • The code inside the else block must contain statements that transfer control flow out of the current scope, such as return, throw, continue, or break. This ensures that the code after the guard statement can only be executed when the condition is met.

For example, in the context of error handling:

func process(number: Int?) {
    guard let number = number else {
        print("Error: Missing number")
        return
    }
    
    // Use 'number' safely here
    print("Number is \(number)")
}

process(number: 10)  // Output: Number is 10
process(number: nil) // Output: Error: Missing number

In the above example, the guard statement ensures that the function process can only proceed if a non-nil value is provided for number. If number is nil, the guard statement's else block is executed, printing an error message, and then the function exits early with return, preventing further execution of the code in the function.

Here's another example:

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

// Example usage:
greet(person: "Alice") // Prints: Hello, Alice!
greet(person: nil) // Prints: No person to greet!

In the above example:

  • The greet function takes an optional String parameter person.
  • The guard let name = person else { ... } statement unwraps the optional person. If person is nil, the guard block is executed, which prints a message and returns from the function.
  • If person is not nil, the code after the guard statement continues to execute, and the function greets the person by printing a message.

In essence, guard provides a way to ensure that the function's requirements for the input are met, and if not, it bails out early with an error. guard statements are often used to handle optional unwrapping.