[swift-users] Robust Codable coding

Howard Lovatt howard.lovatt at gmail.com
Fri Jun 23 19:36:33 CDT 2017

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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170624/538338c6/attachment.html>

More information about the swift-users mailing list