Looking for info on "how to" Codable versioning

My Codable data struct is persisted, then I need to add more fields to the struct. How can I do this? Is there any good way to migrate Codable from one version to another? I think I need to at least have a version field in my struct?

I was hoping to see some examples. Anyway, my inside my head thinking:

  • Store the version number separately
  • Ib load, readd this version number first, if the version is not current, then load via old version Codable struct, migrate this to the current Codable struct, persist back out in new version.

The way that I have done it is to always output all of the fields unconditionally for encode. For decode I use decodeIfPresent and default (nil coalesce) to a reasonable value if the key is not present. If all of the changes are additive, this strategy works well, I think. It has the nice property that it is forward and backwardly compatible if you don't change the semantic meaning of the fields being saved.

2 Likes