问题
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