Swift - Returning Function Type in a Function


A function type can be used as the return type of a function.

Consider the following example:

func sum(num1: Int, num2: Int) -> Int {
   return num1 + num2
func diff(num1: Int, num2: Int) -> Int {
   return abs (num1 - num2)
func functionBuilder(choice:Int) -> (Int, Int)->Int {
   if choice == 0 {
      return sum
   } else {
      return diff

The functionBuilder() function takes in an Int parameter and returns a function of type (Int, Int) -> Int.

If choice is 0, then it returns the sum() function; otherwise it returns the diff() function.

To use the functionBuilder() function, call it and pass in a value and assign its return value to a variable or constant:

var functionToUse = functionBuilder (0)

The return value can now be called like a function:

print(functionToUse(2,6))       //prints out 8

functionToUse = functionBuilder (1)
print(functionToUse(2,6))       //prints out 4

Related Topic