0

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!

Martin Claesson
  • 487
  • 6
  • 16
  • 1
    Like `JSONDecoder` when there is a key sometimes there sometimes not. Override the `init(from decoder)` of `Settings`, and use `decodeIfPresent()` – Larme Mar 18 '19 at 16:24
  • https://stackoverflow.com/questions/49709518/swift-4-jsondecoder-optional-variable – Larme Mar 18 '19 at 16:25

0 Answers0