0

I came across this behavior that I don't really understand.

enum Key: String, Encodable {
    case Key1
    case Key2
}

let dict: [Key: String] = [.Key1: "Value1", .Key2: "Value2"]
let data = try! JSONEncoder().encode(dict)
let json = String(data: data, encoding: .utf8)!
// json value is ["Key1", "Value1", "Key2", "Value2"], which is an Array
// I expect json value to be ["Key1": "Value1", "Key2": "Value2"]

When I replace enum keys with String keys it works as expected. I'm using Swift 5.5.

Is this a bug or am I missing something?

SirDeleck
  • 121
  • 1
  • 6
  • 1
    It's "normal" behavior: https://forums.swift.org/t/jsonencoder-bug-when-dictionary-key-is-enum/40418 https://stackoverflow.com/questions/44725202/swift-4-decodable-dictionary-with-enum-as-key https://stackoverflow.com/questions/66114149/why-does-int-enum-as-dictionary-key-produce-different-json-string-than-int-as-d – Larme Mar 17 '22 at 10:06
  • With your "simple" sample, a quick fix could be `let dictmapped = dict.reduce(into: [String: String](), { $0[$1.key.rawValue] = $1.value })`. – Larme Mar 17 '22 at 10:10
  • @Larme thanks for your answer. I'll mark my question as duplicate. – SirDeleck Mar 17 '22 at 10:13
  • 1
    This has been resolved in Swift 5.6 [SE-0320-codingkeyrepresentable](https://github.com/apple/swift-evolution/blob/main/proposals/0320-codingkeyrepresentable.md) – vadian Mar 17 '22 at 10:16

0 Answers0