我想合并两个数组:
数组1
[["aaa","111"],["bbb","222"],["ccc","333"]]
阵列2
[["ddd","444"],["eee","555"],["fff","666"]]
我想要实现的是拥有一个具有尊重数组位置的值的单个数组,例如:
合并数组
[["aaa","111"],["ddd","444"],["bbb","222"],["eee","555"],["ccc","333"],["fff","666"]]
我怎么能用Swift 2做到这一点
let arr1 = [["aaa","111"],["bbb","222"],["ccc","333"]] let arr2 = [["ddd","444"],["eee","555"],["fff","666"]] let arr3 = arr1 + arr2 print(arr3) // [["aaa", "111"], ["bbb", "222"], ["ccc", "333"], ["ddd", "444"], ["eee", "555"], ["fff", "666"]]
在你的情况下,有特定的要求
let arr4 = zip(arr1, arr2).reduce([]) { (var arr, p:(Array, Array )) -> [[String]] in arr.append(p.0) arr.append(p.1) return arr } print(arr4) // [["aaa", "111"], ["ddd", "444"], ["bbb", "222"], ["eee", "555"], ["ccc", "333"], ["fff", "666"]]
根据您在笔记中提到的需求进行更新,您可以通过这种方式添加其余值(请先将arr4更改为var arr4 !!!)
var i = arr4.count / 2 while i < arr1.count { arr4.append(arr1[i++]) } while i < arr2.count { arr4.append(arr2[i++]) } print(arr4)
这给了你
[["aaa", "111"], ["ddd", "444"], ["bbb", "222"], ["eee", "555"], ["ccc", "333"], ["fff", "666"], ["zzz", "755"]]
它应该工作,即使其中一个数组是空的