count(where:)
About 2 min
count(where:) 관련
HACKING WITH SWIFT
What's new in Swift?
count(where:) | Changes in Swift 6.0
count(where:)
Available from Swift 6.0
SE-0220 (apple/swift-evolution
) 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.
Other Changes in Swift 6.0
Complete concurrency enabled by default | Changes in Swift 6.0
Complete concurrency enabled by default
Typed throws | Changes in Swift 6.0
Typed throws
Pack iteration | Changes in Swift 6.0
Pack iteration
Add Collection Operations on Noncontiguous Elements | Changes in Swift 6.0
Add Collection Operations on Noncontiguous Elements
Access-level modifiers on import declarations | Changes in Swift 6.0
Access-level modifiers on import declarations
Upgrades for noncopyable types | Changes in Swift 6.0
Upgrades for noncopyable types
128-bit Integer Types | Changes in Swift 6.0
128-bit Integer Types
BitwiseCopyable | Changes in Swift 6.0
BitwiseCopyable