Skip to content

Instantly share code, notes, and snippets.

@okla
Last active April 12, 2017 12:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okla/e5dd8fbb4e604dabcdc3 to your computer and use it in GitHub Desktop.
Save okla/e5dd8fbb4e604dabcdc3 to your computer and use it in GitHub Desktop.
Generic failable enum initialization with optional raw value in Swift 2.0
extension RawRepresentable {
init?(rawValue optionalRawValue: RawValue?) {
guard let rawValue = optionalRawValue, value = Self(rawValue: rawValue) else { return nil }
self = value
}
}
enum Position: Int { case First = 1, Second = 2 }
Position(rawValue: 0) // nil
Position(rawValue: 1) // .First
Position(rawValue: nil) // nil
Copy link

ghost commented Apr 12, 2017

Thanks! This helped tremendously!

However, Swift 3.0 requires each parameter in the guard statement to be declared with let:

guard let rawValue = optionalRawValue, let value = Self(rawValue: rawValue) else { return nil }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment