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 returnsTrueif the element should be skipped, orFalseif it should be included. Once the condition returnsFalse, 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 arrayslet 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 resultsprint(numbers.drop(while : {$0 < 10})) // drop numbers < 10print(fruits.drop(while : {$0.count > 5})) // drop fruits whose length > 5print(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 than10. - Line 10: We call the
drop(while:)method to drop the elements whose string length is greater than5. - Line 11: We call the
drop(while:)method to drop the elements whose value is equal to the string valueSwift. - Line 12: We call the
drop(while:)method to drop the years that are greater than2000.