Using dropLast and removeLast in Swift
Arrays are used all the time when building apps, which means having easy ways to manipulate them is huge. Two super useful Array functions that you get out-of-the-box with Swift are dropLast
and removeLast
.
DropLast
var allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let allbutLast = allNumbers.dropLast()
Let’s say you have an array of the numbers 1-10. 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.
RemoveLast
var allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let last = allNumbers.removeLast()
Unlike dropLast
, removeLast
is a mutating function. 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. This can be really useful if you’re doing things like reordering arrays.