Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 5 Default Decododable implementation with only one exception

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 #>
}
like image 424
iVentis Avatar asked Dec 17 '19 07:12

iVentis


Video Answer


1 Answers

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.

like image 54
matt Avatar answered Oct 05 '22 22:10

matt