The following snippet:
struct Foo: Codable {
var x: Int
var y: String
}
enum E: Codable {
case foo(Foo)
case bar(Bar)
}
let v = E.foo(.init(x: 1, y: "2"))
let enc = JSONEncoder()
enc.outputFormatting = .prettyPrinted
let s = String(data: try! enc.encode(v), encoding: .utf8)!
print(s)
Outputs:
{
"foo" : {
"_0" : {
"x" : 1,
"y" : "2"
}
}
}
Is there a way to rename "_0" to something less horrible? Or even remove this extra level? Ideally without implementing encode/decode myself! (which will result into unwanted amount of boilerplate). I am flexible on the types themselves (e.g. can change enum to something else, etc).
I would consider:
struct E {
var foo: Foo?
var bar: Bar?
}
which is less ideal as I will have to ensure that there's one and only one non-nil option to keep the desired "enum" semantics.