Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Array append()
In this tutorial, we will learn about the Swift array append() method with the help of examples.
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?