2016-04-27 9 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()) 
} 

ループに入る必要はありません。

関連する問題