Does anyone know how to fix this issue?
Declared closure result 'InstockProduct?' is incompatible with contextual type 'InstockProduct'
class Database {
let db = Firestore.firestore()
var products = [InstockProduct]()
func getProductsInCollection(collection: String, handler: @escaping ([InstockProduct]) -> Void) {
db.collection("/products/instock/\(collection)").addSnapshotListener { querySnapshot, err in
guard let documents = querySnapshot?.documents else{
print("No document")
handler([])
return
}
self.products = documents.map { (queryDocumentSnapshot) -> InstockProduct in
return try? queryDocumentSnapshot.data(as: InstockProduct.self)
}
}
}
}
CodePudding user response:
You have products declared as [InstockProduct] (with non-optionals).
Also, in your closure, you have a return type specified as InstockProduct (again, non-optional).
But, in your return statement, you return an optional when you do this:
return try? queryDocumentSnapshot.data(as: InstockProduct.self)
Given that the try could fail, I'd change your code to return an optional and then use compactMap to remove those optionals from the final array:
self.products = documents.compactMap { (queryDocumentSnapshot) -> InstockProduct? in
return try? queryDocumentSnapshot.data(as: InstockProduct.self)
}
