我正在从 Firestore 数据库下载文档。该文档是一个 Post
并且包含一个 Comment
数组。评论位于一个数组中,该数组通过 "comments"
键存储在字典中。这是我的简化模型。
class Post: NSObject {
var id: String?
var text: String?
var comments = [Comment]()
init(dictionary: [String: Any]) {
self.id = dictionary["id"] as? String
self.text = dictionary["text"] as? String ?? ""
self.comments = dictionary["comments"] as? [Comment] ?? [Comment]()
}
}
class Comment: NSObject {
var id: String?
var text: String?
init(dictionary: [String: Any]) {
self.id = dictionary["id"] as? String
self.text = dictionary["text"] as? String ?? ""
}
}
这就是我从 Firestore 加载这些数据的方式。
ref.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
let dictionaryData = document.data()
let newPost = Post(dictionary: dictionaryData)
newPost.id = document.documentID
self.posts.append(newPost)
let index = IndexPath(row: 0, section: self.posts.count - 1)
indexPathsToUpdate.append(index)
}
}
}
由于某些原因,newPost.comments
数组在初始化后始终为空。问题出在哪里?
最佳答案
如果我的设置正确,那么在你的 Post
初始化器中你需要替换
self.comments = dictionary["comments"] as? [Comment] ?? [Comment]()
使用这段代码:
let commentsDataArray = dictionary["comments"] as? [[String: Any]]
let parsedComments = commentsDataArray?.compactMap {
return Comment(dictionary: $0)
}
self.comments = parsedComments ?? [Comment]()
这应该允许您从数组的每个元素创建一个新对象。
关于swift - 从字典中解析对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52302404/