Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Function Types in Swift
Written by Team Kodeco

In Swift, functions are first-class citizens, which means that they can be stored in variables, passed as arguments and returned as results. This is possible because functions have a type, just like variables and constants. The type of a function is defined by the number and types of its parameters and return type.

Consider the following function definition:

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

Ths function has a function type of (Int, Int) -> Int.

You can assign a function to a variable of the same type and call it later.

var mathFunction: (Int, Int) -> Int = addTwoNumbers
print(mathFunction(3,4)) // 7

You can also pass a function as an argument to another function:

func performMathOperation(a: Int, b: Int, operation: (Int, Int) -> Int) {
  print(operation(a, b))
}
performMathOperation(a: 3, b: 4, operation: addTwoNumbers) // 7

You can also return a function as a result of another function:

func chooseMathOperation() -> (Int, Int) -> Int {
  return addTwoNumbers
}
let chosenOperation = chooseMathOperation()
print(chosenOperation(3,4)) // 7
© 2024 Kodeco Inc.