If you need to add a new element at the end of a Swift array, then the Swift array append() method can be useful for you.
The array append()
method in Swift can add a new element at the end of an array.
In this tutorial, we will learn about the append()
method with code examples.
Below is the given syntax for the append()
method in Swift:
array.append(newElementToAdd)
In the above syntax, array
is our existing array. Inside the append() method, we have the parameter newElementToAdd which is the new element that will be added at the end of the array array
.
The append() method can take only one element which is the new element we want to add.
The Swift append() method never returns a value. This method only updates the existing array with the new element added.
Below is an example, where we are using the append() method to add a new element to an existing array:
var cities = ["LONDON", "HARRISBURG", "ZURICH"]
print(cities)
cities.append("GENEVA")
print(cities)
Output:
["LONDON", "HARRISBURG", "ZURICH"]
["LONDON", "HARRISBURG", "ZURICH", "GENEVA"]
Below is another example of using the append method where array elements of an array are added to an existing array:
var fruits = ["Apple", "Banana", "Mango"]
var newFruits = ["Strawberry", "Blueberry", "Grape"]
fruits.append(contentsOf: newFruits)
print(fruits)
Output:
["Apple", "Banana", "Mango", "Strawberry", "Blueberry", "Grape"]
In the above example, one thing is noticeable. In this example, we are using the contentsOf
property to append the elements of another array.
In this case, the existing array is updated and contains the element of the new array. You can also think of it as the merging of two arrays using the append()
method.