Skip to content

Instantly share code, notes, and snippets.

@wafflespeanut
Last active September 14, 2018 07:51
Show Gist options
  • Save wafflespeanut/5bed95b307a5192153626b069624303c to your computer and use it in GitHub Desktop.
Save wafflespeanut/5bed95b307a5192153626b069624303c to your computer and use it in GitHub Desktop.
Merging inner object fields during encoding
public struct Object: Codable {
let context: String
}
public struct Activity: Codable {
var base: Object
var hello: String
public func encode(to encoder: Encoder) throws {
try base.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(hello, forKey: .hello)
}
}
let a = Activity(base: Object(context: "foobar"), hello: "hello")
let data = try! JSONEncoder().encode(a)
print(String(data: data, encoding: .utf8)!) // {"context":"foobar","hello":"hello"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment