Count the number of objects that pass a test in Swift using count(where:)
Swift continues to evolve, introducing new features that enhance both performance and code readability. One such addition is the count(where:) method, introduced in SE-0220. This method allows us to count elements in a sequence that satisfy a given condition, providing a more efficient and expressive way to achieve what previously required a combination of filter()
and count
.
The count(where:)
method combines filtering a sequence and counting elements in a single step. It eliminates the need to create an intermediate array that would be discarded, enhancing performance and resulting in cleaner, more concise code.
Here's a simple example. Suppose we have an array of temperatures in Celsius and we want to count how many of them are above freezing (0°C):
let temperatures = [-5, 10, -2, 20, 25, -1]
let aboveFreezingCount = temperatures.count { $0 > 0 }
// Prints `3`
print(aboveFreezingCount)
In this case, aboveFreezingCount
will be 3
since there are three temperatures (10
, 20
, and 25
) that meet the condition.
# Counting elements with a specific prefix
Consider we have a list of products and we want to count how many of them start with "Apple":
let products = [
"Apple", "Banana", "Apple Pie",
"Cherry", "Apple Juice", "Blueberry"
]
let appleCount = products.count { $0.hasPrefix("Apple") }
// Prints `3`
print(appleCount)
Here, appleCount
will be 3 because "Apple", "Apple Pie", and "Apple Juice" all start with "Apple".
# Counting elements based on length
Another common use case is counting elements based on their length. For instance, we might want to find out how many names in an array are shorter than six characters:
let names = ["Natalia", "Liam", "Emma", "Olivia", "Noah", "Ava"]
let shortNameCount = names.count { $0.count < 6 }
// Prints `4`
print(shortNameCount)
In this example, shortNameCount
will be 4, as "Liam", "Emma", "Noah" and "Ava" are all shorter than six characters.
# Counting specific elements
If we need to count how many times a specific element appears in a sequence, we can use the equality operator (==
) within the closure. For example:
let animals = ["cat", "dog", "cat", "bird", "cat", "dog"]
let catCount = animals.count { $0 == "cat" }
// Prints `3`
print(catCount)
Here, catCount
will be 3 because "cat" appears three times in the array.
The count(where:)
method is available to all types that conform to the Sequence
protocol. This means we can use it not only with arrays but also with sets, dictionaries, and other sequence types. The sequence must be finite, ensuring that the method can complete in a reasonable amount of time.
The count(where:)
method was introduced in Swift 6, which means you'll need Xcode 16 to use this feature. It's supported across various platforms and OS versions, including iOS 8.0+, macOS 10.10+, visionOS 1.0+ etc.
If you're an experienced Swift developer looking to learn advanced techniques, check out my latest book Swift Gems. It’s packed with tips and tricks focused solely on the Swift language and Swift Standard Library. From optimizing collections and handling strings to mastering asynchronous programming and debugging, "Swift Gems" provides practical advice that will elevate your Swift development skills to the next level. Grab your copy and let's explore these advanced techniques together.