Мутирование модели Struct в закрытии - PullRequest
0 голосов
/ 15 ноября 2018

У меня есть модель пользователя, которая также обрабатывает сохранение информации об этом пользователе в моей базе данных (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"))
        }
    }
}
...