Last active
March 1, 2019 18:46
-
-
Save IanKeen/4a2235ae9d442f1bcaa9e339d9210178 to your computer and use it in GitHub Desktop.
Composing flat properties onto existing Codable values
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
struct WithSecret<T> { | |
let secret: String | |
let value: T | |
} | |
extension WithSecret: Decodable where T: Decodable { | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: AnyCodingKey.self) | |
self.secret = try container.decode(String.self, forKey: "secret") | |
self.value = try T.init(from: decoder) | |
} | |
} | |
extension WithSecret: Encodable where T: Encodable { | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: AnyCodingKey.self) | |
try container.encode(secret, forKey: "secret") | |
try value.encode(to: encoder) | |
} | |
} | |
struct User: Codable { | |
let name: String | |
let age: Int | |
} | |
let userWithSecret = WithSecret(secret: "foobar", value: User(name: "Ian", age: 36)) | |
//{"name":"Ian","age":36,"secret":"foobar"} | |
print(String(data: try JSONEncoder().encode(userWithSecret), encoding: .utf8)!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AnyCodingKey
: https://gist.github.com/IanKeen/3d226854c8c59a17e151a0022b71f6bb