Skip to content

Instantly share code, notes, and snippets.

@nh7a
Created October 14, 2020 21:52
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 nh7a/e4d93a6ac537d5df18d3b25f0b89567a to your computer and use it in GitHub Desktop.
Save nh7a/e4d93a6ac537d5df18d3b25f0b89567a to your computer and use it in GitHub Desktop.
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