我正在使用一个表视图控制器来根据用户的职业划分用户。我从字典开始,然后将其转换为结构以显示不同的部分。
字典采用字符串和用户对象数组:
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.
}
}
})
}
答案 0 :(得分:2)
将?
与self.userByOccupation[occupationID]
一起使用,nil
首先使该语句不起作用
self.userByOccupation[occupationID]?.append(user)
更改为
self.userByOccupation[occupationID] = [user] // or use +=