Chapter 22, Bronze Challenge Solution

Here’s my solution for the bronze Challenge.

extension Collection where Element == Exercise {
    func count(where test: (Element) -> Bool) -> Int {
        var count: Int = 0
        for exercise in self where test(exercise){
            count += 1
        }
        return count
    }
}

But does anyone know why Collection is the better protocol to add this extension to than Sequence?

Collection is a better choice because Sequence, by definition, is used to represent ordered collections. For example, an Array instance is a sequence but a Set instance is a collection.

Gotcha. Thanks for clearing that up for me!

The other reason for not extending Sequence is this little gem from the Sequence documentation:

Repeated Access

The Sequence protocol makes no requirement on conforming types regarding whether they will be destructively consumed by iteration.

There’s not much point in having a count function in Sequence if it might eat the sequence in the process of counting it.

Collections, on the other hand, do promise that you can non-destructively iterate over the collection. So counting a collection is actually a safe thing to do.