Steve Steve - 2 years ago 81
Swift Question

Swift create one Int array from two int arrays by taking the max() at each index

I feel like this may call for

or something like it to solve but I'm not yet familiar enough with these and was hoping someone here might be. Lets say I have

arrayOne = [1, 3, 7]
arrayTwo = [2, 1, 10]

the expected result for what I'm trying to do would be

mergedArray = [2, 3, 10]

I know I can do this with a relatively simple for loop in a method but I am looking for a more "swift" way to do it if it's possible.

And Yes, both arrays will always be the same length.

Answer Source

This will work:

let arrayOne = [1, 3, 7]
let arrayTwo = [2, 1, 10]

let mergedArray = zip(arrayOne, arrayTwo).map{max($0, $1)}

First, pair each element in two arrays with zip, and then use map to each pair.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download