Reputation: 1678
I suspect I am missing something really obviously wrong here, so forgive me if I am being a bit thick.
All the examples I see for closures are for passing a closure to the array map function. I want to write my own function which takes a closure
This is what I am attempting
func closureExample(numberToMultiply : Int, myClosure : (multiply : Int) -> Int) -> Int
{
// This gets a compiler error because it says myClosure is not an Int
// I was expecting this to do was to invoke myClosure and return an Int which
// would get multiplied by the numberToMultiply variable and then returned
return numberToMultiply * myClosure
}
I am completely stumped on what I am doing wrong
Please help!!
Upvotes: 1
Views: 798
Reputation: 186984
Same way you call any function, with ()
.
return numberToMultiply * myClosure(multiply: anInteger)
A working example:
func closureExample(numberToMultiply : Int, myClosure : (multiply : Int) -> Int) -> Int {
return numberToMultiply * myClosure(multiply: 2)
}
closureExample(10, { num in
return 2*num
}) // 40
Upvotes: 2
Reputation: 93276
You treat a closure parameter just like a function named with the parameter's name. myClosure
is the closure that needs to operate on numberToMultiply
, so you want:
return myClosure(numberToMultiply)
That will pass numberToMultiply to your closure, and return the return value.
Upvotes: 1