Swift - Function as Variables


You can store functions in variables.

First, declare a variable that can store a function with certain parameters and returning value.

Then assign any function with those types of parameters and returning the same type of value to the variable:


var numbersFunc: (Int, Int) -> Int 

func addNumbers(firstValue: Int, secondValue: Int) -> Int { 
    return firstValue + secondValue 
numbersFunc = addNumbers //from www .  j ava2s . co m
var a = numbersFunc(2, 3)  // Using the  'addNumbers' function


Here, numbersFunc can store any function that takes two Ints and returns an Int.

Related Topics