Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import Foundation
enum Either<A,B> {
case left(A)
case right(B)
}
// Works only using Swift 4.1
extension Either: Codable where A: Codable, B: Codable {
enum CodingKeys: CodingKey {
case left
case right
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .left(let value):
try container.encode(value, forKey: .left)
case .right(let value):
try container.encode(value, forKey: .right)
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
let leftValue = try container.decode(A.self, forKey: .left)
self = .left(leftValue)
} catch {
let rightValue = try container.decode(B.self, forKey: .right)
self = .right(rightValue)
}
}
}
let values: [Either<String,Int>] = [
.left("Hi"),
.right(42)
]
let encoder = JSONEncoder()
let data = try! encoder.encode(values)
let str = String(data: data, encoding: .utf8)
print(str)
let decoder = JSONDecoder()
let result = try! decoder.decode([Either<String,Int>].self, from: data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment