Arrays are one of the most widely used data structures in Swift, and we deal with a lot of array manipulations. One such manipulation is the removal of the last element from an array. The three useful methods to remove an element from an array are dropLast(), popLast(), and removeLast()

Let us give back to the community. Before getting started, show your support to indie devs by downloading their apps from the banner displayed below. It will help them build great apps.

dropLast()

We have an array of fruits, namely, [“Apple”,”Orange”,”Banana”]. Using the dropLast() method on the array will remove the last element (‘Banana’ in our case), and it will return the remaining array elements. dropLast() is the preferred method to remove an array because it is safe as it does not mutate the original array.

let fruits = ["Apple","Orange","Banana"]
let nonRoundFruits = fruits.dropLast()
print(nonRoundFruits) // ["Apple", "Orange"]

removeLast()

The next method is the removeLast() method. Unlike the dropLast() method, removeLast() method removes the last element from the original array and modifies it.

var fruits = ["Apple","Orange","Banana"]
let removedFruit = fruits.removeLast()
print(fruits) // ["Apple", "Orange"]
print(removedFruit) // Banana

There are two essential things to note here. The fruits array is mutable and hence it is declared as a ‘var’ If there are no elements in the array and if removeLast() method is invoked, the app will crash.

popLast()

The popLast() method is similar to the removeLast() method, but it has only one difference. When there are no elements in an array, and if the popLast() method is invoked, the app will not crash. Instead, it will return a nil value.

var fruits = ["Apple","Orange","Banana"]
let removedFruit = fruits.popLast()
print(fruits) // ["Apple", "Orange"]
print(removedFruit) // Optional("Banana")

References

[1] https://developer.apple.com/documentation/swift/array/1689751-droplast

[2] https://developer.apple.com/documentation/swift/array/2885764-removelast

[3] https://developer.apple.com/documentation/swift/array/1539777-poplast

About the author