Last active
April 12, 2017 12:55
-
-
Save okla/e5dd8fbb4e604dabcdc3 to your computer and use it in GitHub Desktop.
Generic failable enum initialization with optional raw value in Swift 2.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! This helped tremendously!
However, Swift 3.0 requires each parameter in the
guard
statement to be declared withlet
:guard let rawValue = optionalRawValue, let value = Self(rawValue: rawValue) else { return nil }