I'm looking for a way to count how many times the same product is added to an order (I'm new to Swift)
struct Product {
var name: String
var price: Double
}
struct Order {
var productsSold: [Product] = []
}
currentOrder = Order()
currentOrder.productsSold.append(products[1]) //From a JSON object "products"
currentOrder.productsSold.append(products[1])
currentOrder.productsSold.append(products[2])
currentOrder.productsSold.append(products[4])
I want to have to following result but I can't find a way to do it:
currentOrder.list() --> product_1 x2 // product_2 x1 // product_4 x1
I can only list all the products with:
//Inside struc Order
func listProductsSold() {
if productsSold.count>0 {
for product in productsSold {
product.printProduct()
}
}
}
//Inside struc Product
func printProduct() {
print("Nom: \(name), price: \(price), couleur: \(color)")
}
And then:
currentOrder.listProductsSold()
//Which give:
//Nom: Menu cheese, price: 17.0, couleur: rgb(247, 171, 56)
//Nom: Menu cheese, price: 17.0, couleur: rgb(247, 171, 56)
//Nom: Rouge n1, price: 18.0, couleur: rgb(166, 77, 121)
//Nom: Vin vigneron, price: 22.0, couleur: rgb(166, 77, 121)