Swift array to array of tuples

一曲冷凌霜 提交于 2020-01-13 15:05:47

问题


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

回答1:


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



回答2:


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)



回答3:


Try this:

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

or this:

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



回答4:


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

Assuming yaxis's count always matches to xaxis.



来源:https://stackoverflow.com/questions/45911256/swift-array-to-array-of-tuples

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