Contents Open

DocsLanguage Guide

Closures

Closure syntax, trailing closures, captures and capture lists, escaping and autoclosures.

A closure is a function written as an expression, without a name, that can be passed around and called later. Closures can use the constants and variables of the scope they are written in: they capture them, and keep using them even after that scope has ended.

You have already met two kinds of closure in Functions: top-level functions, which capture nothing, and nested functions, which may capture locals of the function around them. This chapter is about closure expressions, the light syntax for writing a function in place, usually as an argument. Sable's closures are Swift's in most respects, with an arrow form, (x: Int) => x * 2, borrowed from C# for the common short case.

Closure Expressions#

The shortest way to write a closure is a parameter list, =>, and the expression it returns:

Sable
let double = (x: Int) => x * 2let add = (a: Int, b: Int) => a + blet noop = () => { }print(double(21))        // 42print(add(2, 3))         // 5

After the => comes either an expression or a block. A block holds statements, and returns with return like a function body:

Sable
let describe = (n: Int) => {    let parity = n % 2 == 0 ? "even" : "odd"    return "\(n) is \(parity)"}

The result type can be written after the parameters when it should not be inferred:

Sable
let widen = (x: Int) -> I64 => x as I64

There is also a braced form, Swift's, in which the parameters and result type come first inside the braces and in separates them from the body:

Sable
let length = { (s: String) -> Int in    return s.count}

The two forms mean the same thing. The arrow form reads better for a short closure stored in a variable; the braced form is the one used for trailing closures, below.

Inferring Types From Context#

When a closure is passed where a function type is expected, Sable knows its parameter and result types from that function type, so you can leave them out. With one parameter, even the parentheses can go:

Sable
let names = people.map(x => x.name)let adults = people.filter { p in p.age >= 18 }let byScore = players.sorted { a, b in a.score > b.score }

map takes a (Person) -> T, so x is a Person; sorted takes a (Player, Player) -> Bool, so a and b are players. In the braced form the parameter names are written before in without parentheses or types.

A closure with a single expression returns that expression's value; there is no return to write.

Shorthand Argument Names#

In the braced form you can leave out the parameter list altogether and refer to the parameters as $0, $1, $2 and so on:

Sable
let active = items.filter { $0.isActive }let total = prices.reduce(0.0) { $0 + $1 }

The number and types of the parameters come from the function type the closure is passed as, and the highest $n used must fit it.

Trailing Closures#

When a closure is a call's last argument, you can write it after the parentheses instead of inside them. If it is the only argument, the parentheses can go too:

Sable
fn withLock<T>(_ lock: Lock, _ body: () throws -> T) rethrows -> T { }withLock(mutex) {    counter += 1}let evens = numbers.filter { $0 % 2 == 0 }

A trailing closure suits a closure longer than a line, because the call's parentheses close before the body starts.

Which Parameter a Trailing Closure Goes To#

The first trailing closure goes to the next parameter that the arguments in parentheses left unfilled, whether that parameter is labelled or not, passing over any parameter with a default value whose type is not a function. This is Swift's forward scan. So with:

Sable
fn render(_ template: String, with fill: (Substring) -> String) -> String { }fn scaled(_ x: Int, scale: Int = 2, by f: (Int) -> Int) -> Int { }

render("Dear {name}") { key in "Ada" } gives the closure to the labelled fill, and scaled(3) { $0 + 1 } gives it to f, leaving scale at its default. Inside the parentheses, arguments still need their labels as usual.

Multiple Trailing Closures#

A call can take several trailing closures. After the first, each one is written with its parameter's label, starting on the line where the one before it ends:

Sable
fn attempt<T>(_ work: () throws -> T, onFail fallback: () -> T) -> T { }let page = attempt {    try fetch(url)} onFail: {    cachedPage()}

Putting onFail: on the same line as the closing brace is what makes it part of this call rather than a new statement.

Closures and Overloads#

A closure, like an implicit member such as .Fast, has its type decided by the parameter it is passed to, so when overloads are chosen it fits only a parameter of its own shape. With fn pick(_ mode: Mode) and fn pick(_ make: () -> Mode), pick(.Fast) calls the first and pick { .Fast } the second: a function type has no member to name with a dot, and a closure is no enum.

Braces: Record Literal, Trailing Closure or Body#

Three different things open with { in Sable, and the rule that tells them apart is short:

  1. Where a brace would open a statement's body, after an if, guard or while condition, a for sequence or a match subject, it always opens the body. Parentheses and brackets lift that rule, so if isOrigin(Point { x: 0, y: 0 }) { } works as intended.
  2. After a type name (Point {, Geo.Point {), what is inside decides: { } or { name: … is a record literal; anything else is a trailing closure.
  3. Anywhere else, a brace after an expression is a trailing closure: items.filter { $0.isActive }, withLock(m) { … }.

Rule 2 is why a record literal has no field shorthand as JavaScript's objects do: Point { x } could not be told apart from a closure returning x, so a field always carries its value, Point { x: x }. Record literals are covered in Structures and Classes.

Capturing Values#

A closure can use the constants and variables around it. Sable captures a var by reference and a let by value: the closure sees later changes to a captured variable and can make changes of its own, while a captured constant is simply copied in.

Sable
fn makeCounter() -> () -> Int {    var count = 0    return () => {        count += 1        return count    }}let next = makeCounter()print(next())     // 1print(next())     // 2let other = makeCounter()print(other())    // 1: a count of its own

count outlives the call to makeCounter because the closure holds on to it. Each call of makeCounter makes a new count, so each counter is independent.

Capture Lists#

A capture list, in square brackets before the closure, says how particular values are captured. name = expression captures the value of an expression at the moment the closure is made, under a name of the closure's own:

Sable
var limit = 10let check = [max = limit] (n: Int) => n <= maxlimit = 20print(check(15))      // false: 'max' is still 10

A capture list goes before either form of closure: [max = limit] (n: Int) => … or [max = limit] { n in … }.

Weak and Unowned Captures#

A closure that captures a class instance keeps it alive, through reference counting. When the instance also holds the closure, as an object holding its own event handler does, the two keep each other alive for ever. Breaking such cycles is what weak and unowned captures are for. Both capture a class instance without keeping it alive, under a name of the closure's own, self included.

A weak capture is optional. It reads as none once the object has gone, so the body must unwrap it, usually with guard let self:

Sable
class Downloader {    var completed = 0    fn start(_ session: Session) {        session.onFinish([weak self] () => {            guard let self else { return }            self.completed += 1        })    }}

if let s = self and self?.completed work too. Until a weak self is unwrapped, reaching one of its members implicitly, by writing completed rather than self.completed, is an error.

An unowned capture is the object itself, not an optional. Use it when the closure can never outlive the object; reading it once the object has gone traps.

[weak x = expression] captures, weakly, what the expression gives. Classes, cycles and reference counting are covered in Structures and Classes and Memory and Ownership.

Escaping Closures#

A closure passed as an argument escapes if it may be called after the function it was passed to has returned: because the function stored it, returned it, or gave it to something that keeps it. In Sable, as in Swift, a closure parameter is non-escaping unless its type says @escaping:

Sable
var handlers: (() -> Void)[>..] = []fn onShutdown(_ handler: @escaping () -> Void) {    handlers.append(handler)          // kept: must be @escaping}fn twice(_ body: () -> Void) {    body()                            // only called: needs nothing    body()}

A non-escaping closure parameter may only be called, or passed on to another parameter that is not @escaping either. Storing it, returning it, passing it to an @escaping parameter, or capturing it in a closure that may escape is an error (S3205):

The restriction pays for itself. A non-escaping closure is allocated on the stack and costs nothing, and the compiler knows that everything it captured is only used during the call. Most closures you pass, to map, filter, sort and the like, are non-escaping.

A closure that captures a parameter needs care. An inout parameter can be captured: its value is copied into a box when the call begins and copied back to the caller when it ends, so a closure that runs later changes only the box. An out or T& parameter is the caller's own storage and cannot be captured at all (S3205); copy it into a local and capture that.

@escaping Is Part of the Function Type#

@escaping is written on the parameter's type, handler: @escaping () -> Void, not before the parameter, and it is part of the function's type. (@escaping () -> Int) -> Void is the type of a function that may keep the closure it is given; (() -> Int) -> Void is one that promises not to. A function that keeps less fits where one that may keep more is wanted, but not the other way round (S3004):

Sable
let keep: (@escaping () -> Int) -> Void = keeper.keep    // keep's parameter is @escapinglet look: (@escaping () -> Int) -> Void = keeper.look    // look's is not: it fits toolet lend: (() -> Int) -> Void = keeper.keep              // error: keep may keep it

The same holds of a closure taking a closure. One whose parameter type is not @escaping may not keep what it is given, { f in kept = f } (S3205); one whose type says @escaping, or which says so itself, { (f: @escaping () -> Int) in kept = f }, may.

A method that overrides another, or meets a protocol's requirement, may not add @escaping to a parameter the original lacks (S3210), because a caller going through the original lends its closure only for the call. So what a closure parameter's type promises holds of every function that can be reached through it.

A local function is taken to escape, since it can be passed around like any value.

Closures in Mutating Members#

Inside a mutating member of a struct, a non-escaping closure may change self, just as the member itself may:

Sable
fn each(_ n: Int, _ body: (Int) -> Void) {    for i in 0..<n {        body(i)    }}struct Tally {    var total = 0    var log: Int[>..] = []    mutating fn add(upTo n: Int) {        each(n) { i in            total += i            log.append(i)        }    }}

The closure runs during the member's call if at all, so its changes land on the caller's value, written back however the call ends. A closure that may escape may read self but not change it (S3205), since the change could come after the call is over.

Because the closure's accesses to self happen during the call, a call that changes what the closure uses overlaps it: inner.with { inner.x = 1 } is refused (S3062), while inner.with { count += 1 }, touching another field, is fine. Exclusivity is explained in Memory and Ownership.

In-Out Closure Parameters#

A function type's parameter can be inout, and so can a closure's. The caller of such a function passes &x, as it would to a declared function:

Sable
fn apply(_ change: (inout Int) -> ()) -> Int {    var n = 1    change(&n)    return n}print(apply { (v: inout Int) in v += 1 })   // 2print(apply { $0 *= 7 })                     // 7: '$0' is inout, as the type says

Closures That Throw#

What a closure throws is what its body throws, unless the closure says otherwise. To say, write throws(E) as you would on a function, or bare throws for throws(any Error):

Sable
let parse = { (s: String) throws(ParseError) -> Int in    try Int.parse(s)}let check = (s: String) throws(ParseError) => try validate(s)

A closure is never rethrows (S3664); its type already says exactly what it throws. A try inside a closure belongs to the closure, not to the function the closure is written in, so the enclosing function's throws does not cover it (S3033). Functions that take throwing closures and throw only when they do are rethrows, as described in Error Handling.

A closure whose body uses await is an asynchronous closure. Where two overloads differ only in whether the closure they take is async, that decides which is called (see Functions).

Key Paths as Functions#

A key path such as \.name names a way from a value to one of its parts. Where a function is wanted, a key path can be passed as one, standing for the closure that reads that part:

Sable
let names = people.map(\.name)              // the same as people.map { $0.name }let cities = customers.map(\.address.city)

Key paths are values in their own right too, of type KeyPath<Root, Value>; they are covered in Casting, Metatypes and Reflection.

Sendable Closures#

A closure that will run as a separate task, on another thread, must only capture values that are safe to share between tasks. A parameter marks this with @Sendable on its type, and the compiler then checks that everything the closure captures is Sendable. Task-spawning APIs such as Task.spawn and a task group's spawn take their closures this way. See Concurrency.

Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.