Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created January 23, 2018 14:57
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save chriseidhof/a89218cfff4194ac5522470e5cfd2eb8 to your computer and use it in GitHub Desktop.
Save chriseidhof/a89218cfff4194ac5522470e5cfd2eb8 to your computer and use it in GitHub Desktop.
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