gpt4 book ai didi

arrays - Swift 字典在设置键值对后返回 nil

转载 作者:行者123 更新时间:2023-11-28 11:34:35 27 4
gpt4 key购买 nike

<分区>

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

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

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.
}
}
})
}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com