Remove the last element from an array in Swift


In this tutorial, you will learn how to remove the last element from an array in Swift programming.

In Swift, there are three built-in methods that can be used to remove the last element from an array. Both of these methods are able to perform the task. But there is a difference between these three methods that you will learn by following this tutorial.

Removing the last array element using popLast()

The Swift popLast() method returns an optional. If it found the array empty, you will get back nil.

Below is given an example of removing the last array item using the popLast() method:

var cities = ["Philadelphia", "Pittsburgh", "Allentown", "Lakeland"]

cities.popLast()

print(cities)

Output:

["Philadelphia", "Pittsburgh", "Allentown"]

Removing the last array element using removeLast()

On the other hand, if you use the Swift removeLast(), it will return a non-optional value. In the case of an empty array, it will cause an error.

Below is the example of removing the last array item from an array using removeLast() method:

var cities = ["Philadelphia", "Pittsburgh", "Allentown", "Lakeland"]

cities.removeLast()

print(cities)
["Philadelphia", "Pittsburgh", "Allentown"]

Using dropLast() method to remove last array item

The dropLast() method doesn’t change or modify the original array during removing the last item. So if you don’t want your original array untouched, then you can use this method. Below is the example:

var cities = ["Philadelphia", "Pittsburgh", "Allentown", "Lakeland"]

let newArray = cities.dropLast()

print(newArray)

Output:

["Philadelphia", "Pittsburgh", "Allentown"]

In this tutorial, you have learned to use three methods that do the same thing in different ways. You can choose the one depending upon your needs.