Ch 22 Bronze Challenge - how do you declare a closure as an argument?

I modeled the syntax of this declaration after Collection’s prefix(while:) method but it won’t take:

extension Collection where Element == Exercise {
    func count(where stuff: (Self.Element) throws -> Bool) rethrows -> Int {
        var count = 0
        if Self.Element == true { // error: Cannot convert value of type 'Exercise.Protocol' to expected argument type 'Bool'
            count += 1
        }
        return count
    }
}

I don’t know how to declare a closure as an argument. I recall building a custom version of map() back in Ch21, but it’s not like for like here.

You don’t need Self or throws/rethrows in the function definition:

func count(where condition: (Element) -> Bool) -> Int {

Also, you’re not using the closure anywhere inside the function.

I was under the impression I wasn’t supposed to use filter(:_), but…

extension Collection where Element == Exercise {
    func count(where condition: (Element) -> Bool) -> Int {
        let results = self.filter(condition)
        return results.count
    }
}

// bronze challenge output:

let workouts: [Exercise] = [ellipticalWorkout, runningWorkout, tenKRun]
let hardWorkoutCount = workouts.count(where: { $0.caloriesBurned >= 500}) // Playground just gave me '(4 times)' for this line, not '1'
print(hardWorkoutCount) // this is the only way I got '1' 

I had to print the result as well; I’ve had that problem with the playgrounds before where sometimes it won’t automatically print the result of something but instead prints the number of times it executes a loop.

I didn’t see anything in the exercise that pointed away from using filter, so I think it’s fine. It didn’t occur to me to use it, so I did it a different way.

Summary
// Bronze challenge
extension Collection where Element == Exercise {
    func count(where condition: (Element) -> Bool) -> Int {
        var total = 0
        for item in self where (condition(item)) {
            total += 1
        }
        return total
    }
}