Array.append() / insert() / remove()
Methods for adding, inserting, and removing elements in an array. Swift arrays are value types, so you must declare them with var to modify them.
Syntax
// Adds an element to the end of the array. array.append(element) // Inserts an element at the specified index. array.insert(element, at: index) // Removes the element at the specified index. array.remove(at: index) // Removes the last element. array.removeLast() // Removes the first element. array.removeFirst() // Removes all elements. array.removeAll()
Method List
| Method | Description |
|---|---|
| append(_ newElement:) | Adds a single element to the end of the array. |
| append(contentsOf:) | Adds all elements from another array to the end of the array. |
| insert(_ newElement:, at:) | Inserts an element at the specified index. |
| remove(at:) | Removes the element at the specified index and returns it. |
| removeFirst() | Removes the first element. Crashes if the array is empty. |
| removeLast() | Removes the last element. Crashes if the array is empty. |
| removeAll() | Removes all elements from the array. |
Sample Code
var fruits = ["apple", "orange", "grape"]
// Adds an element to the end.
fruits.append("peach")
print(fruits) // ["apple", "orange", "grape", "peach"]
// Adds all elements from another array.
fruits.append(contentsOf: ["strawberry", "melon"])
print(fruits) // ["apple", "orange", "grape", "peach", "strawberry", "melon"]
// Inserts an element at index 1.
fruits.insert("banana", at: 1)
print(fruits) // ["apple", "banana", "orange", ...]
// Removes the element at index 2.
let removed = fruits.remove(at: 2)
print(removed) // "orange"
// Removes the last element.
fruits.removeLast()
print(fruits.last ?? "") // "strawberry"
// Removes all elements.
fruits.removeAll()
print(fruits.isEmpty) // true
Notes
Because Swift arrays are value types (structs), you must declare them with var to modify them. Calling any of these methods on an array declared with let results in a compile error.
remove(at:) returns the removed element, making it convenient when you need to both delete and retrieve a value at the same time. Specifying an index that does not exist causes a runtime crash (Index out of range), so always check the array's size beforehand.
For searching elements, see contains() / firstIndex(). For transforming elements, see map() / compactMap().
If you find any errors or copyright issues, please contact us.