GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

count(where:)

Available from Swift 6.0

Paul Hudson      @twostraws

SE-0220 introduced a new count(where:) method that performs the equivalent of a filter() and count in a single pass. This saves the creation of a new array that gets immediately discarded, and provides a clear and concise solution to a common problem.

This example creates an array of test results, and counts how many are greater or equal to 85:

let scores = [100, 80, 85]
let passCount = scores.count { $0 >= 85 }

And this counts how many names in an array start with “Terry”:

let pythons = ["Eric Idle", "Graham Chapman", "John Cleese", "Michael Palin", "Terry Gilliam", "Terry Jones"]
let terryCount = pythons.count { $0.hasPrefix("Terry") }

This method is available to all types that conform to Sequence, so you can use it on sets and dictionaries too.

Note: count(where:) was originally planned for Swift 5.0 way back in 2019, but was withdrawn at the time for performance reasons.

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure and A/B test your entire paywall UI without any code changes or app updates.

Learn more here

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

Other changes in Swift 6.0…

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

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.