Reputation: 33
I have an array of SKU numbers that I'm returning from Google Firestore "[428024, 4298212]".
I have written a function assigning the array of SKU's to a variable, but I am lost as to how to return that variable from the function.
let db = Firestore.firestore()
func getItems() -> [Int] {
let userID = Auth.auth().currentUser?.uid ?? "nil"
if (session.session != nil) {
self.data.removeAll()
db.collection("users").document(userID).getDocument { (document, error) in
if let document = document, document.exists {
let itemID = document.get("items") as! Array<Int>
print(itemID as Any)
// Prints "[428024, 4298212]"
return itemID
} else {
print("Document does not exist")
}
}
}
}
I'm getting the error "Unexpected non-void return value in void function, though I can see that the array of SKU's are being returned when it runs the "print(itemID as Any)" line.
Is there any mistake in how I have the function written?
Upvotes: 0
Views: 618
Reputation: 664
Querying the document through Firestore is written using a completion handler and trying to return any value from within this handler to your original function will deliver this error. Instead, you'll need to adjust your original function getItems()
to account for this as such:
let db = Firestore.firestore()
@State private var itemIDs: [Int] = []
func getItems(completion: @escaping (_ itemIDs: [Int]?) -> ()) {
let userID = Auth.auth().currentUser?.uid ?? "nil"
if (session.session != nil) {
self.data.removeAll()
db.collection("users").document(userID).getDocument { (document, error) in
if let document = document, document.exists {
let itemIDs = document.get("items") as! Array<Int>
completion(itemIDs) // call completion handler to return value
} else {
print("Document does not exist")
}
}
}
}
func callingYourFunction() {
self.getItems() { itemIDs in
if let ids = itemIDs {
// itemIDs exists -> do whatever else you originally intended to do with the ids
self.itemIDs = ids
}
}
}
Take a look at here if you want to learn more about closures and completion handlers! Hopefully this helps.
Upvotes: 1