Skip to content

Instantly share code, notes, and snippets.

@stephanecopin
Last active November 3, 2020 12:02
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 stephanecopin/4283175fabf6f0cdaf87fef2a00c8128 to your computer and use it in GitHub Desktop.
Save stephanecopin/4283175fabf6f0cdaf87fef2a00c8128 to your computer and use it in GitHub Desktop.
protocol EnumDecodable: RawRepresentable, Decodable {
static func defaultDecoderValue() throws -> Self
}
enum EnumDecodableError: Swift.Error {
case noValue
}
extension EnumDecodable {
static func defaultDecoderValue() throws -> Self {
throw EnumDecodableError.noValue
}
}
extension EnumDecodable where RawValue: Decodable {
init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(RawValue.self)
self = try Self(rawValue: value) ?? Self.defaultDecoderValue()
}
}
// May be used as
enum MediaType: String, Decodable {
static func defaultDecoderValue() throws -> MediaType {
return .other
}
case audio = "AUDIO"
case multipleChoice = "MULTIPLE_CHOICES"
case other
}
// or
enum MediaType: String, Decodable {
case audio = "AUDIO"
case multipleChoice = "MULTIPLE_CHOICES"
}
// Note that since `RawRepresentable` declares a `encode(coder:)` by default, any `EnumDecodable` can be also specified
// `Codable` with no changes to the code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment