Remove last element from an array in Swift

This tutorial will see how to delete the last element from an array in Swift.

Algorithm to remove last element from an array in Swift

  • Check whether the array has any elements or not by finding the count of the array elements.
    array.count: This function is used to find the count of elements from an array.
  • If the count is greater than 0 then remove the last element from the array using the removelast function.
    array.removeLast(): It removes the last element from an array and returns the modified array. This method can only be used on arrays with at least one element. If the array is empty it will give a runtime error.
  • Finally print the modified array.

Code

Here is the Swift code for removing the last element from an array.

var numbers = [1, 2, 3, 4, 5]
if numbers.count >0
{
    numbers.removeLast()
}
print(numbers)

Output:

[1, 2, 3, 4]

Also, refer to Delete all array elements in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *