Writing Structs to Firebase

Hi, I have done some changes to my project (see link for more info). As a consequence of this, I´m having trouble writing data to Firebase.


I have this Struct:

struct CartItem {
    var name: String = ""
    var count = Int()
}

var itemsInCart : [CartItem] = []


Items are being added and removed with a minus, and a plussButton:

@IBAction func plussBUtton(_ sender: UIButton){
  
        if let index = itemsInCart.index(where: { $0.name == name })   {
            itemsInCart[index].count += 1
        } else {
            itemsInCart.append(CartItem(name: name, count: 1))
        }
            if let index = itemsInCart.index(where: { $0.name == name })   {
                counterLabel.text = "\(itemsInCart[index].count)"
            }
        }


@IBAction func minusButton(_ sender: UIButton)  {
            if let index = itemsInCart.index(where: {$0.name == name })   {
            if itemsInCart[index].count <= 1 {
                itemsInCart.remove(at: index)
                counterLabel.text = "0"
                totalAmount -= price
            } else {
                itemsInCart[index].count -= 1
                totalAmount -= price
            }
            if let index = itemsInCart.index(where: { $0.name == name })   {
                counterLabel.text = "\(itemsInCart[index].count)"
            }
        }
    }


And are being displayed in a tableView:

  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CheckOutCell") as! CheckOutTableViewCell
      
         let name = itemsInCart[indexPath.row].name
         let count = itemsInCart[indexPath.row].count
  
       
      cell.checkOutLabel.text = "\(count) Stk \(name)"
      
      return cell
    }



This all works perfectly, but now I have some issues writing to Firebase.

I have a orderButton that should write all data in the tableView to firebase, but when trying to do this:

@IBAction func orderButton(_ sender: UIButton) {
  
        //Write to firebase
        self.ref?.child("User").child(user).updateChildValues(["Order" : itemsInCart])
    }

I get the error: Cannot store object of type _SwiftValue at 0. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.


The goal is to write the data the same way as in the tableView:

cell.checkOutLabel.text = "\(count) Stk \(name)"


Note: There can be multible items: "2 Banana", "1 Apple", "3 Orange" and so on.

Replies

I'm not familiar with FireBase.


But, if I interpret correctly the message, you should try to cast Array to NSArray:


@IBAction func orderButton(_ sender: UIButton) {
 
        //Write to firebase
        let itemsInCartForFireBase = itemsInCart as NSArray
        self.ref?.child("User").child(user).updateChildValues(["Order" : itemsInCartForFireBase])
    }