【发布时间】:2021-08-17 11:15:24
【问题描述】:
我正在尝试从 firestore 集合中获取数据并将其分配给字典数组。对于下面的这部分代码......我收到错误“从'QuerySnapshot投射?'到不相关的类型 '[[String : Any]]' 总是失败”并且控制台打印“不工作”。
guard let snap = snapshot as? [[String:Any]] else {
print("is not working")
completion(.failure(DatabaseError.failedToFetch))
return
}
这是完整的代码。
// fetches and returns all conversations for the user with passed in uid
public func getAllConversations(for uid: String, completion: @escaping(Result<[Conversation], Error>) -> Void) {
print("fetching all convos")
//NEW
let db = Firestore.firestore()
let CurrentUser = Auth.auth().currentUser?.uid
let ListRef = db.collection("users").document(CurrentUser!).collection("conversations")
// fetch the current users convo list
ListRef.getDocuments { snapshot, error in
if let err = error {
debugPrint("Error fetching documents: \(err)")
} else {
guard let snap = snapshot as? [[String:Any]] else {
print("is not working")
completion(.failure(DatabaseError.failedToFetch))
return
}
print("is working")
let conversations: [Conversation] = snap.compactMap({ dictionary in
guard let id = dictionary["id"] as? String,
let name = dictionary["name"] as? String,
let otherUserUID = dictionary["other_user-uid"] as? String,
let latestMessage = dictionary["latest-message"] as? [String:Any],
let date = latestMessage["date"] as? String,
let message = latestMessage["message"] as? String,
let isRead = latestMessage["is-read"] as? Bool else {
return nil
}
//save other user ID to a global var
self.test = otherUserUID
//assign data into an array of dictionaries
let latestConvoObject = LatestMessage(date: date, text: message, isRead: isRead)
return Conversation(id: id, name: name, otherUserUid: otherUserUID, latestMessage: latestConvoObject)
})
completion(.success(conversations))
}
}
}
【问题讨论】:
-
嗨 Mikhail,不,现在是从 firestore 获取数据,但是我如何将获取数据分配给字典数组?
-
for doc in (snapshot?.documents)! {}
-
我可以从 firestore 获取数据作为字典,但现在我想将该字典分配给数组,这可能吗?
-
有很多方法可以做到这一点,但有两个重要问题。 1) 为什么是字典数组? 2)问题中的代码似乎是一个对话数组,而不是字典。你能澄清一下吗?哦 - 作为旁注,在编程中,大写对象通常保留给结构和类,所以不要这样做
let ListRef = db.collection- 它应该是listRef。
标签: swift firebase google-cloud-firestore