Blog / August 25, 2024 / 4 mins read / By Mahi Garg

Count with where clause (count(where:)) in Swift

In Swift, the count(where:) method is a powerful tool for filtering and counting elements in a collection that meet specific criteria. This method is part of the Swift Standard Library’s extensions to Sequence and allows for a concise and expressive way to determine how many elements in a collection match a given predicate.

count(where:) method is introduced in Swift 6.0 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. Keep in mind this is only available from Swift 6.0 only.

What is count(where:)?

The count(where:) method returns the number of elements in a collection that satisfy a specified condition (predicate). It’s a convenient way to count elements without having to filter the collection first and then count the resulting array, which makes the code both more readable and efficient.

Syntax

The general syntax for count(where:) is:

let count = collection.count(where: { predicate })
//or 
let count = collection.count { predicate }

Here, collection is the sequence you are working with, and { predicate } is a closure that takes an element of the sequence and returns a Bool indicating whether the element should be counted.

Examples Using Different Types of Sequences

1. Array

An array is an ordered collection that can contain duplicates and allows random access.

Example: Count Odd Numbers in an Array

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let oddCount = numbers.count { $0 % 2 != 0 }

print("There are \(oddCount) odd numbers.")
// Output: There are 5 odd numbers.

Here, we use an array of integers and count how many of them are odd using the predicate { $0 % 2 != 0 }.

2. Set

A set is an unordered collection of unique elements.

Example: Count Strings with More Than Three Characters in a Set

let fruits: Set<String> = ["apple", "kiwi", "banana", "pear", "fig"]
let longFruitCount = fruits.count { $0.count > 3 }

print("There are \(longFruitCount) fruits with more than three characters.")
// Output: There are 4 fruits with more than three characters.

This example uses a set of strings and counts how many strings have more than three characters.

3. Dictionary

A dictionary is a collection of key-value pairs where each key is unique.

Example: Count Dictionary Values That Are True

let numberAvailability: [String: Bool] = [
    "One": true,
    "Two": false,
    "Three": true,
    "Four": false,
    "Five": true
]

let availableNumbersCount = numberAvailability.count { $0.value }

print("There are \(availableNumbersCount) available numbers.")
// Output: There are 3 available numbers.

In this case, we have a dictionary of number spot and their availability (as a Bool). The predicate { $0.value } checks if the number is available.

4. Range

A range is a sequence of numbers, often used to generate numbers in a specific interval.

Example: Count Numbers Greater Than 50 in a Range

let numberRange = 1...100
let greaterThanFiftyCount = numberRange.count { $0 > 50 }

print("There are \(greaterThanFiftyCount) numbers greater than 50.")
// Output: There are 50 numbers greater than 50.

Here, we use a closed range from 1 to 100 and count how many numbers are greater than 50.

5. String

A string in Swift is a collection of characters, and it conforms to Sequence.

Example: Count Vowels in a String

let text = "Hello, World!"
let vowels = "aeiouAEIOU"
let vowelCount = text.count { vowels.contains($0) }

print("There are \(vowelCount) vowels in the text.")
// Output: There are 3 vowels in the text.

In this example, we count the number of vowels in a string using a predicate that checks if each character is a vowel.

Conclusion

The count(where:) method in Swift is a built-in utility that provides a concise, readable, and efficient way to count elements in a collection that meet a specific condition. It can be used with any type that conforms to the Sequence protocol, such as arrays, sets, dictionaries, ranges, and strings. While it is powerful and expressive, it’s essential to consider performance and suitability when using it, especially in cases involving large collections or complex predicates.

By understanding these limitations and using count(where:) appropriately, you can write cleaner and more efficient Swift code that leverages the capabilities of the Swift standard library.

Comments