解析字典中的对象数组

时间:2018-09-12 19:47:38

标签: 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数组在初始化后始终为空。问题出在哪里?

1 个答案:

答案 0 :(得分:1)

如果我的设置正确,则需要在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]()

这应该允许您从数组的每个元素创建一个新对象。