Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does 'condition' mean here in swift tutorial ----function?

Tags:

swift

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. enter image description here

like image 420
jack Avatar asked Jul 14 '26 07:07

jack


2 Answers

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!

like image 73
Flavio Silverio Avatar answered Jul 18 '26 01:07

Flavio Silverio


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
like image 38
dfrib Avatar answered Jul 17 '26 23:07

dfrib