guard let for Early Exit
Unwrap and exit early on failure to reduce nesting.
The Idea of guard
guard checks a condition and, if it fails, exits the current scope. It is built for early exits that keep the happy path unindented.
func greet(_ name: String?) {
guard let name else {
print("No name")
return
}
print("Hello, \(name)")
}
greet("Ada")
greet(nil)guard let Syntax
Write guard let value = optional else { return }. Unlike if let, the unwrapped value stays in scope after the guard.
func double(_ text: String) {
guard let n = Int(text) else {
print("Not a number")
return
}
print(n * 2)
}
double("8")
double("x")All lessons in this course
- if let and Shorthand Binding
- guard let for Early Exit
- Binding Multiple Optionals
- Optional Pattern in switch and for