-2

I want to check if the array being passed to the CartViewController contains duplicates if so I want to increment the quantity variable by one. I'm just not sure where to start. Could I use a filter or something to check if the cart product object is already contained.

  struct Cart{
    var product: Product!
    var quantity: Int = 0

    init(prod: Product, quantity: Int = 1){
        product = prod
        self.quantity = quantity
    }
}

Pseudeo code

 var cartItems = [Product]()
  var finalCart = [Cart]()
override func viewDidLoad() {
        for product in cartItems{

            if finalCart.contains(product){
                finalCart increment index of current product by 1
            }else{
                finalCart.append(Cart.init())
            }
        }

    }
Bhugy
  • 711
  • 2
  • 8
  • 23
Terrance
  • 275
  • 1
  • 3
  • 11

2 Answers2

1

I hope this answer may help you. I am not familiar with struct, but I tried to solve your problem.

for product in cartItems{
        if finalCart.contains(product) {
            let index = finalCart.indexOf(product)
            let incrementedindex = index! + 1
            if cartItems.count > incrementedindex {
                let Product_Next = finalCart[incrementedindex]
                finalCart[index!] = Product_Next
                finalCart[incrementedindex] = product
            }else {
                //there is no more items in next indexes
            }
        }else {
            finalCart.append(Cart.init())
        }
    }
Ayath Khan
  • 213
  • 2
  • 10
1

Try this one.

if finalCart.containsObject(value) {
    finalCart.append(Cart.init())
}

No need to go into loop.