Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Array dropLast()
In this tutorial, we will learn about the Swift array dropLast() method with the help of examples.
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?