[SWIFT] Cannot convert value of type'DocumentSnapshot' to expected argument type'QueryDocumentSnapshot'

I was instantiating a model from QueryDocumentSnapshot, so when I tried to generate it from DocumentSnapshot I got an error.

Difference between DocumentSnapshot and QueryDocumentSnapshot

This article is easy to understand. https://note.com/shion_consul/n/nd45e9f385696

Document Snapshot is a single piece of data that you get with .getDocument (). However, there is no guarantee of existence. QuerySnapshot is a block of documents obtained by db.collection ("posts"). AddEventLitener () etc., and each one is QueryDocumentSnapshot. QueryDocumentSnapshot is a child of QueySnapshot, so it seems that its existence is guaranteed.

Main subject

In my case, I used QueryDocumentSnapshot to create an instance from Model, but since QueryDocumentSnapshot was a class that inherited DocumentSnapshot, the error disappeared when I did the following.

struct Post {
   var name: String?

   init(document: DocumentSnapshot) {
        guard let data = document.data() else { return } //I think this is not a very good way to write
        if let name = data["name"] as? String {
            self.name = name
        }
    }
}


Recommended Posts

Cannot convert value of type'DocumentSnapshot' to expected argument type'QueryDocumentSnapshot'
Convert Map <K, V1> to Map <K, V2> (Convert Map Value)
Convert an array of strings to numbers
How to convert a value of a different type and assign it to another variable
Sample code to assign a value in a property file to a field of the expected type