What is the difference between removeLast() and popLast() methods of Array in Swift? They are doing the same thing, removing and returning the last element of the array. Can someone tell me when to use what?
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. Similarly, we can also use the popLast () method to remove the last element of an array.
When you call removeLast it will remove the last item from the array, and rather than returning back a new array it returns the item that it removed. So in the example above when removeLast () is called on allNumbers the number 10 is returned, and allNumbers is updated to only contain the numbers 1-9.
If you call dropLast () on that array it will return a new array that is the same as the original except without the last item. It’s also a really safe function to call because it isn’t mutating, so you won’t ever be changing the original array.
var allNumbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] let last = allNumbers.removeLast () Unlike dropLast, removeLast is a mutating function.
Those two methods are from AnyRandomAccessCollection
which Array conforms to.
popLast
returns nil
if the collection is empty.
removeLast
crashes if the collection is empty. It also has a discardable result.
popLast() returns an optional, so it can be nil; removeLast() returns the last element, not optional, so it will crash if the array is empty.
You need to use @discardableResult for popLast() if you don't use the returned element, while removeLast() doesn't need to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With