Switching over an optional enum got easier in Swift 5.1
Up to Swift 5.0 you had to write .some(.daily). In 5.1 you can write .daily directly.
- Published
This article is also published elsewhere. https://iganin.hatenablog.com/entry/2019/12/08/172711
Originally written in Japanese. This is a translation of the same piece.
Introduction
Up to Swift 5.0, switching over an instance of an optional enum meant spelling out .some(T) and
.none:
enum Frequency {
case daily
case weekly
case monthly
case yearly
}
let frequency: Frequency? = .daily
switch frequency {
case .some(.daily): print("daily")
case .some(.weekly): print("weekly")
case .some(.monthly): print("monthly")
case .some(.yearly): print("yearly")
case .none: print("nil")
}
That is because Optional in Swift is itself expressed as an enum:
enum Optional<T> {
case some(T)
case none
}
Swift 5.1 changed how this switch can be written, so here it is.
Environment
- Swift 5.1
What changed
From Swift 5.1 on, you no longer need to write .some(T) when switching over an optional enum property.
Concretely, the code from the introduction can be written like this in Swift 5.1:
enum Frequency {
case daily
case weekly
case monthly
case yearly
}
let frequency: Frequency? = .daily
switch frequency {
case .daily: print("daily")
case .weekly: print("weekly")
case .monthly: print("monthly")
case .yearly: print("yearly")
case .none: print("nil")
}
Summary
A small change, but dropping .some means typing . now completes the list of cases you can branch on,
which makes it nicer to write.