Swift - Defining a Function Type Variable

Introduction

In Swift, you can define a variable or constant as a function type.

For example, you could do the following:

var myFunction: (Int, Int) -> Int

Here, it basically defines a variable called myFunction of type "a function that takes in two Int parameters and returns an Int value."

Because myFunc has the same function type as the sum() function discussed earlier, you can then assign the sum() function to it:

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

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

myFunction = sum

You can shorten the preceding statements to:

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

Related Topic