Swift Guard Statement Example

1. Introduction

Swift provides a guard statement as an elegant way to handle conditions in your code. The primary function of the guard statement is to ensure that certain conditions hold true in a program. If they don't, the guard statement's else block is executed, allowing you to exit the current scope cleanly.

2. Source Code Example

func greeting(to name: String?) {
    // Use guard to ensure name isn't nil
    guard let unwrappedName = name else {
        print("Name cannot be nil!")
        return
    }

    // If the guard statement succeeds, the unwrapped value can be used here
    print("Hello, \(unwrappedName)!")
}

greeting(to: "John")   // Valid name
greeting(to: nil)      // Nil name

Output:

Hello, John!
Name cannot be nil!

3. Step By Step Explanation

1. We define a function greeting(to:) that takes an optional String parameter, name.

2. Within the function, we use a guard statement to check if name is nil. The guard statement tries to bind the optional name to a non-optional constant unwrappedName.

3. If the binding succeeds (i.e., name is not nil), the code after the guard statement executes. This is where we print the greeting message using the unwrapped name.

4. If the binding fails (i.e., name is nil), the code within the else block of the guard statement is executed. In this case, we print an error message and exit the function using return.

5. We call the greeting(to:) function twice, once with a valid name and once with a nil value, to demonstrate both paths of execution.


Comments