swift - 从字典中解析对象数组

标签 swift firebase google-cloud-firestore

我正在从 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/

相关文章:

ios - 为什么 UITableViewDataSource 或 UITableViewDelegate 不需要在 UITableView 中定义为弱?

arrays - Swift:创建一个具有不同对象实例默认值的数组

android - 如何确保用户只能在 firebase 中查看和访问自己的数据?

android - Firebase UI Auth 2.0.1 显示多个欢迎返回密码提示屏幕

java - Firestore凭据问题: Firebase app [default] already exists

swift - 当我编辑文本字段 textField(_ :shouldChangeCharactersInRange:replacementString:) not get called

ios - SwiftUI列表未显示所有项目

firebase - "The plugin cloud_firestore could not be built due to the issue above."如何解决

angularFire 2 的 Firebase Firestore 集合计数

android - Firestore 查询监听器