Skip to content

Instantly share code, notes, and snippets.

@shaps80
Last active March 27, 2024 12:07
Show Gist options
  • Save shaps80/5136bcba4c396fe26342497cba57b02b to your computer and use it in GitHub Desktop.
Save shaps80/5136bcba4c396fe26342497cba57b02b to your computer and use it in GitHub Desktop.
Returns the number of elements matching the closure predicate.
import Swift
extension Sequence {
/// Returns the number of elements matching the closure predicate.
///
/// The `isIncluded` closure is called sequentially comparing each
/// element to determine the number of matches found.
/// This example shows how to find the number of elements matching
/// the given predicate.
///
/// let numbers = [1, 2, 3, 4]
/// let count = numbers.count { $0 < 3 }
/// // count == 2
///
/// If the sequence has no elements, `isIncluded` is never executed
/// and the result will be zero.
///
/// - Parameters:
/// - isIncluded: The closure to execute for each element to determine if
/// its a match
/// - Returns: The number of elements matching the closure predicate
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable func count(_ isIncluded: (Element) throws -> Bool) rethrows -> Int {
try reduce(0, { $0 + (try isIncluded($1) ? 1 : 0) })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment