How to convert document to a custom object in Swift 5?

You need to initialize your struct and then you can extend the QueryDocumentSnapshot and QuerySnapshot like:

extension QueryDocumentSnapshot {
    func toObject<T: Decodable>() throws -> T {
        let jsonData = try JSONSerialization.data(withJSONObject: data(), options: [])
        let object = try JSONDecoder().decode(T.self, from: jsonData)
        
        return object
    }
}

extension QuerySnapshot {
    
    func toObject<T: Decodable>() throws -> [T] {
        let objects: [T] = try documents.map({ try $0.toObject() })
        return objects
    }
}

Then, try to call the Firestore db by:

db.collection("users").document((user?.email)!).getDocument() { (document, error) in
    guard error == nil else { return }
    guard let commentItem: [CommentResponseModel] = try? document.toObject() else { return }
     // then continue with your code
}

After contacting the firebase team, I found the solution I was looking for. It turns out I have to do import FirebaseFirestoreSwift explicitly instead of just doing import Firebase. The error will disappear after this. (And of course you'll need to add the pod to your podfile first:D)


You can do it as shown below:-

First create model class:-

import FirebaseFirestore
import Firebase

//#Mark:- Users model
struct CommentResponseModel {

    var createdAt : Date?
    var commentDescription : String?
    var documentId : String?

    var dictionary : [String:Any] {
        return [
                "createdAt": createdAt  ?? "",
                "commentDescription": commentDescription  ?? ""
        ]
    }

   init(snapshot: QueryDocumentSnapshot) {
        documentId = snapshot.documentID
        var snapshotValue = snapshot.data()
        createdAt = snapshotValue["createdAt"] as? Date
        commentDescription = snapshotValue["commentDescription"] as? String
    }
}

Then you can convert firestore document into custom object as shown below:-

func getJStoreUserFromDB() {
    db = Firestore.firestore()
    let user = Auth.auth().currentUser
    db.collection("users").document((user?.email)!).getDocument() { (document, error) in
        //        Convert firestore document your custom object
        let commentItem = CommentResponseModel(snapshot: document)
    }
}