-
-
Save TerryCK/f8b2415a0ce001c995fd3febddf5e4a2 to your computer and use it in GitHub Desktop.
Codable Either
This file contains hidden or 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
enum Either<A, B> { | |
case left(A) | |
case right(B) | |
} | |
extension Either: Decodable where A: Decodable, B: Decodable { | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
if let a = try? container.decode(A.self) { | |
self = .left(a) | |
} else if let b = try? container.decode(B.self) { | |
self = .right(b) | |
} else { | |
fatalError("Must be decoded into \(A.self) or \(B.self)") | |
} | |
} | |
} | |
extension Either: Encodable where A: Encodable, B: Encodable { | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
switch self { | |
case .left(let a): | |
try container.encode(a) | |
case .right(let b): | |
try container.encode(b) | |
} | |
} | |
} | |
// Example model | |
// You can directly decode `Foo` when the value of `bar` is either a `String` or `Bar` object. | |
struct Foo: Codable { | |
let bar: Either<String, Bar> | |
} | |
struct Bar: Codable { | |
let name: String | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment