Thank you for your reply!
they have built-in assumptions about how their types are represented
Yes, they have assumptions about the payload structure. However, sometimes it differs from built-in structure provided by Swift standard library, like the example of CGPoint .
Dates and Data specifically because they are ... likely to have the same representation across your entire payload
I agree. Not only Date and Data , but also all types are likely to have same representation across entire payload. The types indicate their only one representation by conforming to Codable .
The current problem is that, when it differs from assumption, there is no way to adopt "really" assumed format instead of built-in format.
So I realized that introducing strategies is not the best way for my motivation. A better way is to
- remove built-in
Codable conformance from some types ( Data , Date , CGPoint and more).
- let developers define their own
extension Foo: Codable to conform their "real" format.
My conclusion strays from the topic, so I want to create another thread to discuss it. Is it ok?
By the way, back to the topic.
The discussion whether or not to extend strategy might be worthy.
it felt like it too strongly violated the principles of encapsulation
I'm not sure what the principles of encapsulation means.
All types provide some initializers, except for init(from decoder: Decoder) . The .custom strategy just uses one initializer of them. In old days it hadn't, but now SE-0189 ensures it. So the customization doesn't violate encapsulation, isn't it?
Is there a use-case that this approach doesn’t meet, though?
The approach to wrap with adapter type is a good solution, but it can be exaggerated in some case.
For example, the code below fails with error.
struct A: Decodable {
let url: URL?
}
let data = """
{ "url": "" }
""".data(using: .utf8)!
try JSONDecoder().decode(A.self, from: data)
I want URL? to ignore thrown errors, but I should make adapter type or write own init(from:) to get it. Both ways seem too much for me. (Especially, when A has tons of other properties)