When I use JSONEncoder
for structure like this:
struct A: Encodable {
var items: [String : Int]
}
let a = A(items: ["a": 1, "b": 2, "c": 3])
I get items
property as JSON object as expected: {"a": 1, "b": 2, "c": 3}
. But when I use enumeration for key like this:
enum E: String, Encodable {
case a, b, c
}
struct A: Encodable {
var items: [E : Int]
}
let a = A(items: [.a: 1, .b: 2, .c: 3])
I get items
as JSON array: ["a", 1, "b", 2, "c", 3]
. This is very confusing and also I can not find any documentation about this behaviour.
There is a way to have this code working by wrapping such dictionary into structure and implement Encodable protocol, but maybe there is simple way to do this?
struct A {
var items: W
}
struct W {
var items: [E : Int]
}
extension W: Encodable {
// etc
}