This probably happens because JSONDecoder
cannot decode the stored data as a Preferences
instance any more. (and in that case you are returning a new instance Preferences()
)
What you can do is to add your new property as an optional, like this:
struct Preferences: Codable {
var soundsDisabled: Bool = false
var hapticsDisabled: Bool = false
var badgeNumberEnabled: Bool = false
var newProperty: Bool? = false
}
Then after decoding the old data, newProperty
will be nil
.
Update: Another, maybe better, solution would be to implement decoding yourself and when there is no property newProperty
set the default value:
struct Preferences: Codable {
var soundsDisabled: Bool = false
var hapticsDisabled: Bool = false
var badgeNumberEnabled: Bool = false
var newProperty: Bool = false
enum CodingKeys: String, CodingKey {
case soundsDisabled
case hapticsDisabled
case badgeNumberEnabled
case newProperty
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
soundsDisabled = try container.decode(Bool.self, forKey: .soundsDisabled)
hapticsDisabled = try container.decode(Bool.self, forKey: .hapticsDisabled)
badgeNumberEnabled = try container.decode(Bool.self, forKey: .badgeNumberEnabled)
// Decode newProperty and if not present set default value
newProperty = try container.decodeIfPresent(Bool.self, forKey: .newProperty) ?? false
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…