DEV Community

Khoa Pham
Khoa Pham

Posted on

2 2

Initializing Enums With Optionals in Swift

Original post https://github.com/onmyway133/blog/issues/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.

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)
Enter fullscreen mode Exit fullscreen mode

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

let name: String? = "venus"
let planet = name.flatMap({ Planet(rawValue: $0) })
Enter fullscreen mode Exit fullscreen mode

🎉

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more