I'm downloading a document from the Firestore Database. The document is a Post and contains an array of Comments. The comments are in an array that is stored in a dictionary by the "comments" key. Here are my simplified models.
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 ?? ""
}
}
And this how I load this data from 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)
}
}
}
For some reason newPost.comments array is always empty after initializing. Where is the problem?