What is the drop(while:) array method in Swift?

Overview

In Swift, we can use the drop(while:) method on an array to return a new one by skipping elements while the condition specified is true, and returning the remaining elements.

Syntax

arr.drop(while: condition)

Parameters

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

  • condition: This parameter takes an element of the array, arr, as its argument, and returns True if the element should be skipped, or False if it should be included. Once the condition returns False, it will not be called again.

Complexity

The time complexity of the method is O(n). Here, ‘n’ is the length of the array.

Return value

This method returns a new array that contains the elements that were not dropped.

// 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.drop(while : {$0 < 10})) // drop numbers < 10
print(fruits.drop(while : {$0.count > 5})) // drop fruits whose length > 5
print(languages.drop(while: {$0 == "Swift"})) // drop string whose value = "Swift"
print(dates.drop(while : {$0 > 2000})) // drop years > 2000

Code explanation

  • Lines 2–5: We create some arrays.
  • Line 9: We call the drop(while:) method to drop the elements whose value is less than 10.
  • Line 10: We call the drop(while:) method to drop the elements whose string length is greater than 5.
  • Line 11: We call the drop(while:) method to drop the elements whose value is equal to the string value Swift.
  • Line 12: We call the drop(while:) method to drop the years that are greater than 2000.

Free Resources