Difference Between popLast() & removeLast() in Swift

Sakshi
1 min readOct 4, 2023

--

popLast:

  • popLast is a method available on arrays.
  • It removes and returns the last element of the array if the array is not empty. If the array is empty, it returns nil.
  • It does not require you to specify the element to remove; it automatically operates on the last element.

Example:

var array = [1, 2, 3, 4] let lastElement = array.popLast() // lastElement will be 4, and array will be [1, 2, 3]

removeLast:

  • removeLast is also a method available on arrays.
  • It removes the last element from the array if the array is not empty, but it does not return the removed element.
  • It does not return anything; it has a Void return type.

Example:

var array = [1, 2, 3, 4] array.removeLast() // Removes the last element (4), and array will be [1, 2, 3]

In summary, the main difference is that popLast both removes and returns the last element from the array (or nil if the array is empty), while removeLast only removes the last element and does not return it. You would choose one over the other based on whether you need the removed element or not in your specific use case

--

--

Sakshi
Sakshi

Responses (2)