Swift数组到元组数组

时间:2017-08-28 03:00:17

标签: swift tuples

我有以下两个数组:

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

我想将它们合并到一个如下所示的数组中:

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

4 个答案:

答案 0 :(得分:10)

使用zipmap

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

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

答案 1 :(得分:3)

试试这个:

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)

答案 2 :(得分:2)

试试这个:

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

或者这个:

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

答案 3 :(得分:1)

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

假设yaxis的计数始终与xaxis匹配。