如果我有两个数组,例如
let one = [1,3,5] let two = [2,4,6]
我想以以下模式[one [0],two [0],one [1],two [1]等合并/交织数组。
//prints [1,2,3,4,5,6] let comibned = mergeFunction(one, two) print(combined)
什么是实现合并功能的好方法?
func mergeFunction(one: [T], _ two: [T]) -> [T] { var mergedArray = [T]() //What goes here return mergedArray }
如果两个数组的 长度相同, 那么这可能是一种解决方案:
let one = [1,3,5] let two = [2,4,6] let merged = zip(one, two).flatMap { [$0, $1] } print(merged) // [1, 2, 3, 4, 5, 6]
此处zip()枚举并行的数组,并返回一对对(2元素元组)的序列,每个数组中都有一个元素。flatMap()从每对创建一个2元素数组,并将结果连接起来。
zip()
flatMap()
如果数组的 长度 可以 不同, 则可以将较长数组的额外元素附加到结果中:
func mergeFunction<T>(one: [T], _ two: [T]) -> [T] { let commonLength = min(one.count, two.count) return zip(one, two).flatMap { [$0, $1] } + one.suffixFrom(commonLength) + two.suffixFrom(commonLength) }
Swift 3更新:
func mergeFunction<T>(_ one: [T], _ two: [T]) -> [T] { let commonLength = min(one.count, two.count) return zip(one, two).flatMap { [$0, $1] } + one.suffix(from: commonLength) + two.suffix(from: commonLength) }