我有一个用户模型,该模型还处理有关该用户的信息保存到我的数据库(Firestore)中。当用户更新其信息时,我需要将其保存到Firestore,但我也需要更新模型。我不确定如何处理此问题,目前正在获取“关闭无法隐式捕获变异的自身参数”。
我应该创建一个单独的处理程序类,还是该怎么做?
型号:
struct User {
var displayName: String?
var lastLoggedInAt: Int?
var createdAt: Int?
private(set) var questionsLeft: Int?
var currency: Int?
var dictionary: [String: Any]
init(dictionary: [String: Any]) {
self.displayName = dictionary["displayName"] as? String
self.lastLoggedInAt = dictionary["lastLoggedInAt"] as? Int
self.createdAt = dictionary["createdAt"] as? Int
self.questionsLeft = dictionary["questionsLeft"] as? Int
self.currency = dictionary["currency"] as? Int
self.dictionary = dictionary
}
mutating func setQuestionsLeft(to num: Int) {
questionsLeft = num
dictionary["questionsLeft"] = num
}
}
// MARK: Set Firestore User Data
extension User {
mutating func set(data: Data, then handler: Handler = nil) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let firestore = Firestore.firestore()
let ref = firestore.collection("users").document(uid)
ref.setData(data, merge: true) { (error) in
if let error = error {
handler?(.failure(error))
}
// update current user struct
// get an error
let keys = data.keys
for key in keys {
self.dictionary[key] = data[key]
}
self = User(dictionary: self.dictionary)
handler?(.success("Successfully Set User Data"))
}
}
}