Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 146 ยท Functions and Closures

Function Types

Learn that Swift functions are values with types - store them in variables, pass them as arguments, return them from other functions, and write your first higher-order functions.

In Swift, a function is not just a block of code with a name: it is also a value. Every function has a type that describes its parameters and result, and you can store a function in a variable, put it in an array, pass it to another function and return it from one. This idea, first-class functions, is the foundation for map, filter, sorting with a custom order, callbacks and much of modern Swift.

This lesson shows how to read and write function types and how to use them. It builds on Functions and Argument Labels, and it prepares the ground for Closures.

The type of a function

Look at this function:

Swift
func add(_ a: Int, _ b: Int) -> Int { a + b }

Its type is (Int, Int) -> Int: "takes two Ints, returns an Int". The type lists the parameter types in parentheses, then an arrow, then the return type. A function with no parameters and no result has the type () -> Void. Parameter names and argument labels are not part of the type, only the types are.

Swift Reading function types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

type(of:) shows the types as Swift sees them. Top-level functions in Swift 6 mode also carry the attribute @Sendable (they capture nothing, so they are safe to use from any thread); you can ignore it for now, Sendable and Data Races explains it. Note that length(of:) has the type (String) -> Int with no trace of its label. The variable operation holds the function add, and you call it like any function. When you assign multiply to current, Swift infers the type (Int, Int) -> Int, and a later assignment of add is fine, because the types match. When you use a function as a value, you write its name without parentheses; the parentheses would call it.

Note the call operation(3, 4): the labels from the original declaration are not required here, because the type has none.

Functions as parameters

Because a function type is a type like any other, it can appear in a parameter list. A function that takes another function as an argument is called a higher-order function. It lets the caller supply behavior, not just data.

Swift Passing a function as an argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

apply knows nothing about addition or powers: it only knows it has something of type (Int, Int) -> Int. Passing max works too, because the standard library's max can be used as an (Int, Int) -> Int, and Swift picks the matching overload. repeatAction takes a () -> Void function. The caller decides what to repeat. This separation of "what to do" from "when and how often" is the heart of higher-order programming.

Functions as return values

A function can also return a function. The return type is then a function type, and you can read the arrows from left to right: (Int) -> (Int) -> Int is "takes an Int and returns a function that takes an Int and returns an Int". (Arrows associate to the right.)

Swift Returning functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

makeMultiplier builds a new function each time it is called. The returned function remembers factor, even though makeMultiplier has already finished. Capturing values like this is what makes such a function a closure, and the details (when factor is stored, how long it lives) are the topic of Closures. The second example selects one of two functions with a switch. A call like makeMultiplier(by: 5)(4) calls the returned function immediately.

Collections of functions

Since functions are values, they can live in arrays and dictionaries. A table of functions often replaces a long switch.

Swift A dictionary of operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The curly-brace values are closure expressions, a shorthand for writing a function without a name, introduced in the next lesson. For now treat { $0 + $1 } as "a function that adds its two arguments". The dictionary (kept local to calculate) maps operator symbols to behavior, and the pipeline is an ordered list of steps applied one after another: 4, then 5, then 50, then 47.

Optional and escaping function parameters

A function parameter can be optional, which makes it a callback that the caller may omit. The type needs parentheses around the function type so the question mark applies to the whole thing. Function parameters are non-escaping by default: the function may call them while it runs, but must not keep them for later. If a function stores or returns its parameter, mark it @escaping, which the next lessons explain (Closures and Escaping Closures and Autoclosures).

Swift Optional callbacks and the escaping error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler rejects this with main.swift:4:18: error: converting non-escaping parameter 'action' to generic parameter 'Element' may allow it to escape. Adding @escaping to the parameter type fixes it, and it tells every caller that the function may run later.

Swift Optional callback and @escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The optional callback is called with onFinish?(), optional chaining that does nothing when the value is nil. The global array is marked nonisolated(unsafe) because Swift 6 treats a mutable global as a possible data race; for a single-threaded demo that is acceptable, and Sendable and Data Races explains the rule properly.

Using type aliases to name function types

Long function types are hard to read. A typealias gives them a name.

Swift typealias for function types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Transform is just another name for (Int) -> Int. Generic aliases such as Predicate<T> work too. Generic Functions explains the <T> syntax.

Higher-order functions in the standard library

You do not need to write all your own. The standard library is full of functions that take functions: sorted(by:), map, filter, reduce, first(where:) and many more. They are the subject of map, filter, reduce and Friends.

Swift Passing named functions to the standard library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice how operators are functions too: > has the type (Int, Int) -> Bool and + has (Int, Int) -> Int, so they can be passed in directly, as in reduce(0, +). Initializers can be passed as well: String.init is used as a function from Int to String here.

Pitfalls and guidance

  • Labels disappear in the type. A function value (String) -> Int loses its of: label, so name the variable well.
  • Overloads can be ambiguous. Passing max or String.init as a value works only when the context makes the type clear; otherwise, write the type or a closure.
  • Escaping is a promise. Add @escaping only when the function stores or returns the closure, because callers then must watch for reference cycles (ARC).
  • Prefer a protocol or a struct when a function type grows many parameters or you pass several related callbacks together.
  • Function values cost a little. Calling through a function value is an indirect call. For hot loops, the generic or inlined forms are faster; for normal code, the difference does not matter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of func greet(person name: String, times: Int) -> String?

    A function type lists only the parameter types and the result type. Argument labels and parameter names are not part of it.
  2. 2. What does (Int) -> (Int) -> Int mean?

    The arrow associates to the right, so it is a function taking an Int and returning another function of type (Int) -> Int.
  3. 3. When must a function parameter of function type be marked @escaping?

    Function parameters are non-escaping by default. If the function keeps the closure beyond its own execution, the parameter must be @escaping.
  4. 4. Which call passes the standard + operator as a function?

    Operators are functions, so + can be passed where a function of two Ints returning an Int is expected.
  5. 5. What is a higher-order function?

    Higher-order functions work with other functions: they accept them as arguments, return them, or both.

Summary

  • Every function has a type such as (Int, Int) -> Int; labels and parameter names are not part of it.
  • Functions are values: assign them to variables, store them in collections, pass and return them.
  • A function that takes or returns a function is a higher-order function; it lets the caller supply behavior.
  • Function parameters are non-escaping by default; use @escaping when the function keeps them for later.
  • Use typealias to name long function types, and f?() to call an optional function value.
  • Operators and initializers can be passed as functions: reduce(0, +), map(String.init).

Next: Closures