4

As I am learning about the Codable protocol of Swift 4 and thinking about how this can be used, I want to understand what are the implications on the potential future evolution of a type when making it Codable.

In usual code, if I change a type by adding a property to it, I just need to update my local codebase to react to this change (by adding a new argument to my type initialiser calls for instance).

On the other hand, if my type had been Codable and I had already used it in combination with a distant server (by sending and receiving this type encoded as JSON) wouldn't it be pretty problematic to add new properties ?

For instance, say that I receive a JSON encoded by the previous version of my app (that was still stored by the server), and I try to decode it with the new version, the decoding process will fail as the data for the new property won't be available.

How should I deal with such situations ?
"Locking" my type at some point, forbidding it to evolve in the future ?
What would be the cleanest way to decode incompatible data if it was really needed ?

jscs
  • 63,694
  • 13
  • 151
  • 195
Pop Flamingo
  • 3,023
  • 2
  • 26
  • 64
  • 2
    Related: [What is the best way to handle versioning using JSON protocol?](https://stackoverflow.com/q/10042742) – jscs Jan 02 '18 at 16:29
  • @JoshCaswell That's interesting ! But that doesn't seem to solve the issue of receiving a JSON encoded by a previous version, does it ? – Pop Flamingo Jan 02 '18 at 16:32
  • @JoshCaswell Since in Swift all properties must be initialised, the only solution I would see is to make the new properties optional, but I don't know how the automatic decoding process would react to this... – Pop Flamingo Jan 02 '18 at 16:33
  • If your new field is not required, declare it to be optional and `Decodable` will gracefully handle its absence in JSON. If it's not optional and does not have a default value, then it's obviously not a backwards-compatible change. And if its a new property completely unrelated to what is exchanged with the web service, you might explicitly declare your `CodingKeys` and omit this field from that so it doesn't factor into `Decodable` at all. – Rob Jan 02 '18 at 16:34
  • 1
    I just said it was related! :) Not that it had all the answers. – jscs Jan 02 '18 at 16:35
  • @JoshCaswell Yes thank you !! :) – Pop Flamingo Jan 02 '18 at 16:38
  • @Rob Oh that's really interesting, especially how `Decodable` handles nil, didn't knew it was so easy ! Thank you ! :) – Pop Flamingo Jan 02 '18 at 16:39

0 Answers0