I have this Swift function which I created which takes a function as a param:
func doMath(_ f:(_ i1 : Int, _ i2 : Int) ->
(), _ i1: Int, _ i2: Int) {
print("doing Math")
f(i1, i2)
}
The function takes two params (both of Int) and returns nothing.
I can successfully call that method with the following code, using a non-anonymous function.
func add(_ m1:Int, _ m2: Int){
print (m1 + m2)
}
doMath(add, 3,5)
When doMath is called, it prints:
doing Math
and then calls the add function, which then prints:
8
What syntax allows calling the doMath
function with an anonymous function?
What I've Tried
doMath(5,8, {
(m1:Int, m2:Int) -> () in
print(m1 * m2)
})
I get an error that states:
func doMath
– as you defined it – takes a closure as the first argument,
and two integers as second and third argument. Therefore you call it as
doMath({
(m1:Int, m2:Int) -> () in
print(m1 * m2)
}, 5, 8)
or with shorthand parameters:
doMath({ print($0 * $1) }, 5, 8)
If you change the function definition to take the closure as the last parameter
func doMath(_ i1: Int, _ i2: Int, _ f:(_ i1 : Int, _ i2 : Int) -> ()) {
print("doing Math")
f(i1, i2)
}
then you would call it as
doMath(5, 8, { print($0 * $1) })
or, using the “trailing closure” syntax:
doMath(5, 8) { print($0 * $1) }
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