Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active March 1, 2019 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/4a2235ae9d442f1bcaa9e339d9210178 to your computer and use it in GitHub Desktop.
Save IanKeen/4a2235ae9d442f1bcaa9e339d9210178 to your computer and use it in GitHub Desktop.
Composing flat properties onto existing Codable values
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)!)
@IanKeen
Copy link
Author

IanKeen commented Mar 1, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment