Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created January 3, 2021 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukeredpath/d7e58b43cc10c69476d9e66d4b786361 to your computer and use it in GitHub Desktop.
Save lukeredpath/d7e58b43cc10c69476d9e66d4b786361 to your computer and use it in GitHub Desktop.
Swift enum parsing using the swift-parsing library
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