I have this function named “addToBasketButtonPressed()” to add item Id in my basket with default quantity 1 and the function name “incrementQty” called after else is checking if item to append already exist in basket and if it does then just increase the qty by 1.
@objc func addToBasketButtonPressed() {
//check if user is logged in or show login view
if MUser.currentUser() != nil {
downloadBasketFromFirestore(MUser.currentId()) { (basket) in
if basket == nil {
self.createNewBasket()
}else {
self.incrementQty(basketId: basket!.id, itemToUpdate: self.item!.id, deltaQty: 1)
let qty: Int = 1
let item = self.item.id
let dataTosave = (id: item!, qty: qty)
basket?.itemIds.append("\(dataTosave)")
print("basket id is \(basket!.id)")
print("current item name is \(self.item.name)")
self.updateBasket(basket: basket!, withValues: [kITEMIDS: basket!.itemIds!])
}
Here’s the function to increment qty by 1 which is erroring.
Error 1 = Value of optional type '[String : Any]?' must be unwrapped to a value of type '[String : Any]' on line = for item in itemArray { which I can fix by adding ! but I then get below error.
Error 2 = Value of tuple type '(key: String, value: Any)' has no member 'subscript' on last 3 lines
func incrementQty (basketId: String, itemToUpdate: String, deltaQty: Int) {
FirebaseReference(.Basket).document(basketId).getDocument { (documentSnapshot, error) in
if let error = error {
print(error.localizedDescription)
return
}
if let documentData = documentSnapshot?.data() {
print("item exists. update qty")
print("document data in itemIds", documentData)
let itemArray = documentData["itemIds"] as? [String: Any]
print("items in item array \(itemArray)")
for item in itemArray {
if item["Id"] == itemToUpdate {
print("checking document with id", item["Id"])
(item["Qty"] as! Int) + deltaQty
}
}
If I comment out the last 4 lines of code and amend below codes by commenting out “as? [String: Any]’ as shown below then in the debug window I can see the list of items. If I don’t comment out “as? [String: Any]” then it’s nil.
let itemArray = documentData["itemIds"] // as? [String: Int]
print("items in item array \(itemArray)")
My last question is after correcting above errors, how do I loop through this list to check if an item user is appending to basket already exists and if it does then just increase the quantity by 1 else add with default quantity 1?
note: data is extracted from Firebase Database.
your help on this will be greatly appreciated as I've spent few days searching for answers/solution but no luck.