I think there's one common use case which is not covered by the current Codable
design: heterogeneous/dynamic decoding/encoding.
Many times in my developing, I wanted to decode part of a json into an intermediate representation, and later further decode that thing into a specific type.
struct Outer: Decodable {
let value: Int
let partialData: PartialJSONValue // PartialJSONValue is a placeholder for the heterogeneous json value type I need
}
let fullObject = try SomeDecoder().decode(Outer.self, from: someData)
if someDynamicCondition {
let a = SomeDecoder().decode(A.self, from: fullObject.partialData)
} else {
let b = SomeDecoder().decode(B.self, from: fullObject.partialData)
}
Because the current Codable
mechanism lacks ways to express PartialJSONValue
, I often resorted to something like [String: Any]
, which has its own fatal flaws (such as implementation difficulties and performance problems).