Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

drop
array
swift
communitycreator

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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]
Drop some number of last elements of an array

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.

RELATED TAGS

drop
array
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring