简体   繁体   中英

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. Perhaps it wasn't in the core library at the time? Anyway the map/reduce can be replaced with one call to flatMap. Also Zip2 has been renamed. The new solution is

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

And if you run this in the swift repl environment:

> 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)")
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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