Swift Array append()

The append() method adds a new element at the end of the array.

Example

var city = ["Boston", "Tokyo", "Kathmandu"]

// add "London" to the city array city.append("London")
print(city) // Output: [ "Boston", "Tokyo", "Kathmandu", "London" ]

append() Syntax

The syntax of the array append() method is:

array.append(newElement)

Here, array is an object of the Array class.


append() Parameters

The append() method takes a single parameter:

  • newElement - element to be added to array

append() Return Value

The append() method doesn't return any value. It only updates the current array.


Example 1: Swift Array append()

var languages = ["Swift", "C", "Java"]

// add "C++" to the languages array languages.append("C++")
print(languages) var priceList = [12, 21, 35]
// add 44 to the priceList array priceList.append(44)
print(priceList)

Output

["Swift", "C", "Java", "C++"]
[12, 21, 35, 44]

Example 2: Adding One Array To Another Array

//  animals array
var animals = ["cat", "dog"]

// array of wild animals
var wildAnimals = ["tiger", "fox"]

// appending wildAnimals array to animals animals.append(contentsOf: wildAnimals)
print(animals)

Output

["cat", "dog", "tiger", "fox"]

In the above example, we have used the append() method and contentsOf property to append the elements of wildAnmals to animals.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges