Array Combine ExampleCombine arrays with the plus operator and the append contentsOf method.
This page was last reviewed on Aug 23, 2023.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.