How to initialize Enums With Optionals in Swift

Issue #49

Today someone showed me https://medium.com/@_Easy_E/initializing-enums-with-optionals-in-swift-bf246ce20e4c which tries to init enum with optional value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
enum Planet: String {
case mercury
case venus
case earth
case mars
case jupiter
case saturn
case uranus
case neptune
}

extension RawRepresentable {
init?(optionalValue: RawValue?) {
guard let value = optionalValue else { return nil }
self.init(rawValue: value)
}
}

let name: String? = "venus"
let planet = Planet(optionalValue: name)

One interesting fact about optional, is that it is a monad, so it has map and flatMap. Since enum init(rawValue:) returns an optional, we need to use flatMap. It looks like this

1
2
let name: String? = "venus"
let planet = name.flatMap({ Planet(rawValue: $0) })

🎉

Comments