PropertyListDecoder handle key not found

332 Views Asked by At

I have a struct that is saved in user defaults as a property list. If the struct changes (perhaps after a app version update), the PropertyListDecoder().decode generates an error for key not found. For example, I've added the key "passwordProtect" to my struct. When the app gets the stored struct from user defaults and tries to decode it, it gives the error Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "passwordProtect", intValue: nil)

The behavior I want in this case is that since passwordProtect is not set, I'd like to decode to my struct but with a default value for passwordProtect. I have already declared the variables default value in my struct. How can I get this behavior?

My struct:

struct Settings: Codable {
    var showTimeOutMessage: Bool = false
    var browserLimit: Bool = false
    var browserLimitSeconds: Int = 300
    var passwordProtect: Bool = false
    var metaTime: TimeInterval?

    init(fromDict : [String : Any?]?){...}
}

How I save it:

var settingsStruct = Settings(fromDict: formatedDict)
settingsStruct.metaTime = Date().timeIntervalSince1970
defaults.set(try? PropertyListEncoder().encode(settingsStruct), forKey:"settings")

How I retrieve it:

if let settingsData = defaults.value(forKey:"settings") as? Data {
    let settingsStruct = try! PropertyListDecoder().decode(Settings.self, from: settingsData)
    dump(settingsStruct)
}

Thanks!

0

There are 0 best solutions below