首页 > 解决方案 > 设置键值对后 Swift 字典返回 nil

问题描述

我正在使用表格视图控制器根据用户的职业来划分用户。我从字典开始,然后将其转换为结构以显示不同的部分。

字典接受一个字符串和用户对象数组:

var userByOccupation: [String: [User]] = [:]

我从后端(firestore)中提取职业,然后是用户,然后我将用户附加到指定的职业。但是,每当我设置值和键,然后从字典中打印出值计数时,它都会返回 nil。

我在 getUsers() 函数中遇到错误:

(见最后 3 行也标有其输出)

func getOccupations(){
    let db = Firestore.firestore()

    db.collection("occupations").getDocuments { (snapshot, err) in
        if let error = err {
            print("There was an error fetching documents: \(error)")
        } else {
            guard let documents = snapshot?.documents else { return }
            for document in documents {
                var occupationID = document.documentID
                db.collection("occupations").document(occupationID).collection("users").getDocuments(completion: { (secondSnapshot, error) in
                    if let err = error {
                        print("There was an error fetching documents: \(err)")
                    } else {
                        guard let secondDocuments = secondSnapshot?.documents else { return }
                        for document in secondDocuments {
                           self.getUsers(occupationID: occupationID, userID: document.documentID)
                        }
                    }
                })
            }
        }
    }
}

func getUsers(occupationID: String, userID: String) {
    let db = Firestore.firestore()
    db.collection("users").document(userID).getDocument(completion: { (snapshot, error) in
        if let err = error {
             print("There was an error fetching documents: \(err)")
        } else {
            if let dictionary = snapshot?.data() {
                let user = User(dictionary: dictionary  as [String: AnyObject])
                user.id = snapshot?.documentID
                print(occupationID) //MARK - prints: Janitor
                print(user.name) //MARK - prints: Jason
                self.userByOccupation[occupationID]?.append(user) //MARK: Setting the key & values
                print(self.userByOccupation.keys.count) //MARK - prints: nil.
            }
        }
    })
}

标签: arraysswiftdictionarystructgoogle-cloud-firestore

解决方案


最初使用?with self.userByOccupation[occupationID]which isnil会使语句无影响

self.userByOccupation[occupationID]?.append(user) 

改成

self.userByOccupation[occupationID] = [user] // or use +=    

推荐阅读