Swift - Function as Variables

Introduction

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:

Demo

var numbersFunc: (Int, Int) -> Int 

func addNumbers(firstValue: Int, secondValue: Int) -> Int { 
    return firstValue + secondValue 
} 
numbersFunc = addNumbers // ww  w. ja va 2  s . c o  m
var a = numbersFunc(2, 3)  // Using the  'addNumbers' function
print(a)

Result

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

Related Topics