Programming languages have many syntaxes for combining 2 arrays. In Swift we use the plus operator. We can also append many elements (in an array) at once.
And with append contentsOf
, we can add arrays to arrays with a more verbose syntax. This can make some programs clearer and may be preferred.
Here we merge 2 arrays with an addition expression. We can use array variable names (like "numbers") or place the array expression directly in the addition statement.
let numbers = [10, 20, 30] let numbers2 = [1, 2, 3] // Combine the two arrays into a third array. // ... The first 2 arrays are not changed. let combined = numbers + numbers2 print(combined)[10, 20, 30, 1, 2, 3]
Sometimes we want to append two or more elements to an array at once. We can use an addition expression for this purpose.
// This must be a var. var colors = ["red"] // Add two elements to the array. // ... The arrays are combined. colors += ["orange", "blue"] // Add more elements. colors += ["silver", "gold"] print(colors)["red", "orange", "blue", "silver", "gold"]
Append
, contentsOf
With this method, we add the elements of one array to another. This has the same effect as the plus operator expressions. But it uses a normal method call.
var animals = ["cat"] var animals2 = ["bird", "fish", "dog"] // Add the second array to the first. // ... This is like using the "add" operator. animals.append(contentsOf: animals2) print(animals)["cat", "bird", "fish", "dog"]
In Swift we can use a plus to combine two arrays. But the append()
method is also worth using as it may be clearer to understand in some programs.