It's not necessary to use JSONSerialization
here unless you're combining arbitrary values together. To stay within the Encodable
world you can simply use composition with custom encoding. I'd recommend staying structured and generic if you can.
struct CommonValues<AdditionalValues: Encodable>: Encodable {
let bar: Baz
let additionalValues: AdditionalValues
enum CodingKeys: CodingKey { case bar }
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(bar, forKey: .bar)
try additionalValues.encode(to: encoder)
}
}
That will encode bar
and additionalValues
at the same level in the resulting object.
You could also just define container values with arbitrary arity (at least until the compiler gives up):
struct EncodeMany<First, Second, Third>: Encodable where First: Encodable, Second: Encodable, Third: Encodable {
let first: First
let second: Second
let third: Third
func encode(to encoder: Encoder) throws {
try first.encode(to: encoder)
try second.encode(to: encoder)
try third.encode(to: encoder)
}
}