Optional Pattern in switch and for
Match optionals with case let patterns.
Optionals in switch
You can switch directly on an optional. The cases .some(value) and .none match a present value or nil.
let value: Int? = 7
switch value {
case .some(let n):
print("Got \(n)")
case .none:
print("Nothing")
}The ? Shorthand Pattern
Writing case let x? is shorthand for .some(x). The trailing ? means "unwrap into x".
let value: String? = "Swift"
switch value {
case let text?:
print(text.uppercased())
case nil:
print("none")
}All lessons in this course
- if let and Shorthand Binding
- guard let for Early Exit
- Binding Multiple Optionals
- Optional Pattern in switch and for