I am trying to get the sum of prices * quantity for each item in an array.
I have this array:
var itemsInCart = [Order(productUID: "abc1", productName: "Shoe", productPrice: 100, quantity: 1), Order(productUID: "abc2", productName: "Shirt", productPrice: 150, quantity: 1), Order(productUID: "abc3", productName: "Pants", productPrice: 180, quantity: 1)]
So the thing I cannot figure out is how to combine the price and the quantity of each item in the array, to get and update my variable var totalCost = ""
I know I can use this piece of code, to get the sum of prices, but how to get the quantity too?
let sum = itemsInCart.reduce(0, )
Any help or points in the right direction would be much appreciated!
CodePudding user response:
You can try
let sum = itemsInCart.map { $0.productPrice * $0.quantity }.reduce(0, )
Or
let sum = itemsInCart.reduce(0) { $0 $1.productPrice * $1.quantity }