Swift – Append Another Array to this Array

To append another Array to this Array in Swift, call append(contentsOf:) method on this array, and pass the other array for contentsOf parameter.

append(contentsOf:) method appends the given array to the end of this array. This method modifies the contents of the array on which we are calling.

The syntax to append another array to the array is

array.append(contentsOf: anotherArray)

We can only append an array whose type is same as that of the elements in the array.

Example

In the following program, we will take an array fruits, and append another array moreFruits to the fruits array.

main.swift

var fruits = ["apple", "banana", "cherry"]
var moreFruits = ["mango", "guava"]

fruits.append(contentsOf: moreFruits)

print(fruits)

Output

The resulting array fruits gets appended with contents of moreFruits.

ADVERTISEMENT

Conclusion

In this Swift Tutorial, we learned how to append another array to this array.