给定两个独立的数组,我想将它们组合成一个单独的字典数组。
例如,给定:
var array = ["myDataOne", "myDataTwo", "myDataThree", "myDataFour"]
var array_second = ["apple", "banana", "orange", "kiwi"]
我希望我的阵列看起来像:
dictionnary[0] -> dataOne: "myDataOne", dataSecond: "apple"
dictionnary[1] -> dataOne: "myDataTwo", dataSecond: "banana"
dictionnary[2] -> dataOne: "myDataThree", dataSecond: "orange"
dictionnary[3] -> dataOne: "myDataFour", dataSecond: "kiwi"
我正在使用Xcode 7 B5在Swift 2中编码。
编辑:只是为了澄清,实际上最终的数组应该如下所示:
[[dataOne: "myDataOne", dataSecond: "apple"],[dataOne: "myDataTwo", dataSecond: "banana"],[dataOne: "myDataThree", dataSecond: "orange"],[dataOne: "myDataFour", dataSecond: "kiwi"]]
所以array[0]
必须返回类似[dataOne: "myDataOne", dataSecond: "apple"]
的内容,如果我array[0].dataOne
,则必须返回“myDataOne”。
答案 0 :(得分:0)
典型的程序方法是:
var result = [[String: String]]()
for var i = 0; i < array.count; i++ {
result.append(["dataOne": array[i], "dataSecond" : array_second[i]])
}
-
您也可以在功能上执行此操作:
let result = zip(array, array_second).map { ["dataOne" : $0.0, "dataSecond" : $0.1] }