Different methods to remove the last item from an array in Swift
• Rizwan Ahmed A • Array • swift, UIButton, iOS15, remove array elements, iOS 16, swift ios 15, droplast in swift, removeLast in swift, how to remove element from an array
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()
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.
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.
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.
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
- Rizwan Ahmed - iOS Engineer. Twitter - https://twitter.com/rizwanasifahmed
More articles
Like our articles? Support us!