Counting the number of objects that pass a test has a wide range of uses in many domains. However, Swift currently doesn’t give its users a simple way to perform this operation. While the behavior can currently be approximated with a
filter and a
count, this approach creates an intermediate array which it immediately discards. This is a bit wasteful.
To correctly avoid a potentially expensive intermediate array, you can use the Swift’s
lazy comes with the downside of being forced to use an
@escaping block. Lastly, you could rely on an eminently unreadable
These three solutions lie on a spectrum between “easy to write, but include performance traps” to “performant, but require Swift arcana to write”.
Swift 5.0 would avoid a performance trap and provide a simple interface for users to both read and write. Autocomplete should present it to them handily as well.