Изменить значение в моей UserModel (класс) на основе идентификатора пользователя - PullRequest
0 голосов
/ 10 февраля 2020

У меня есть UserModel:

class UserModel {

var uid: String?
var username : String?
var email: String?
var profileImageUrl: String?
var dateOfBirth: String?
var registrationDate: Int?
var isFollowing: Bool?
var accessLevel: Int?
var onlineStatus: Bool?

init(dictionary: [String : Any]) {
    uid = dictionary["uid"] as? String
    username = dictionary["username"] as? String
    email = dictionary["email"] as? String
    profileImageUrl = dictionary["profileImageUrl"] as? String
    dateOfBirth = dictionary["dateOfBirth"] as? String
    registrationDate = dictionary["userRegistrationDate"] as? Int
    accessLevel = dictionary["accessLevel"] as? Int
    onlineStatus = dictionary["onlineStatus"] as? Bool
    }
}

И у меня также есть значение типа [12ih12isd89: True]

Я хочу изменить значение "onlineStatus" для пользователя "12ih12isd89" в True, и я подумал, что правильный способ сделать это - updateValue (: forKey :). Но мой класс UserModel не имеет updateValue (: forKey:).

Как я могу использовать это в моей существующей модели?

Редактировать:

Как я могу получить данные:

func fetchAllUsers (completion: @escaping ([UserModel]) -> Void) {

    let dispatchGroup = DispatchGroup()
    var model = [UserModel]()

    let db = Firestore.firestore()
    let docRef = db.collection("users")

    dispatchGroup.enter()

    docRef.getDocuments { (querySnapshot, err) in

        for document in querySnapshot!.documents {
            let dic = document.data()
            model.append(UserModel(dictionary: dic))
        }
        dispatchGroup.leave()
    }
    dispatchGroup.notify(queue: .main) {
        completion(model)
    }
}

Ответы [ 2 ]

1 голос
/ 10 февраля 2020

Если ваш словарь значений содержит более одного пользователя, вы можете использовать для l oop, например:

var model = [UserModel]()

//Some initalization ...

let values =  ["12ih12isd89" : true]

for (k, v) in values {
    model.filter({$0.uid == k}).first?.onlineStatus = v
}
1 голос
/ 10 февраля 2020

Мне кажется, вам нужно найти нужный объект в массиве и обновить свойство

let dict =  ["12ih12isd89" : true]
var model = [UserModel]()

if let user = model.first(where: {$0.uid == dict.keys.first!}) {
    user.onlineStatus = dict.values.first!
}

В зависимости от того, что на самом деле ["12ih12isd89": true], вы можете изменить доступ с dict.keys.first! что я использовал

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...