Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 146 ยท Functions and Closures

Closures

Master Swift closures - closure expression syntax, type inference, shorthand argument names, trailing closures, capturing variables, reference semantics and when a closure may escape.

A closure is a piece of code you can pass around like a value, without giving it a name. If you have used lambdas in Python, arrow functions in JavaScript or anonymous functions in Kotlin, you already know the idea. Swift closures are the same thing with two Swift-flavored superpowers: very compact syntax when the types are obvious, and precise rules for capturing the variables around them.

The previous lesson showed that functions are values. Closures are the way you usually write such values: inline, exactly where you need them. They power sorting, map and filter, callbacks, asynchronous code and SwiftUI. This lesson covers the syntax from the long form to the shortest, trailing closures, capturing, and the difference between escaping and non-escaping closures.

A closure is a function without a name

A closure expression is written in braces: parameters and return type, then the keyword in, then the body.

TEXT
{ (parameters) -> ReturnType in
    statements
}

Here are the same operation written as a named function and as a closure stored in a constant:

Swift Function and closure side by side

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.

You call a closure by writing the constant's name and arguments. Notice what is missing: closures have no argument labels. You call addClosure(2, 3), not addClosure(a: 2, b: 3). When a closure has no parameters, you can omit the in and the parentheses, as with noInput.

Making closures shorter

The long form is rarely needed, because Swift infers types from the context. Take a classic example, sorting an array with sorted(by:), which expects a function of type (String, String) -> Bool. Watch the closure shrink step by step.

Swift From long to short

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.

Every step removes something the compiler can work out:

  1. Types of parameters and result. sorted(by:) declares its parameter type, so you do not repeat it.
  2. return. A closure with a single expression returns its value implicitly, just like a function.
  3. Parameter names. $0, $1, ... are shorthand names for the first, second, ... argument. Use them only when the closure is short and obvious.
  4. Trailing closure. When the closure is the last argument, it can be written after the parentheses, and the parentheses can vanish if it is the only argument.
  5. Operators. > already is a function (Int, Int) -> Bool.

Which form should you use? The one that reads best. A one-line comparison with $0 and $1 is idiomatic. A multi-line closure deserves named parameters, because $0.name == $1.name && $0.age > $1.age makes readers decode the numbers.

Trailing closures in depth

The trailing-closure form is more than a convenience: it lets you write your own functions that look like language features. If a function takes a closure last, callers can pass a block of code.

Swift Trailing closures

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.

Since Swift 5.3 a function with several closure parameters can use multiple trailing closures: the first has no label, the following ones keep their labels (onFailure:). Notice that you drop the label of the first trailing closure (onSuccess) but write the others.

In an if, guard or while condition a trailing closure is confusable with the statement's own braces (the compiler warns: trailing closure in this context is confusable with the body of the statement), so pass the closure inside parentheses there.

Capturing values

Here is the feature that makes a closure a closure: it can capture constants and variables from the scope where it is written and keep using them after that scope has ended.

Swift Capturing a variable

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.

makeCounter returns a closure that uses total and step. After makeCounter returns, those would normally be destroyed. The closure keeps them alive on the heap instead. Each call to makeCounter creates a fresh, independent total, which is why byOne and byTen count separately.

The last lines reveal a crucial detail: closures capture variables by reference, not by copying their values at the time the closure is created. The closure show printed "after", because it looks at the variable message, not at the string it contained when the closure was written. Changes made by the closure are visible outside, and changes made outside are visible inside.

That is often what you want, and sometimes a surprise. If you need to freeze a value at creation time, use a capture list in square brackets before the parameters:

Swift Capture lists freeze a value

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.

[level] copies the value into the closure when it is created, so frozen always prints 1. A capture list is also how you break reference cycles with [weak self] and [unowned self], which become important once classes are involved: see Escaping Closures and Autoclosures and Memory Management with ARC.

Closures are reference types

If you assign a closure to another variable, both refer to the same closure and share its captured state:

Swift Closures share their state

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.

alias and first are the same counter, so the third call prints 3. second came from another call of makeCounter and starts over. This is different from structs, which are copied. The rule to remember: a closure value is a reference to code plus its captured environment.

Escaping and non-escaping closures

A closure passed as a function argument is non-escaping by default: it may be called while the function runs but not stored or called later. That restriction lets the compiler optimize and skip some bookkeeping. If the function stores the closure (in a property or a global), calls it after returning, or passes it to something that might, mark the parameter @escaping.

Swift @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.

Escaping is a statement about lifetime. A non-escaping closure ends before the function returns, so it can freely use local variables and, in classes, self without writing it. Escaping closures outlive the call and must capture things safely. That has consequences for classes and reference cycles, which the next lesson, Escaping Closures and Autoclosures, takes on. (The global array is nonisolated(unsafe) only because a mutable global is a data-race risk in Swift 6. See Sendable and Data Races.)

When inference fails

Closure shorthand is only as good as the compiler's ability to infer. If the context does not provide a type, the compiler asks for help:

Swift No context to infer from (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.

Nothing says what $0 is, so the compiler reports main.swift:1:12: error: cannot infer type of closure parameter '$0' without a type annotation. Fix it by giving the type of the constant, let pass: (Int) -> Int = { $0 }, or by writing the parameter: { (n: Int) in n }. (A closure like { $0 * 2 } happens to compile, because the literal 2 makes Swift default the parameter to Int; then twice(2.5) is an error. Do not rely on that, annotate instead.)

Another common case is a multi-statement closure whose return type cannot be deduced. Swift can infer the types of multi-statement closures in recent versions, but when it cannot, add an explicit signature: { (a: Int, b: Int) -> Int in ... }. A signature also speeds up compilation of complicated expressions.

Practical patterns

A few closure idioms you will meet everywhere:

Swift Everyday closure patterns

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 first pattern, let x: T = { ... }(), runs a block once to initialize a constant that needs several statements. The retry helper hides the loop and leaves the what to the caller. The multi-key sort uses named parameters, because $0.age and $1.name mixed would be hard to read. The last function shows deferred work: the default-producing closure is only run when needed (a first taste of @autoclosure, coming up next).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does names.sorted { $0.count < $1.count } use?

    The closure is written after the call, so it is a trailing closure, and $0 and $1 are shorthand names for its first and second argument.
  2. 2. What does the capture list in { [level] in print(level) } do?

    A capture list captures the value at creation time. Without it, the closure refers to the variable itself and sees later changes.
  3. 3. Two variables hold the same counter closure (let alias = first). What happens when you call each once?

    Closures are reference types. Assigning a closure copies the reference, not the captured variables.
  4. 4. Which argument label does a closure have when you call it, as in let add = { (a: Int, b: Int) in a + b }?

    Closure parameters never have argument labels; they only have names used inside the body.
  5. 5. When must a function parameter of closure type be marked @escaping?

    Non-escaping is the default. @escaping is required when the closure outlives the call, such as when it is stored or run later.

Summary

  • A closure is an unnamed function written in braces: { (params) -> Result in body }; it has no argument labels.
  • Swift infers parameter and return types from context; single-expression closures return implicitly, and $0, $1 are shorthand names.
  • A closure that is the last argument can be written as a trailing closure; several trailing closures keep the labels after the first.
  • Closures capture surrounding variables by reference and keep them alive; a capture list such as [level] copies the value instead.
  • Closures are reference types: copies of a closure value share the same captured state.
  • Closure parameters are non-escaping by default; use @escaping when the closure outlives the call.
  • When there is no context, add a type annotation or an explicit signature.

Next: Escaping Closures and Autoclosures