Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between removeLast() and popLast() methods of Array in Swift?

Tags:

arrays

swift

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?

like image 696
Raju Avatar asked Dec 21 '16 01:12

Raju


People also ask

How to remove the last element from an array in Swift?

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.

How does removelast () work in Python?

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.

What happens when you call droplast on an array?

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.

What is the difference between droplast () and removelast ()?

var allNumbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] let last = allNumbers.removeLast () Unlike dropLast, removeLast is a mutating function.


2 Answers

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.

like image 60
rmaddy Avatar answered Oct 08 '22 01:10

rmaddy


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.

like image 4
Mike Avatar answered Oct 08 '22 00:10

Mike