gpt4 book ai didi

swift - 将变量添加到已保存的用户默认值变量

转载 作者:行者123 更新时间:2023-12-02 19:08:11 25 4
gpt4 key购买 nike

我已经下载了一个可以帮助我保存和加载自定义变量的 swift 文件:

import Foundation

protocol ObjectSavable {
func setToObject<Object>(_ object: Object, forKey: String) throws where Object: Encodable
func getToObject<Object>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable
}

extension UserDefaults: ObjectSavable {
func setToObject<Object>(_ object: Object, forKey: String) throws where Object: Encodable {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(object)
set(data, forKey: forKey)
} catch {
throw ObjectSavableError.unableToEncode
}
}

func getToObject<Object>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable {
guard let data = data(forKey: forKey) else { throw ObjectSavableError.noValue }
let decoder = JSONDecoder()
do {
let object = try decoder.decode(type, from: data)
return object
} catch {
throw ObjectSavableError.unableToDecode
}
}
}

enum ObjectSavableError: String, LocalizedError {
case unableToEncode = "Unable to encode object into data"
case noValue = "No data object found for the given key"
case unableToDecode = "Unable to decode object into given type"
}

我有这个 Person 结构:

struct Person: Encodable, Decodable {
var firstName: String
var lastName: String
var birthday: Date

init() {
self.firstName = "Tim"
self.lastName = "Cook"
self.birthday = Date()
}
}

而且我还有用于保存/加载 Person 结构的代码(使用上面的代码)

保存:

print("Saving object...")
let person: Person = Person()

do {
try UserDefaults.standard.setToObject(person, forKey: "person")
print("Object saved successfully")
} catch let err {
print("Error while saving object:\n\(err.localizedDescription)")
}

正在加载:

print("Loading object...")

do {
self.person = try UserDefaults.standard.getToObject(forKey: "person", castTo: Person.self)
print("Successfully load object:\n\(self.person!)")
} catch let err {
print("Error while loading object:\n\(err.localizedDescription)")
}

现在,所有这些都确实有效。但是,假设我以这种方式发布我的应用程序,然后我想向 Person 添加一个新变量,例如,我将添加一个 favorite:

struct Person: Encodable, Decodable {
var firstName: String
var lastName: String
var birthday: Date
var favorite: Bool = false

init() {
self.firstName = "Tim"
self.lastName = "Cook"
self.birthday = Date()
}
}

在更新之前,应用程序(在 Person 中没有 favorite 变量)将在没有 favorite 变量的情况下保存。更新后,应用程序将尝试使用 favorite 变量加载之前保存的 Person。这就是它失败的地方,因为旧版本数据中没有 favorite 变量。所以它会抛出一个错误。

我的问题是,当它从用户默认值解码 Person 时,如果没有找到任何匹配的变量(例如:favorite ), 而不是抛出错误,它会尝试自动创建它? (来自 var favorite = false)?

我的项目:https://github.com/orihpt/Encodable

提前致谢。

最佳答案

一种方法是将自定义解码代码添加到 Person 中:

enum CodingKeys : CodingKey {
case firstName
case lastName
case birthday
case favorite
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstName = try container.decode(String.self, forKey: .firstName)
lastName = try container.decode(String.self, forKey: .lastName)
birthday = try container.decode(Date.self, forKey: .birthday)
favorite = try container.decodeIfPresent(Bool.self, forKey: .favorite) ?? false
}

请注意,对于 favorite,我使用了 decodeIfPresent 并默认为 false


另一种方法是将favorite 声明为可选:

var favorite: Bool?

这将导致 favorite 被设置为 nil 如果它不存在于数据中,而不是您想要的 false。如果你真的想要 false,你可以使用隐式解包的可选 Bool?,你需要将 nil 更改为 false 每次解码时:

self.person = try UserDefaults.standard.getToObject(forKey: "person", castTo: Person.self)
if self.person.favorite == nil {
self.person.favorite = false
}

如果你担心你可能会忘记这样做,你可以让 getToObject 只接受符合这个协议(protocol)的对象:

protocol HasDefaults {
func changeNilsToDefaults()
}


extension UserDefaults {
func getToObject<Object: HasDefaults>(forKey: String, castTo type: Object.Type) throws -> Object where Object: Decodable {
guard let data = data(forKey: forKey) else { throw ObjectSavableError.noValue }
let decoder = JSONDecoder()
do {
let object = try decoder.decode(type, from: data)
object.changeNilsToDefaults() // notice this line!
return object
} catch {
throw ObjectSavableError.unableToDecode
}
}
}

并且你将无法执行 getToObject(forKey: "person", castTo: Person.self) 除非你使 Person 符合 HasDefaults:

extension Person : HasDefaults {
func changeNilsToDefaults() {
if self.person.favorite == nil {
self.person.favorite = false
}
}
}

关于swift - 将变量添加到已保存的用户默认值变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64747293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com