I know that in the first line, we can use lessThanTen(number: Int) to replace (int), and contidion means a label, but in the third line: * why dont we use if condition : (item) to replace if condition(item), since condition is a label.

Condition is the method that you're receiving on that method, if you look at that method signature:
condition: (int) -> Bool
which means that you're receiving a condition that can be called using an argument of Int type and will return a bool. Anywhere, inside:
hasAnyMatches
you'll be able to use
condition(anyInt)
Now if you look at the method caller:
hasAnyMatches(list: numbers, condition: lessThanTen)
so, you're saying that the 'condition' on 'hasAnyMatches' will be 'lessThanTen'. Which means that in your
if condition(item)
What really is happening is:
if lessThanTen(item)
I hope it made it clearer!
condition is a Bool-returning closure supplied to hasAnyMatches that needs to be called to yield a boolean value. The closure takes a single argument of type Int, which is the same type as the elements of list. Hence, we call the supplied (Int) -> Bool closure on each item, and in case condition applied to an item returns true, we cut the traversal over the list items short and return true from the function.
Using functional programming tecniques, we could make use of a reduce operation on list to compress the implementation of hasAnyMatches:
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
return list.reduce(false) { $0 || condition($1) }
}
Or, even better (allowing exit return as in the original loop), as described by @Hamish in the comments belows (thanks!), using contains
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
return list.contains(where: condition)
}
Example usage:
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
print(hasAnyMatches(list: numbers, condition: lessThanTen)) // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With