please help me I have following struct and photos attached. I want to find the duplicate drinks and then delete duplicate and change the original drink quantity by adding one
var id = UUID()
var name : String
var price : Double
var extra : [DrinkExtra]
var unit : Int
var date : Date
}
I have tried following code but producing error and index out of range and no magic happened.
func mergeItem(){
for i in cartDrinks.indices.sorted(by: { name1, name2 in
return cartDrinks[name1].name > cartDrinks[name2].name
}) {
if cartDrinks[i].name == cartDrinks[i 1].name {
cartDrinks[i].unit = 1
cartDrinks.remove(at: i 1)
print("\(cartDrinks[i].name) \(cartDrinks[i].unit)")
} else {
print("Nothing found")
}
}
}
CodePudding user response:
Finally I have following code to complete my desired task. many thanks
func mergeItem(complete:() -> Void) {
var arr = cartDrinks
var alacartarr = cartexpress
arr.enumerated().forEach { index,item in
if let existIndex = arr.firstIndex(where: {item.name == $0.name }),
existIndex != index {
arr[existIndex].unit = arr[index].unit
arr[index].unit = 0
}
}
arr.removeAll(){$0.unit == 0}
self.cartDrinks.removeAll()
self.cartDrinks.append(contentsOf: arr)
alacartarr.enumerated().forEach { index,value in
if let existedIndex = alacartarr.firstIndex(where: {value.name == $0.name}),
existedIndex != index {
alacartarr[existedIndex].quantity = alacartarr[index].quantity
alacartarr[index].quantity = 0
}
}
alacartarr.removeAll(){$0.quantity == 0}
cartexpress.removeAll()
cartexpress.append(contentsOf: alacartarr)
complete()
}