Swift: custom key-value encoding with Encodable conformance in struct

321 Views Asked by At
struct Struct: Encodable {
  let key: String
  let value: String
}

let aStruct = Struct(key: "abc", value: "xyz")

Given this struct and the default Encodable conformance provided, JSON encoding produces

{
    key = abc;
    value = xyz;
}

whereas instead I'd like to to encode it to

{
    abc = xyz;
}

how do I conform this struct to Encodable to end up with this result?

1

There are 1 best solutions below

0
On BEST ANSWER

Implement encode(to encoder: Encoder) and encode the struct as single dictionary

struct Struct: Encodable {
    let key: String
    let value: String
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode([key:value])
    }
}