3 Ways to Concatenate Arrays in Swift

Updated: April 17, 2023 By: Khue Post a comment

In the context of programming, concatenating arrays means joining two or more arrays into one array. This succinct example-based article will walk you through a couple of different ways to concatenate arrays in Swift (provided that the input arrays have the same data type). No more delays; let’s get to the main points.

Using the + operator

This operator creates a new array by adding the elements of two input arrays together.

Example:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

// Concatenate two arrays
let array3 = array1 + array2

print(array3)

// concatenate 3 arrays
let array4 = array1 + array2 + [7, 8, 9]
print(array4)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also use the += operator to get the job done. This operator appends the elements of one array to the end of another array. The first array is modified and the second array is unchanged.

Example:

var array1 = [1, 2, 3]
let array2 = [4, 5, 6]
array1 += array2

print(array1)

Output:

[1, 2, 3, 4, 5, 6]

Using the append(contentsOf:) method

This method adds the elements of another array or sequence to the end of an array. While the first array is modified, the second array or sequence is intact.

Example:

var arr1 = ["a", "b", "c"]
var arr2 = ["d", "e", "f"]

arr1.append(contentsOf: arr2)
print(arr1)

Output:

["a", "b", "c", "d", "e", "f"]

Using the insert(contentsOf:at:) method

This method inserts the elements of another array or sequence at a specified position in an array. The elements at that index and later indices are shifted back to make room. The first array is modified and the second array or sequence is unchanged.

Example:

var array1 = [1 ,2 ,3]
let array2 = [4 ,5 ,6]

 // insert contents of array2 at index zero
array1.insert(contentsOf:array2 ,at:0)

print(array1)

Output:

[4, 5, 6, 1, 2, 3]