Hi All,
I have started to use Codable and was looking for some advice. I want to make
the persisted data structure robust so that if I change the properties as the
code develops the new code can deserialise an old saved file. This is what I am
currently doing:
struct Project: Codable {
var ecsVersion = 0
var comment = ""
init() {}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
ecsVersion = try values.decodeIfPresent(Int.self, forKey: .ecsVersion)
?? ecsVersion
comment = try values.decodeIfPresent(String.self, forKey: .comment) ??
comment
}
}
The idea is that if I add fields the deserialisation doesn’t fail provided that
I provide a default value. However this presumably fails when you delete a
field because CodingKeys is now incorrect. (I say presumably because the
documentation doesn’t say what will happen.) Though not ideal, I can leave
disused properties in Projects to prevent the deserialisation error.
Any advice? Is there a better way?
Thanks in advance,
— Howard.
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users