如果在swift中创建了两个数组,就像这样:

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

如何将它们合并为[1,2,3,4,5,6]?


当前回答

类似地,使用数组字典可以:

var dict1 = [String:[Int]]()
var dict2 = [String:[Int]]()
dict1["key"] = [1,2,3]
dict2["key"] = [4,5,6]
dict1["key"] = dict1["key"]! + dict2["key"]!
print(dict1["key"]!)

如果“key”匹配,则可以遍历dict1并添加dict2

其他回答

不同数据类型的Marge数组:

var arrayInt = [Int]()
arrayInt.append(6)
var testArray = ["a",true,3,"b"] as [Any]
testArray.append(someInt)

输出:

["a", true, 3, "b", "hi", 3, [6]]

您可以用+连接数组,构建一个新数组

let c = a + b
print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

或者用+=将一个数组附加到另一个数组(或append):

a += b

// Or:
a.append(contentsOf: b)  // Swift 3
a.appendContentsOf(b)    // Swift 2
a.extend(b)              // Swift 1.2

print(a) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

如果你不喜欢操作符重载,或者更喜欢函数类型:

// use flatMap
let result = [
    ["merge", "me"], 
    ["We", "shall", "unite"],
    ["magic"]
].flatMap { $0 }
// Output: ["merge", "me", "We", "shall", "unite", "magic"]

// ... or reduce
[[1],[2],[3]].reduce([], +)
// Output: [1, 2, 3]

自Swift 2.0以来,我最喜欢的方法是扁平化

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

let c = [a, b].flatten()

这将返回flatbidirectionalcollection,所以如果你只是想要一个CollectionType,这就足够了,你将有免费的懒惰求值。如果你确实需要数组,你可以这样做:

let c = Array([a, b].flatten())

类似地,使用数组字典可以:

var dict1 = [String:[Int]]()
var dict2 = [String:[Int]]()
dict1["key"] = [1,2,3]
dict2["key"] = [4,5,6]
dict1["key"] = dict1["key"]! + dict2["key"]!
print(dict1["key"]!)

如果“key”匹配,则可以遍历dict1并添加dict2