user6702783 user6702783 - 2 months ago 11
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

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 }
print(result)

Output:

["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.