Swift - Passing a function into a function parameters and Closures

·

2 min read

How do we pass in a function into another function?

Let say there is a calculator function, which will perform addition function. For example, let have a calculator function that take in 2 Int param, and output an Int.

func calculator(num1:Int, num2:Int)->Int
{
    return num1+num2
}

var result = calculator(num1:2,num2:3)

print(result) //will return 5

Now, we can also write in this way, by passing an add function into the calculator function, and let the calculator function call the input function to do the processing instead.

This way, we can pass in an add function, or multiply function into the calculator function, and it will call the respective function to do the operations.

//pass in a function into the param.
//calculator function will call the input function
func calculator(num1:Int, num2:Int, operation:(Int,Int)->Int)->Int
{
    return operation(num1,num2)
}

func add(num1:Int,num2:Int)->Int{
  return num1+num2
}

func multiply(num1:Int,num2:Int)->Int{
  return num1*num2
}

var add_result = calculator(num1:2,num2:3,operation:add)
var multiply_result = calculator(num1:2,num2:3,operation:multiply)

print(add_result) //will return 5
print(multiply_result) //will return 6

We can also simplify the code further, by converting the input function into closures.

func calculator(num1:Int,num2:Int,operation:(Int,Int)->Int)->Int
{
    return operation(num1,num2)
}


//1. converting input function into closure
var add_result1 = calculator(num1:2,num2:3,operation:{(num1:Int,num2:Int)->Int in
  return num1+num2
})


//2. can simplify it further by removing the return keyword, as we are in the closures and swift will help us to infer the return type for us
var add_result2 = calculator(num1:2,num2:3,operation:{(num1,num2) in num1+num2})

//3. can simplify it further again by changing into anonymous parameter name
//In swift $0 refer to 1st parameter, $1 refer to the 2nd
var add_result3 = calculator(num1:2,num2:3,operation:{$0+$1})


//4. if the last parameter is a closure, we can remove the function name. This is called a trailing closure
var add_result4 = calculator(num1:2,num2:3) {$0+$1}

In conclusion, we can re-write the calculator function call in the following format below. Notice that by using closures, we have reduced the amount of code needed to be written in just one line. Then again, we have to strike a balance between readability and simplicity :)

func calculator(num1:Int,num2:Int,operation:(Int,Int)->Int)->Int
{
    return operation(num1,num2)
}

var add_result = calculator(num1:2,num2:3) {$0+$1}
var multiply_result = calculator(num1:2,num2:3) {$0*$1}
var subtract_result = calculator(num1:2,num2:3) {$0-$1}

Happy coding!

Swift documentation on clousures: docs.swift.org/swift-book/LanguageGuide/Clo..