Search code examples
arraysswiftdictionaryhigher-order-functions

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:

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 don't 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