How to remove the last element from an array in Swift
In this tutorial, we are going to learn about how to remove the last element from a array in Swift.
Removing the last element
We can remove the last element from an array by using the built-in removeLast()
method in Swift.
Here is an example, that removes the last element "oranges"
from the following array.
var fruits = ["apples", "grapes", "pears", "oranges"]
fruits.removeLast()
print(fruits)
Output:
["apples","grapes", "pears"]
Similarly, we can also use the popLast()
method to remove the last element of an array.
var fruits = ["apples", "grapes", "pears", "oranges"]
let last = fruits.popLast() ?? "Empty array"
print(fruits) // ["apples","grapes", "pears"]
Note: The
removeLast()
andpopLast()
methods modifies the original array instead of creating a new array.
If you want to keep your original array untouched then you can use the dropLast()
method.
var fruits = ["apples", "grapes", "pears", "oranges"]
print(fruits.dropLast())
print(fruits)
Output:
["apples","grapes", "pears"] # modified array
["apples", "grapes", "pears", "oranges"] # original array
The dropLast()
method creates a new array instead of modifying the original array.