NiravS
NiravS

Reputation: 1282

A function can take another function as one of its arguments

I wrote the following code in playground and try to learn from Apple doc function & classes.
Here is my code..

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)

How can I directly pass the different condition? can I write like that..

hasAnyMatches(numbers, condition: { $0 < 10 })

Actually this function return true/false, but when I write like that so in play ground behalf of this line o/p: (4 times) So what happen when I'm write like that.

And give me solution to direct pass the condition in hasAnyMatches() func.

Upvotes: 0

Views: 124

Answers (3)

Suhit Patil
Suhit Patil

Reputation: 12023

hasAnyMatches function takes the list of numbers and the condition closure so you can pass any closure which takes a Int and returns bool

let numbers = [20, 19, 7, 12]
let lessThan: (Int) -> Bool = { $0 < 10 }
let match = hasAnyMatches(list: numbers, condition: lessThan)
print(match)

Another way to write the same thing would be to use filters which iterates over a collection and return an Array containing only those elements that match an include condition. main advantage of using filter is its inbuilt and you don't need separate hasAnyMatches function to check the condition

let numbers = [20, 19, 7, 12]
let match = numbers.filter ({ $0 < 10 }).count > 0
print(match)

Upvotes: 1

Sweeper
Sweeper

Reputation: 274480

When you write this:

hasAnyMatches(numbers, condition: { $0 < 10 })

The playground says "(4 times)". This is because the closure { $0 < 10 } is executed four times, one time on each item in numbers.

To get it to show the return value of the hasAnyMatches function, there are a few ways to do this.

  • You can just make {$0 < 10} be on its own line:

    hasAnyMatches(list: numbers, condition: // shows true on this line
        {$0 < 10} // shows (4 times) on this line
    )
    
  • You can store the result into a variable, then get the value of the variable:

    let val = hasAnyMatches(list: numbers, condition: {$0 < 10})
    val // shows true on this line
    

Upvotes: 1

S&#248;ren Mortensen
S&#248;ren Mortensen

Reputation: 1755

The way you wrote it was fine! You're just missing the first argument label in the call. It should be:

hasAnyMatches(list: numbers, condition: { $0 < 10 })

Upvotes: 1

Related Questions