They explain here a subtle behaviour (to say the least) of JSONEncoder.
https://forums.swift.org/t/encoding-decoding-a-swift-dictionary-to-from-json/39989
A dictionary with Int or String key is encoded as dictionary.
But with other type key, it is encoded as an array. That seems to be the case with the enum.
I tested by catching error:
do {
let json = try JSONDecoder().decode(Json.self, from: jsonString.data(using: .utf8)!)
print("JSON", json)
} catch {
print("Error", error)
}
and got the same error message:
Error typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "variations", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
As you noted, if you replace the key type by String:
struct Json: Codable {
let variations: [String: String]
}
Then you get the expected result:
JSON Json(variations: ["plural": "tests", "singular": "test"])
Topic:
App & System Services
SubTopic:
General
Tags: