Last active
November 3, 2020 12:02
-
-
Save stephanecopin/4283175fabf6f0cdaf87fef2a00c8128 to your computer and use it in GitHub Desktop.
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
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