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()
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.
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.
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.
Let us give back to the community. Show your support to indie devs by downloading their apps from the banner displayed below. It will help them build great apps.
About the author
- Rizwan Ahmed - iOS Engineer. Twitter - https://twitter.com/rizwanasifahmed
Like our articles? Support us!