'How can I properly read/write a users cart items document in firebase firestore on iOS?

class CartViewModel: ObservableObject {

@Published var cartItems = [Cart]()
@Published var errorMessage = ""

private var db = Firestore.firestore()


func fetchData() {
    
    db.collection("customers").document(Auth.auth().currentUser!.uid).collection("cart").addSnapshotListener{(querySnapshot, error) in
        
        guard let documents = querySnapshot?.documents else {
            print("no documents")
            return
        }
        self.cartItems = documents.compactMap { (queryDocumentSnapshot) -> Cart? in
            return try? queryDocumentSnapshot.data(as: Cart.self)
            
        }
        if let error = error {
            self.errorMessage = error.localizedDescription
            return
        }
        
    }
    
}}

struct Cart: Identifiable, Codable {
let db = Firestore.firestore()

@DocumentID var id: String?

var name: String
 var details: String
 var image: String
var price: Float
var quantity: Int

enum CodingKeys: String, CodingKey {
    case id = "id"
    case name = "name"
    case details = "details"
    case image = "image"
    case price = "price"
    case quantity = "quantity"
}}

This is the code for the struct and viewmodel. I tried following https://www.youtube.com/watch?v=3-yQeAf3bLE and replacing the Book with Cart. I am getting the following error in my CartViewModel "Type of expression is ambiguous without more context". The editor highlights the = in the self.cartItems = documents.compactMap



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source