Created
January 23, 2018 14:57
-
-
Save chriseidhof/a89218cfff4194ac5522470e5cfd2eb8 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
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