Swift Array dropLast()

The dropLast() method drops the last element and returns the remaining elements in the array.

Example

var names = ["Dwight", "Kevin", "Creed"]

// drop last element // and return remaining elements print(names.dropLast())
// Output: ["Dwight", "Kevin"]

dropLast() Syntax

The syntax of the array dropLast() method is:

array.dropLast(i: Int)

Here, array is an object of the Array class.


dropLast() Parameter

The dropLast() method can take a single parameter:

  • i (optional) - number of elements to be dropped from the end of the array

dropLast() Return Value

  • returns the remaining elements in the array after dropping the last element

Example 1: Swift Array dropLast()

var country = ["Nepal", "Greece", "Spain"]

// drop last element and return remaining elements print(country.dropLast())
// original array is not modified print(country)

Output

["Nepal","Greece"]
["Nepal", "Greece", "Spain"]

Here, we have used the dropLast() method to drop the last element from the country array.

The original array is unchanged because dropLast() creates a new array instead of modifying the original array.


Example 2: Drop Multiple Number of Elements

var languages = ["Swift", "Python", "Java", "C", "C++"]

print("Original Array:", languages)

// remove last two elements from languages print("After dropLast():", languages.dropLast(2))

Output

Original Array: ["Swift", "Python", "Java", "C", "C++"]
After dropLast(): ["Swift", "Python", "Java"]

Here, languages.dropLast(2) removes the last 2 elements from languages and returns the remaining elements.

Did you find this article helpful?