In Swift, guard let is often used for early exits when certain conditions aren’t met, particularly when dealing with optional values. Here’s an example that demonstrates the use of guard let for safely unwrapping an optional value within a function:

func processUserInput(input: String?) {
    guard let unwrappedInput = input else {
        print("Input was nil, exiting function.")
        return
    }
    print("Input was: \(unwrappedInput)")
}
 
// Example usage:
processUserInput(input: "Hello, World!")  // Prints: Input was: Hello, World!
processUserInput(input: nil)              // Prints: Input was nil, exiting function.

In this example:

  • input is an optional string, which means it could be nil.
  • The guard let statement attempts to unwrap the optional input.
  • If input is not nil, its unwrapped value is assigned to unwrappedInput, and the function continues to execute the print statement using unwrappedInput.
  • If input is nil, the code inside the else block is executed, which prints a message and then exits the function by using return. This prevents the rest of the function from executing with an invalid state.