Reputation: 15
func sortFunc (array: [Int], closure: (Int?, Int) -> Bool) -> Int {
var tempVar: Int? = nil
for value in array {
if closure (tempVar, value) {
tempVar = value
}
}
return tempVar!
}
In this code I can't understand this:
if closure (tempVar, value) {
tempVar = value
}
Can you explain what closure(tempVar, value) means? I tried to find info in documentation, but there is nothing, that can help me.
Upvotes: 1
Views: 64
Reputation: 2160
Let's break this down. Looking at the method signature, you can see the definition of closure
:
func sortFunc (array: [Int], closure: (Int?, Int) -> Bool) -> Int
What this means is that there is a parameter named closure
for the function sortFunc
which must have two arguments, an Int?
and Int
, that returns a Bool
ean value.
So what does that even mean?
That means we are passing a function to sortFunc
as a parameter. An example of this would be something like this:
func myFunction(_ temporaryValue: Int?, value: Int) {
// return a boolean value
return temporaryValue != nil
}
When you call if closure(tempVar, value)
it evaluates the function passed provided with the arguments of tempVar
and value
and returns a boolean (true/false) based on the results of that function.
Upvotes: 1
Reputation: 19884
closure
is a block of code that takes two parameters, one Int?
and one Int
, and returns a Bool
.
It can be called like a function and will return a value.
When you do this if closure(tempVar, value)
, you are calling that block of code with those two parameters, so it will return a boolean value.
Upvotes: 1