Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

drop
array
swift
communitycreator

What is the drop(while:) array 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

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
Drop some elements of an array based on some conditions

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.

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