Swift - Calling a Function Type Variable

Introduction

You can call the sum() function using the function type variable myFunction , like this:

Demo

func sum(num1: Int, num2: Int) -> Int {
   return num1 + num2
}
func diff(num1: Int, num2: Int) -> Int {
   return abs (num1 - num2)
}

var myFunction: (Int, Int) -> Int = sum

print(myFunction(3,4) )  //prints out 7

Result

The myFunction variable can be assigned another function that has the (Int, Int) -> Int function type:

myFunction = diff

This time, if you call the myFunction again, you will instead be calling the diff() function:

print(myFunction(3,4))  //prints out 1

The following table shows the definition of some functions and their corresponding function types.

FUNCTION DEFINITION                                                FUNCTION TYPE (DESCRIPTION)

func average(nums: Int...)                                         (Int...) -> Float
  -> Float {                                                       The parameter is a variadic parameter;
}                                                                  hence, you need to specify the three
                                                                   periods ( ... ).

func joinName(firstName:String,                                    (String, String, String) -> String
              lastName:String,                                     You need to specify the type for the
              joiner:String = " ")     -> String {                 default parameter (third parameter).
}

func myFunction(num1: Int,                                         (Int, Int) ->  ()
                 num2: Int) {                                      The function does not return a value;
}                                                                  hence, you need the () in the function
                                                                   type.

func myFunction() {                                                () ->  ()
}                                                                  The function does not have any
                                                                   parameter and does not return a value;
                                                                   hence, you need to specify the () for
                                                                   both parameter and return type.

Related Topic