Swift – Assign Function to a Variable

To assign function to a variable in Swift, declare a variable that takes specific set/type of parameters and return a specific type of value. Then we can assign a function that has same type of parameters and return value to this variable.

The syntax to declare a variable with specific parameters and return type is

var variableName: (ParameterType, ParameterType) -> ReturnType;

Example

In the following program, we will declare a variable addFunction that takes two integers as parameters and returns an integer value. We will define a function add(), that takes two integers as parameters and return the sum of the given values.

Now, we can assign the function add() to the variable addFunction.

main.swift

func add(a: Int, b: Int) -> Int {
    return a + b
}
//declare variable
var addFunction: (Int, Int) -> Int
//assign function to variable
addFunction = add
//call function using variable
let result = addFunction(5, 4)
print("Result is \(result)")

Output

Swift - Assign Function to a Variable - Example

Conclusion

In this Swift Tutorial, we learned how to assign a function to a variable in Swift.