Passing function within function parameter swift
This is one of the powerful feature of swift. That’s called “function type” that means function itself is a type and you can pass this function to another function. For example (Int,Int) -> Int that means you can pass any such function which takes two integer parameters and returns an integer.
Below is a great example done by me, would be easy to understand the concept.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
func addTwoNum(a:Int,b:Int) -> Int { return a+b } func mulTwoNum(a:Int,b:Int) -> Int { return a*b } func testFunc(adderFunc:(Int,Int)->Int,c:Int,d:Int) -> Int { let answer = adderFunc(c,d) return answer } let answer1 = testFunc(addTwoNum, c: 4, d: 5) // answer1 = 9 let answer2 = testFunc(mulTwoNum, c: 4, d: 5) // answer2 = 20 |
So, in above program we have to similar type of functions. addTwoNum and mulTwoNum. Another function is testFunc – that takes two integers and a function as a parameter. Wonderful is that we passed first addTwoNum as parameter and then mulTwoNum and we got both results accordingly.