Optional Binding
Safely unwrapping optionals with if let and guard let instead of force-unwrapping.
2 menit membaca
Force-unwrapping with ! crashes your program the moment an optional turns out to be nil. Optional binding is the safe alternative: it checks whether a value exists and, if so, hands you the unwrapped value to use directly.
if let
let input = "42"
let parsed = Int(input) // Int?
if let number = parsed {
print("Got a number: \(number)")
} else {
print("Not a valid number")
}if let number = parsed reads as "if parsed has a value, bind it to a new constant called number and run this block." Inside the if block, number is a plain Int — no ! needed, because you're already inside the branch where Swift knows it's safe.
You can unwrap several optionals in one line, and the block only runs if all of them succeed:
let firstName: String? = "Ada"
let lastName: String? = "Lovelace"
if let first = firstName, let last = lastName {
print("\(first) \(last)")
}guard let
guard let does the same unwrapping, but inverted: it's for the case where you want to exit early if a value is missing, rather than nesting the "happy path" inside an if block.
func greet(_ name: String?) {
guard let name = name else {
print("No name provided")
return
}
// name is a plain String from here to the end of the function
print("Hello, \(name)!")
}guard requires the else block to exit the current scope — with return, break, continue, or by throwing an error. That requirement is what makes guard let so useful: once you're past it, the compiler guarantees the value is unwrapped for the rest of the function, with no extra nesting. Compare that to wrapping the entire function body in an if let — as more conditions stack up, that approach spirals into deeply nested code often called the "pyramid of doom," which guard avoids by handling each failure case and moving on.
Shorthand unwrapping
Since Swift 5.7, you can drop the repeated name when binding to a constant of the same name:
if let parsed {
print(parsed)
}
guard let name else { return }This is exactly equivalent to if let parsed = parsed — just shorter, and common enough in modern Swift code that it's worth recognizing even before you start using it yourself.
When to use which
Reach for if let when the unwrapped value is only needed for a small block of code. Reach for guard let when a missing value means "this function/loop iteration can't continue" — which, in practice, ends up being most of the time in real code.