Created
January 3, 2021 01:45
-
-
Save lukeredpath/d7e58b43cc10c69476d9e66d4b786361 to your computer and use it in GitHub Desktop.
Swift enum parsing using the swift-parsing library
This file contains hidden or 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 where Self.RawValue == String { | |
/// Parses out the first matching raw value from a list of possible values, or returns nil. | |
/// | |
/// Example: | |
/// | |
/// enum SomeValues: String, CaseIterable { | |
/// case one | |
/// case two | |
/// } | |
/// | |
/// SomeValues.firstMatchingValue(in: [.one]).parse("one").output // SomeValues.one | |
/// SomeValues.firstMatchingValue(in: [.two]).parse("one").output // nil | |
/// | |
static func firstMatchingValue(in possibleValues: [Self]) -> AnyParser<Substring, Self> { | |
OneOfMany( | |
possibleValues.map { value in | |
StartsWith(value.rawValue[...]).map { value } | |
} | |
) | |
.eraseToAnyParser() | |
} | |
} | |
extension RawRepresentable where Self: CaseIterable, Self.RawValue == String { | |
/// Parses out the first matching raw value from all possible cases, or returns nil. | |
/// | |
/// Example: | |
/// | |
/// enum SomeValues: String, CaseIterable { | |
/// case one | |
/// case two | |
/// } | |
/// | |
/// SomeValues.firstMatchingValue.parse("one").output // SomeValues.one | |
/// SomeValues.firstMatchingValue.parse("six").output // nil | |
/// | |
static var firstMatchingValue: AnyParser<Substring, Self> { | |
firstMatchingValue(in: allCases as? [Self] ?? []) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment