Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting sum from price and quantity of an array

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 = ""

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

You can try

let sum = itemsInCart.map { $0.productPrice * $0.quantity }.reduce(0, +)

Or

let sum = itemsInCart.reduce(0) { $0 + $1.productPrice * $1.quantity }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading