如何将 Swift 中的两个数组合并并保留每个数组的顺序? (swift 中的交错数组)

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 是一个很好的候选者。也许当时它不在核心库中?无论如何,map/reduce 可以用一次调用 flatMap 来代替。 Zip2 也已重命名。新的解决方案是

let c = Zip2Sequence(a,b).flatMap{[[=10=], ]} 

如果你在 swift repl 环境中 运行 这个:

> let c = Zip2Sequence(a,b).flatMap{[[=11=], ]}
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)){ [[=14=].0, [=14=].1] }.reduce([], +)

说不定能帮到你。

let aPlusB = ["Icon1" : "icon1.png" , "Icon2" : "icon2.png" , "Icon3" : "icon3.png"]

    for (aPlusBcode, aplusBName) in aPlusB {

        println("\(aPlusBcode),\(aplusBName)")
 }

如果两个数组相互关联并且大小相同,您只需在一个循环中一次追加一个:

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