The dropLast() method drops the last element and returns the remaining elements in the array.
Example
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()
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
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.