How do I concatenate or merge arrays in Swift?

Hristo picture Hristo · Aug 5, 2014 · Viewed 242.3k times · Source

If there are two arrays created in swift like this:

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

How can they be merged to [1, 2, 3, 4, 5, 6]?

Answer

Martin R picture Martin R · Aug 5, 2014

You can concatenate the arrays with +, building a new array

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

or append one array to the other with += (or 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]