2

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
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
John Tracid
  • 3,836
  • 3
  • 22
  • 33
  • @koen my enum already encodable because I use `String` as parent type. I don't have problems with encoding dictionary into JSON. My question is about why I'm getting different JSON types. – John Tracid Dec 13 '19 at 19:09

0 Answers0