Is there a way to keep Swift's default implementation for a Decodable class with only Decodable objects but one exception? So for example if I have a struct/class like that:
struct MyDecodable: Decodable {
var int: Int
var string: String
var location: CLLocation
}
I would like to use default decoding for int
and string
but decode location
myself.
So in init(from decoder:)
i would like to have something like this:
required init(from decoder: Decoder) throws {
<# insert something that decodes all standard decodable properties #>
// only handle location separately
let container = try decoder.container(keyedBy: CodingKeys.self)
location = <# insert custom location decoding #>
}
Is there a way to keep Swift's default implementation for a Decodable class with only Decodable objects but one exception
Unfortunately no. To be Decodable all properties must be Decodable. And if you are going to write a custom init
you must initialize (and therefore decode) all properties yourself.
Apple knows this is painful and has given some thought to the matter, but right now a custom init
for a Decodable is all or nothing.
As has been suggested in a comment you might work around this by splitting your struct into two separate types. That way you could have a type with just one property, you initialize it manually, and you’re all done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With