if let and Shorthand Binding
Unwrap optionals within a scope, including Swift 5.7 shorthand.
Why Bind Optionals
An optional must be unwrapped before you can use the value inside. if let safely unwraps it only when a value exists.
let stored: Int? = 5
if let value = stored {
print(value)
}The if let Form
Write if let name = optional { ... }. Inside the braces, name is the unwrapped non-optional value. If the optional is nil, the block is skipped.
let input: String? = "Swift"
if let text = input {
print(text.count)
}All lessons in this course
- if let and Shorthand Binding
- guard let for Early Exit
- Binding Multiple Optionals
- Optional Pattern in switch and for