How to remove the last element of an array in Swift

Overview

In Swift, we use the removeLast() method to remove the last element of an array.

Syntax

arr.removeLast()
Syntax to remove last element in Swift

Parameters

This method takes no parameters.

Return value

It returns the array arr but with its last element removed.

Example

// create an array
var gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook"]
print("Initial array is ", gnaam)
// remove last element
gnaam.removeLast()
print("Last Element Removed: ", gnaam)
// add new element
gnaam.append("Meta")
// print new array values
for coy in gnaam{
print(coy)
}

Explanation

  • Line 2: We create an array gnaam. It contains the names of the big tech companies.
  • Line 3: We print the array to the console.
  • Line 5: We call the removeLast() method on the array.
  • Line 6: We print the modified array because the last element, "Facebook", was removed.
  • Line 8: We append the value Meta to the array.
  • Line 10: We use the for-in loop to print each element of the array.