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

Overview

The dropFirst(:_) method is used to return a new array that contains all but the given number of initial elements of the original array.

Syntax

arr.dropFirst(n)

Parameters

  • arr: This is the array from which we want to return a new array.

  • n: This is the total number of elements to drop from the beginning of the array arr. It must be greater than or equal to zero.

Return value

A new array that contains elements starting after the specified number of elements n.

Example

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

Explanation

  • Line 2–5: We create some arrays.
  • Line 9–12: We call the dropFirst(_:) method on the array and print the results to the console.

Free Resources