A quick followup about the AttributedString
Codable
conformance:
It already doesn't play well with snake case key coding strategy:
let input = AttributedString("Hello").settingAttributes(.init([.imageURL : URL(string: "https://example.com/")!]))
print("Before: ", input)
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let encoded = try! encoder.encode(input)
print("Encoded: ", String(data: encoded, encoding: .utf8)!)
let decoded = try! decoder.decode(AttributedString.self, from: encoded)
print("After: ", decoded)
Outputs the following:
Before: Hello {
NSImageURL = https://example.com/
}
Encoded: ["Hello",{"n_s_image_url":{"relative":"https:\/\/example.com\/"}}]
After: Hello {
}
So it suffers from a similar (but not quite the same) issue as described above, but doesn't fail parsing - it just has an 'empty' attribute covering the "Hello" String.
I think that there may be some learning from this - I hope that I can formulate it clearly:
First of all my intuition about 'dynamic' keys still holds with this example: namely that it doesn't play well with key coding strategies.
Secondly: Is there a way to fix this? The only thing I can think of is a mechanism to explicitly opt-out from key coding strategies. You actually already get that when decoding dictionaries keyed by String
s - the keys are left alone. I suspect that dictionary decoding wouldn't work in this case, however, but perhaps we can think of another way to opt out of the key coding? Another 'marker' protocol on CodingKey
, perhaps?