Adding elements of two arrays to each other

I have 2 types of type int like this

let arrayFirst = [1,2,7,9] let arraySecond = [4,5,17,20] 

I want to add the elements of each array, for example arrayFirst [0] + arraySecond [0], arrayFirst [1] + arraySecond [1] and so on and assign it to another array, so the result of the array will look like

[5, 7, 24, 29]

What would be the best practice to achieve this with swift3

+6
source share
2 answers

You can add both arrays like this

 let arrayFirst = [1,2,7,9] let arraySecond = [4,5,17,20] let result = zip(arrayFirst, arraySecond).map(+) print(result) 
+14
source
 let arrayFirst = [1,2,7,9] let arraySecond = [4,5,17,20] 

First zip(_:_:) them to create a sequence that acts like an array of pairs

 let zipped = zip(arrayFirst, arraySecond) // zipped acts like [(1, 4), (2, 5), (7, 17), (9, 20)] 

Then map(_:) over the tuples and apply the + operator:

 let result = zipped.map(+) // result is [5, 7, 24, 29] 

Together:

 let result = zip(arrayFirst, arraySecond).map(+) 
+8
source

Source: https://habr.com/ru/post/1012240/


All Articles