我有一个名为User
的对象,它符合Swift4中引入的Codable
。
例如,这个对象曾经是
struct User: Codable {
var firstName: String
}
我们使用PropertyListDecoder().decode(User.self, from: data)
和PropertyListEncoder().encode(value)
将User
编码成Data
,并将Data
解码成User
。
现在,我们将对象更新为
struct User: Codable {
var firstName: String
var isLoggedIn: Bool
}
如果我们的应用程序从旧的应用程序更新,旧的Data
存储在UserDefault
中。更新后,应用程序要做的第一件事就是获取这个Data
,并尝试使用PropertyListDecoder().decode(User.self, from: data)
解码成User
。但是,它给出了一个错误:
po PropertyListDecoder().decode(User.self, from: data)
▿ DecodingError
▿ keyNotFound : 2 elements
- .0 : CodingKeys(stringValue: "isLoggedIn", intValue: nil)
▿ .1 : Context
- codingPath : 0 elements
- debugDescription : "No value associated with key CodingKeys(stringValue: \"isLoggedIn\", intValue: nil) (\"isLoggedIn\")."
- underlyingError : nil
你知道在这种情况下我该如何处理模型迁移吗?我知道对于Coredata来说,有一些简单的方法可以处理这个问题,但我不知道如何在UserDefault中实现它。
发布于 2019-03-20 09:04:34
您可以实现解码初始化器并为isLoggedIn
设置默认值(如果没有默认值):
struct User: Codable {
var firstName: String
var isLoggedIn: Bool
enum Keys: CodingKey {
case firstName
case isLoggedIn
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decode(String.self, forKey: .firstName)
isLoggedIn = try container.decodeIfPresent(Bool.self, forKey: .isLoggedIn) ?? false
}
}
https://stackoverflow.com/questions/55252033
复制相似问题