UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.