Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift array to array of tuples

Tags:

swift

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)]
like image 686
Martheli Avatar asked Aug 28 '17 03:08

Martheli


4 Answers

Use zip and map:

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

let tuples = zip(xaxis, yaxis).map { ($0, $1) }
like image 70
Rob Avatar answered Nov 10 '22 04:11

Rob


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)
like image 29
3stud1ant3 Avatar answered Nov 10 '22 04:11

3stud1ant3


Try this:

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

or this:

let arrayMerged = Array(zip(xaxis, yaxis))
like image 3
nayem Avatar answered Nov 10 '22 03:11

nayem


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

Assuming yaxis's count always matches to xaxis.

like image 2
sCha Avatar answered Nov 10 '22 03:11

sCha