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

How to add elements of an array to another array's element in Swift?

let prices = [11, 22, 12, 32, 1, 5, 26] //this is a collection of initial prices of some items

let increasingAmount = prices.map{($0 * 0.5)} //this constant stores the amount the initial price will increase

I would like to add the increasingAmount to prices to get the new price for each item:

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

let prices = [11, 22, 12, 32, 1, 5, 26]
let increasingAmount = [5.5, 11, 6, 16, 0.5, 2.5, 13]
let newPrices = [16.5, 33, 38, 17, 5.5, 7.5, 39] //this is the desired output that i would like to achieve.

I could just modify the multiply value from 0.5 to 1.5 but I dont want that approach.

>Solution :

You can take advantage of the zip method which is going to return a sequence of tuple pairs of kind (prices_i, increasingAmount_i) and then use map to sum the elements

let prices = [11.0, 22.0, 12.0, 32.0, 1.0, 5.0, 26.0]
let increasingAmount = [5.5, 11, 6, 16, 0.5, 2.5, 13]
var newPrices: [Double] = zip(prices, increasingAmount).map { $0 + $1 }
// or shorter
newPrices = zip(prices, increasingAmount).map(+)

print(newPrices) // [16.5, 33, 38, 17, 5.5, 7.5, 39]

Note that you have to specify the type of newPrices because the swift compiler interprets prices array as [Int] and increasingAmount as [Double] and it has to know what you want newPrices to be.

This will work even if the arrays have different sizes, in that case zip will ignore the extra elements in the longest array.

You can play around with this here

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