Martheli
Martheli

Reputation: 981

Swift array to array of tuples

I have the following two arrays:

let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]

I would like to merge them into an array that looks like this:

[ ("monday", 1), ("tuesday", 2), ("wednesday", 3), ("thursday", 4), ("friday", 5)]

Upvotes: 10

Views: 4871

Answers (4)

Rob
Rob

Reputation: 437442

Use zip and map:

let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]

let tuples = Array(zip(xaxis, yaxis))  // or `zip(xaxis, yaxis).map { ($0, $1) }`

I know you asked about a tuple, but you can also consider a custom object, e.g.:

struct Day {
    let name: String
    let value: Int
}

let names = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let values = [1, 2, 3, 4, 5]

let days = zip(names, values).map(Day.init)

Upvotes: 24

nayem
nayem

Reputation: 7585

Try this:

let arrayMerged = zip(xaxis, yaxis).map { ($0, $1) }

or this:

let arrayMerged = Array(zip(xaxis, yaxis))

Upvotes: 3

3stud1ant3
3stud1ant3

Reputation: 3606

Try this:

let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]

let yaxis = [1, 2, 3, 4, 5]

var newArr = [(String, Int)]()

for i in 0..<xaxis.count {
        newArr.append((xaxis[i], yaxis[i]))
}
print(newArr)

Upvotes: 2

sCha
sCha

Reputation: 1504

let tuples = xaxis.enumerated().map { (index, value) in (value, yaxis[index]) }

Assuming yaxis's count always matches to xaxis.

Upvotes: 1

Related Questions