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 arrayvar gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook"]print("Initial array is ", gnaam)// remove last elementgnaam.removeLast()print("Last Element Removed: ", gnaam)// add new elementgnaam.append("Meta")// print new array valuesfor 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
Metato the array. - Line 10: We use the
for-inloop to print each element of the array.