简体   繁体   English

在Swift中,如何结合两个数组并保持每个数组的顺序? (快速交织数组)

[英]How do you join two arrays in Swift combing and preserving the order of each array? (Interleaving arrays in swift)

I have two arrays and I need to preserve the order 我有两个数组,我需要保留顺序

let a = ["Icon1", "Icon2", "Icon3",]
let b = ["icon1.png", "icon2.png", "icon3.png",]

If I combine the two I get 如果我将两者结合起来

let c = a + b
// [Icon1, Icon2, Icon3, icon1.png, icon2.png, icon3.png]

How do I get the result below? 如何获得以下结果?

[Icon1, icon1.png, Icon2, icon2.png, Icon3, icon3.png]

UPDATE 12/16/2015: Not sure why I didn't recognize that flatMap was a good candidate here. 2015年12月16日更新:不知道为什么我不认识到flatMap是一个很好的候选人。 Perhaps it wasn't in the core library at the time? 也许当时它不在核心库中? Anyway the map/reduce can be replaced with one call to flatMap. 无论如何,可以通过一次调用flatMap来替换地图/缩小。 Also Zip2 has been renamed. Zip2也已重命名。 The new solution is 新的解决方案是

let c = Zip2Sequence(a,b).flatMap{[$0, $1]} 

And if you run this in the swift repl environment: 并且如果您在迅速的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"
}

Original answer below: 原始答案如下:

Here's one way I whipped together for fun 这是我一起玩耍的一种方式

let c = map(Zip2(a,b), { t in
  [t.0, t.1]
})

let d = c.reduce([], +)

or inlining 或内联

let c = map(Zip2(a,b), { t in
  [t.0, t.1]
}).reduce([], +)

The zipping seems unnecessary. 拉链似乎不必要。 I imagine there's a better way of doing that. 我想有一种更好的方法。 But basically, I'm zipping them together, then converting each tuple into an array, and then flattening the array of arrays. 但基本上,我将它们压缩在一起,然后将每个元组转换为一个数组,然后展平该数组。

Finally, a little shorter: 最后,简短一点:

let c = map(Zip2(a,b)){ [$0.0, $0.1] }.reduce([], +)

If both arrays are related to each other and both have the same size you just have append one at a time in a single loop: 如果两个数组相互关联且大小相同,则只需在一个循环中一次追加一个数组即可:

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

and just for the fun this is how it would look like as a function: 只是为了好玩,这就是它作为函数的样子:

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

May be it can help you. 可能可以帮助您。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM