← All languages
Swift function of the day
Random

Array.append

Add a new element to the end of an array.

Description

The append method adds the specified element to the end of the array. The array must be declared as a variable (using var) since append modifies it in place.

If the array does not have sufficient capacity to store the new element, it reallocates its storage with exponentially increasing capacity to amortize the cost of repeated appends.

append has O(1) amortized time complexity. Use append(contentsOf:) to add multiple elements from a sequence at once.

Arguments

NameDescriptionOptional
newElement The element to append to the array. No

Example

var numbers = [1, 2, 3]
numbers.append(4)
print(numbers)  // [1, 2, 3, 4]

Reference