Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an inline anonymous function, for immediate use in a function call?

Tags:

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

  • I'm reading the book, iOS 12 Programming Fundamentals with Swift by Matt Neuberg but he skips explaining anonymous methods with params.
  • I've googled and SOed but can't find a swift example that I can figure out.
  • I've tried many variations and the following is my closest but I get the error shown below:

doMath(5,8, { 
   (m1:Int, m2:Int) -> ()  in  
   print(m1 * m2) 
 })

I get an error that states:

error msg

like image 435
raddevus Avatar asked Nov 20 '18 19:11

raddevus


1 Answers

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) }
like image 109
Martin R Avatar answered Oct 13 '22 23:10

Martin R