Reputation: 73
Is there a neat way to add two arrays in Swift:
IE I would like
let arrayA: [Float] = [1,2,3,4]
let arrayB: [Float] = [10,20,30,40]
let arrayResult:[Float] = arrayA.map({($0) + ***stuck here***})
I would like the arrayResult to be [11,22,33,44] and not [1,2,3,4,10,20,30,40] that you would get should you were to do:
let arrayResult = arrayA + arrayB
I know it is possible with:
for i in arrayA{
arrayResult[i] = arrayA[i] + arrayB[i]
}
But there must be a neater way than this using closures (that I can't fully grasp currently)
Thanks
Upvotes: 7
Views: 4648
Reputation: 1198
Indeed there is an easier way. Zip then map.
let arrayA: [Float] = [1,2,3,4]
let arrayB: [Float] = [10,20,30,40]
let arrayResult:[Float] = zip(arrayA,arrayB).map() {$0 + $1}
edit: Even prettier from the comment below:
let arrayResult:[Float] = zip(arrayA,arrayB).map(+)
Upvotes: 22