Kristian Lofthus
Kristian Lofthus

Reputation: 55

Parse array of objects from dictionary

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?

Upvotes: 1

Views: 328

Answers (1)

Yury Imashev
Yury Imashev

Reputation: 2128

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.

Upvotes: 1

Related Questions