Combine arrays. 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.
First example. 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.
Result The combined array has 6 elements. This is equal to the length of the two arrays "numbers" and "numbers2."
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]
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.
// 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.