Created
October 14, 2020 21:52
-
-
Save nh7a/e4d93a6ac537d5df18d3b25f0b89567a 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 UnknownDecodable: RawRepresentable, Decodable { | |
static var unknown: Self { get } | |
} | |
extension UnknownDecodable where RawValue: Decodable { | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
self = Self.init(rawValue: try container.decode(RawValue.self)) ?? .unknown | |
} | |
} | |
enum Foo: String, UnknownDecodable { | |
case foo | |
case unknown | |
} | |
struct Bar: Decodable { | |
var foo: Foo | |
} | |
let data1 = Data(#"{"foo":"foo"}"#.utf8) | |
let bar1 = try JSONDecoder().decode(Bar.self, from: data1) | |
bar1.foo == .foo | |
let data2 = Data(#"{"foo":"bar"}"#.utf8) | |
let bar2 = try JSONDecoder().decode(Bar.self, from: data2) | |
bar2.foo == .unknown // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment