1

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?

1 Answer 1

1

If I got your setup right, then in your Post initializer you need to replace

self.comments = dictionary["comments"] as? [Comment] ?? [Comment]()

With this code:

let commentsDataArray = dictionary["comments"] as? [[String: Any]]
let parsedComments = commentsDataArray?.compactMap {
    return Comment(dictionary: $0) 
}
self.comments = parsedComments ?? [Comment]()

This should allow you to create a new object from every element of the array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.