Functions as variables

This may come as a surprise, but functions in Swift are simply another data type. You can assign them to variables and constants just as you can any other type of value, such as an Int or a String.

To see how this works, consider the following function:

func add( a: Int, b: Int) -> Int { return a + b

}

This function takes two parameters and returns the sum of their values. You can assign this function to a variable, like so:

var function = add

Here, the name of the variable is function and its type is inferred as (Int, Int) -> Int from the add function you assign to it.

Notice how the function type (Int, Int) -> Int is written in the same way you write the parameter list and return type in a function declaration. Here, the function variable is of a function type that takes two Int parameters and returns an Int.

Now you can use the function variable in just the same way you’d use add, like so:

function(4, 2)

This returns 6.

Now consider the following code:

func subtract( a: Int, b: Int) -> Int { return a - b

}

Here, you declare another function that takes two Int parameters and returns an Int. You can set the function variable from before to your new subtract function, because the parameter list and return type of subtract are compatible with the type of the function variable.

function = subtract function(4, 2)

This time, the call to function returns 2.

The fact that you can assign functions to variables comes in handy because it means you can pass functions to other functions. Here’s an example of this in action:

func printResult( function: (Int, Int) -> Int, a: Int, _ b: Int) { let result = function(a, b)

print(result)

}

printResult(add, 4, 2)

printResult takes three parameters:

  1. function is of a function type that takes two Int parameters and returns an Int, declared like so: (Int, Int) -> Int.
  2. a is of type Int.
  3. b is of type Int.

printResult calls the passed-in function, passing into it the two Int parameters. Then it prints the result to the console:

6

It’s extremely useful to be able to pass functions to other functions, and it can help you write reusable code. Not only can you pass data around to manipulate, but passing functions as parameters lets you be flexible about what code gets executed too.

results matching ""

    No results matching ""