Swift 5 Default Decododable implementation with only one exception
Asked Answered
B

1

10

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 #>
}
Bullnose answered 17/12, 2019 at 7:25 Comment(3)
Why is this downvoted???? It’s a great question.Stroh
Perhaps put the location property in its own struct and ovride init(from:) there for only that property. Maybe a little overkill...Seagrave
thanks @JoakimDanielson I thought about that too.. and it works, but unfortunately it's not really nice either :/ It's a shame that apple doesn't provide anything like that.Bullnose
S
7

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.

Stroh answered 17/12, 2019 at 7:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.