🎓 A1Learner
🔍
0 of 36 lessons completed

Swift Function Types

A function type describes the parameter types and the return type of a function. A function can travel through a program wherever a value of its type can go.

A function stored in a variable

The add function matches the written type, so operation can hold it. The call through operation passes two numbers with no labels.

func add(a: Int, b: Int) -> Int {
    a + b
}
let operation: (Int, Int) -> Int = add
print(operation(4, 5))

A function passed as an argument

The compute function receives a function and applies it to x and y. The underscore before its first parameter lets each call pass a function with no label.

func add(a: Int, b: Int) -> Int {
    a + b
}
func multiply(a: Int, b: Int) -> Int {
    a * b
}
func compute(_ operation: (Int, Int) -> Int, x: Int, y: Int) -> Int {
    operation(x, y)
}
print(compute(add, x: 2, y: 3))
print(compute(multiply, x: 2, y: 3))

A function returned from a function

The choose function hands back multiply for a true argument and add for a false one. Each returned function is stored and then called.

func add(a: Int, b: Int) -> Int {
    a + b
}
func multiply(a: Int, b: Int) -> Int {
    a * b
}
func choose(multiplyWanted: Bool) -> (Int, Int) -> Int {
    if multiplyWanted {
        return multiply
    }
    return add
}
let chosen = choose(multiplyWanted: true)
print(chosen(3, 4))
let other = choose(multiplyWanted: false)
print(other(3, 4))

Example

func double(n: Int) -> Int {
    n * 2
}
func triple(n: Int) -> Int {
    n * 3
}
var transform: (Int) -> Int = double
print(transform(5))
transform = triple
print(transform(5))

Key points

  • A function type writes the parameter types in parentheses, then an arrow, then the return type.
  • A function whose shape matches a type can be stored in a variable of that type.
  • A call through a function variable writes no argument labels.
  • A function can take another function as one of its parameters.
  • A function can return another function as its result.
  • The returned function can be stored and called like any other function value.

In this example, the transform variable starts out holding the double function, so the first call prints 10. The variable then takes the triple function, and the same call shape prints 15.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which type fits a function that takes two Int values and returns an Int value?