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 benil
.- The
guard let
statement attempts to unwrap the optionalinput
. - If
input
is notnil
, its unwrapped value is assigned tounwrappedInput
, and the function continues to execute the print statement usingunwrappedInput
. - If
input
isnil
, the code inside theelse
block is executed, which prints a message and then exits the function by usingreturn
. This prevents the rest of the function from executing with an invalid state.