Skip to content

Instantly share code, notes, and snippets.

@giovani-pereira-ifood
Created July 27, 2020 17:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giovani-pereira-ifood/9c894627d45d16a43bd891f41c71170c to your computer and use it in GitHub Desktop.
Save giovani-pereira-ifood/9c894627d45d16a43bd891f41c71170c to your computer and use it in GitHub Desktop.
protocol UnknownCase: RawRepresentable, CaseIterable where RawValue: Equatable & Encodable {
static var unknownCase: Self { get }
}
extension UnknownCase {
init(rawValue: RawValue) {
let value = Self.allCases.first { $0.rawValue == rawValue }
self = value ?? Self.unknownCase
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let rawValue = try container.decode(RawValue.self)
let value = Self(rawValue: rawValue)
self = value ?? Self.unknownCase
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment