Swift array to array of tuples

匆匆过客 提交于 2019-12-05 20:05:27

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) }

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)

Try this:

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

or this:

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

Assuming yaxis's count always matches to xaxis.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!