by Sai gowtham

How to remove the last element from an array in Swift

We can remove the last element from an array by using the built-in removeLast() method in Swift.

Here is an example that removes the last element "oranges" from the following array.

var fruits = ["apples", "grapes", "pears", "oranges"]

fruits.removeLast()

print(fruits)

Output:

["apples","grapes", "pears"]

Similarly, we can also the popLast() method to remove the last element of an array.

var fruits = ["apples", "grapes", "pears", "oranges"]

let last = fruits.popLast() ?? "Empty array"

print(fruits) // ["apples","grapes", "pears"]

Note: The removeLast() and popLast() methods modifies the original array instead of creating a new array.

If you want to keep your original array untouched then you can use the dropLast() method.

var fruits = ["apples", "grapes", "pears", "oranges"]

print(fruits.dropLast())

print(fruits)

Output:

["apples","grapes", "pears"] # modified array

["apples", "grapes", "pears", "oranges"] # original array

The dropLast() method creates a new array instead of modifying the original array.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course