[英]How do you join two arrays in Swift combing and preserving the order of each array? (Interleaving arrays in swift)
我有兩個數組,我需要保留順序
let a = ["Icon1", "Icon2", "Icon3",]
let b = ["icon1.png", "icon2.png", "icon3.png",]
如果我將兩者結合起來
let c = a + b
// [Icon1, Icon2, Icon3, icon1.png, icon2.png, icon3.png]
如何獲得以下結果?
[Icon1, icon1.png, Icon2, icon2.png, Icon3, icon3.png]
2015年12月16日更新:不知道為什么我不認識到flatMap是一個很好的候選人。 也許當時它不在核心庫中? 無論如何,可以通過一次調用flatMap來替換地圖/縮小。 Zip2也已重命名。 新的解決方案是
let c = Zip2Sequence(a,b).flatMap{[$0, $1]}
並且如果您在迅速的repl環境中運行此命令:
> let c = Zip2Sequence(a,b).flatMap{[$0, $1]}
c: [String] = 6 values {
[0] = "Icon1"
[1] = "icon1.png"
[2] = "Icon2"
[3] = "icon2.png"
[4] = "Icon3"
[5] = "icon3.png"
}
原始答案如下:
這是我一起玩耍的一種方式
let c = map(Zip2(a,b), { t in
[t.0, t.1]
})
let d = c.reduce([], +)
或內聯
let c = map(Zip2(a,b), { t in
[t.0, t.1]
}).reduce([], +)
拉鏈似乎不必要。 我想有一種更好的方法。 但基本上,我將它們壓縮在一起,然后將每個元組轉換為一個數組,然后展平該數組。
最后,簡短一點:
let c = map(Zip2(a,b)){ [$0.0, $0.1] }.reduce([], +)
如果兩個數組相互關聯且大小相同,則只需在一個循環中一次追加一個數組即可:
let a = ["Icon1", "Icon2", "Icon3"]
let b = ["icon1.png", "icon2.png", "icon3.png"]
var result:[String] = []
for index in 0..<a.count {
result.append(a[index])
result.append(b[index])
}
println(result) // "[Icon1, icon1.png, Icon2, icon2.png, Icon3, icon3.png]"
只是為了好玩,這就是它作為函數的樣子:
func interleaveArrays<T>(array1:[T], _ array2:[T]) -> Array<T> {
var result:[T] = []
for index in 0..<array1.count {
result.append(array1[index])
result.append(array2[index])
}
return result
}
interleaveArrays(a, b) // ["Icon1", "icon1.png", "Icon2", "icon2.png", "Icon3", "icon3.png"]
可能可以幫助您。
let aPlusB = ["Icon1" : "icon1.png" , "Icon2" : "icon2.png" , "Icon3" : "icon3.png"]
for (aPlusBcode, aplusBName) in aPlusB {
println("\(aPlusBcode),\(aplusBName)")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.