Swift Combine Arrays: append, contentsOfThis Swift example pages combines arrays with the plus operator and the append contentsOf method.
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.Array
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.
Combined: The combined array has 6 elements. This is equal to the length of the two arrays "numbers" and "numbers2."
Swift program that combines two arrays
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
[10, 20, 30, 1, 2, 3]
Add many elements. Sometimes we want to append two or more elements to an array at once. We can use an addition expression for this purpose.
Swift program that appends multiple elements
// 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"]
["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.
Swift program that uses append, contentsOf
var animals = ["cat"]
var animals2 = ["bird", "fish", "dog"]
// Add the second array to the first.
// ... This is like using the "add" operator.
["cat", "bird", "fish", "dog"]
A summary. 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.