user6702783 user6702783 - 1 year ago 78
Swift Question

Swift: match two arrays into one array

I have two arrays

array1 = ["Fri","Sat","Sun"]
array2 = ["5","6","7"]

Now I want to create a newArray: ["Fri5","Sat6","Sun7"]
How to make it? Thanks in advance.

Answer Source

For a functional approach, use zip and map:

let array1 = ["Fri","Sat","Sun"]
let array2 = ["5","6","7"]

let result = zip(array1, array2).map { $0 + $1 }


["Fri5", "Sat6", "Sun7"]

zip creates a sequence of tuples [("Fri", "5"), ("Sat", "6"), ("Sun", "7")] and map then creates the final array by taking each tuple and combining the two Strings into a single String.

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