Dictionary Coding Issue

Is anyone else having headaches with dictionary coding as of Swift 5.5 (SR‐15289)?

The workaround I am currently employing is to manually implement encode(to:) for any type with a dictionary member, check if the dictionary is empty and if so, encode an empty array instead of the property itself. But it is a fragile solution, because some properties are rarely empty and so go a long time before being noticed.

What I want to know is if anyone has found better workaround to use instead—especially one that is more centralized?

(Also the fact that I have not seen anyone else mention it either on the forums or bug reports tempts me to wonder if I have just gone insane and am imagining the whole thing. It seems like it ought to be causing widespread breakage for everyone.)

1 Like

The code snippet compiles and runs fine on my machine

% swift --version
swift-driver version: 1.26.9 Apple Swift version 5.5 (swiftlang-1300.0.31.1 clang-1300.0.29.1)
Target: x86_64-apple-macosx11.0

I'm seeing:

let encoded = try JSONEncoder().encode([Context(dictionary: [Key(string: "..."): Value(string: "...")])])
print(String(data: encoded, encoding: .utf8))
// Optional("[{\"dictionary\":[{\"string\":\"...\"},{\"string\":\"...\"}]}]")
let decoded = try JSONDecoder().decode([Context].self, from: encoded)
// [Context(dictionary: [Key(string: "..."): Value(string: "...")])]

let emptyEncoded = try JSONEncoder().encode([Context()])
print(String(data: emptyEncoded, encoding: .utf8))
// Optional("[{\"dictionary\":[]}]")  <-- an empty array here
let emptyDecoded = try JSONDecoder().decode([Context].self, from: emptyEncoded)
// [Context(dictionary: [:])]

Maybe there's something different in the implementation of swift-corelibs-foundation's JSONDecoder?

Yes, I just ran the code on macOS and it does not suffer from the problem; the trouble only appears on Linux.

(Thankfully macOS does not suffer any harm from the workaround either.)

I have noticed the same issue, and ended up implementing my own JSON parser and Codable conformances.

1 Like