Following situation: I use several devices that use a data struct. If I now expand the keys of the structure for newer versions, the new structs are encoded and then synchronized. As a result of the synchronization, the old data struct is used for decoding. When you then synchronize with the new devices, the new keys have been lost. How can I prevent this?
Use playground
import Foundation
struct OLD_API: Codable {
var text: String
}
struct NEW_API: Codable {
var text: String
let value: Int
}
// Init data on device with NEW data struct
var newDevice = NEW_API(text: "Dog", value: 200)
let data = try! JSONEncoder().encode(newDevice)
// .. sync to other devices (new to old)
// modified data on device with OLD data struct
var oldDevice = try! JSONDecoder().decode(OLD_API.self, from: data)
oldDevice.text = "Cat"
let newData = try! JSONEncoder().encode(oldDevice)
// .. sync to other devices (old to new)
// decode data on device with NEW data struct
newDevice = try! JSONDecoder().decode(NEW_API.self, from: newData)
print(newDevice)