2016-04-27 72 views
-2

我想检查传递给CartViewController的数组是否包含重复项,如果是的话我想将数量变量加1。我只是不知道从哪里开始。我可以使用filter或其他东西来检查cart产品对象是否已包含在内。检查数组是否重复

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

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

Pseudeo代码

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()) 
      } 
     } 

    } 
+0

此答案可能会帮助您:http://stackoverflow.com/a/29730259/4557505 – HardikDG

回答

1

我希望这个答案可以帮助你。我不熟悉struct,但我试图解决你的问题。

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()) 
     } 
    } 
1

试试这个。

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

无需进入循环。