What is the dropLast(_:) method in Swift?

Overview

The dropLast(:_) method is used to remove a given number of elements at the end of the array and return a new array without those elements.

Syntax

arr.dropLast(n)

Parameters

n: This is the number of elements to drop off at the end of the array. It must be greater than or equal to zero.

Return value

This method returns new array that contains elements of the original array, except for the last n elements.

Example

// create arrays
let numbers = [2, 4, 5, 100, 45]
let fruits = ["orange", "mango", "grape"]
let languages = ["Swift", "Python", "Java", "C", "C++"]
let dates = [2022, 2012, 1998, 1774]
// invoke the dropLast(:_) method
// and print results
print(numbers.dropLast(2)) // [2, 4, 5]
print(fruits.dropLast(1)) // ["orange", "mango"]
print(languages.dropLast(4)) // ["Swift"]
print(dates.dropLast(0)) // [2022, 2012, 1998, 1774]

Explanation

  • Line 2–5: We create some arrays.
  • Line 9–12: We call the dropLast(_:) method on the arrays and print the results to the console.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources