JSONEncoder bug when dictionary key is enum?

import Foundation
enum Foo: String, Encodable { 
    case asc
    case desc
}
let foobar: [Foo: String] = [.desc: "testing"]
let encoder = JSONEncoder()
let data = try encoder.encode(foobar)
print(String(data: data, encoding: .utf8)!)

// Prints: ["desc","testing"]

This is a simplified example that demonstrates an issue I have been encountering in a project I'm working on. When the key of a dictionary is an enum, the JSONEncoder encodes it as an array and not as a dictionary.

I am able to reproduce this on both swift 5.3 and 5.2.4

You may want to check out this thread:

1 Like

Thanks @Lantua! Good to know why it's happening although it is a frustrating limitation. Since the enum has a string rawValue I can just transform the keys to strings prior to encoding.

Terms of Service

Privacy Policy

Cookie Policy