How to migrate Codable object in Swift
Issue #83
As of swift 4 migration, we updated Cache to fully take advantage of Codable. It works for most cases, as we should usually declare our entity as typed safe object instead of array or json dictionary. And by conforming to Codable
, it is easily encoded and decoded to and from json data. And persisting them to Cache
is as easy as eating cookie.
The other day, I saw someone asking on how to migrate if the model changes https://github.com/hyperoslo/Cache/issues/153, and he likes the way Realm
does https://realm.io/docs/swift/latest/#migrations
1 |
|
I think we can rely on Codable
to the migration. FYI, here is the PR https://github.com/hyperoslo/Cache/pull/154
Class name change
I see Codable
is based on json, and the importance of json is its data structure, not the class name. So if you change the class name, it still works.
First, we save model of type Person
, later we load model of type Alien
. It works because the structure stays the same
1 | struct Person: Codable { |
Property change
If the property changes, then you need to do a little work of migration.
First, we save model of type Person1
, it has just fullName
. Later we change the model to Person2
with some new properties. To do the migration, we need to load model with old Person1
first, then construct a new model Person2
based on this Person1
. Finally, save that to Cache
with the same key.
1 | struct Person1: Codable { |