WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

Sequences get prefix(while:) and drop(while:) methods

Available from Swift 3.1

Paul Hudson      @twostraws

Two useful new methods have been added to the Sequence protocol: prefix(while:) and drop(while:). The former returns the longest subsequence that satisfies a predicate, which is a fancy way of saying that you give it a closure to run on every item, and it will go through all the elements in the sequence and return those that match the closure – but will stop as soon as it finds a non-matching element.

Let's take a look at a code example:

let names = ["Michael Jackson", "Michael Jordan", "Michael Caine", "Taylor Swift", "Adele Adkins", "Michael Douglas"]
let prefixed = names.prefix { $0.hasPrefix("Michael") }
print(prefixed)

That uses the hasPrefix() method to return the subsequence ["Michael Jackson", "Michael Jordan", "Michael Caine" – the first three elements in the sequence. It won't include "Michael Douglas", because that comes after the first non-Michael. If you wanted all the Michaels regardless of their position, you should use filter() instead.

The second new method, drop(while:) is effectively the opposite: it finds the longest subsequence that satisfies your predicate, then returns everything after it. For example:

let names = ["Michael Jackson", "Michael Jordan", "Michael Caine", "Taylor Swift", "Adele Adkins", "Michael Douglas"]
let dropped = names.drop { $0.hasPrefix("Michael") }
print(dropped)

That will return the subsequence ["Taylor Swift", "Adele Adkins", "Michael Douglas"] – everything after the initial Michaels.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Other changes in Swift 3.1…

Download all Swift 3.1 changes as a playground Link to Swift 3.1 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.