skip to content

Result Builders

A result builder turns a closure's statements into a value through static build methods, the mechanism behind @ViewBuilder. Interviewers ask how if and for work inside such closures.

on this pageshow

explore

questions

6

In Swift, what does the @resultBuilder attribute do, and how does a closure of separate expression lines become one value?

level: juniorimportance: should knowfreq 35%

answer

  1. a type full of static methods
  2. its name becomes a custom attribute
  3. each line is a partial result
  4. one call combines the partials

basics

~20 s

@resultBuilder marks a type whose static build methods the compiler calls. Where that type is written as an attribute, the compiler rewrites the body: each expression line becomes a partial result, and buildBlock (or buildPartialBlock) combines them into the return value.

solid answer

~50 s

`@resultBuilder` turns a struct, enum or class into a result builder: a set of `static` methods the compiler calls. Nobody instantiates the type and it conforms to no protocol, but it must provide a static `buildBlock(_:)`, or both `buildPartialBlock(first:)` and `buildPartialBlock(accumulated:next:)`. You then write its name as an attribute, `@EmailBuilder`, on a parameter of function type, on a `func`, or on a computed property or subscript that has a getter. At compile time the compiler rewrites that body. Each expression statement becomes a partial result, the partials go to `buildBlock` as unlabeled arguments (or are folded by the `buildPartialBlock` pair), and its result is what the body returns. A closure holding the lines `"Hi Sam,"` and `"Your order has shipped."` compiles to `EmailBuilder.buildBlock("Hi Sam,", "Your order has shipped.")`. Those are ordinary static calls: nothing interprets the closure at run time.

code

swift · 24 lines
swift
@resultBuilder
enum EmailBuilder {
    static func buildBlock(_ lines: String...) -> [String] {
        lines
    }
}

func emailBody(@EmailBuilder _ content: () -> [String]) -> [String] {
    content()
}

let body = emailBody {
    "Hi Sam,"
    "Your order has shipped."
    "Thanks for shopping with us."
}

// What the compiler generates for that closure, written by hand:
let manual = EmailBuilder.buildBlock(
    "Hi Sam,",
    "Your order has shipped.",
    "Thanks for shopping with us."
)
print(body == manual) // true

go deeper

for a junior

Recall that @resultBuilder marks a type of static methods, that its name becomes an attribute, and that buildBlock receives each expression line of the body as a partial result.

for a middle

Explain the transform: expression lines become partial results, local declarations stay as they are, buildBlock combines the partials, and every other statement form needs its own optional build method.

for a senior

Show where the attribute may go, including protocol requirements and stored closure properties, and why a builder on a parameter becomes part of the function's interface for callers.

for a principal

Treat a builder as a compile-time rewrite with a fixed method protocol: judge when that is cheaper for a team to read and maintain than plain array literals or a chained API.

## What the attribute declares A **result builder** is a type that the compiler uses to turn a sequence of statements into a single value. You create one by writing `@resultBuilder` on a `struct`, `enum` or `class`. The Swift book states the two rules that matter first: - All of a builder's behaviour lives in **`static` methods**, so you never create an instance of the builder type. - The type needs **no protocol conformance**. What the compiler checks is that the right method names exist. The one required method is `buildBlock(_:)`, which takes the partial results of a block and combines them. Since Swift 5.7 a builder may instead provide the pair `buildPartialBlock(first:)` and `buildPartialBlock(accumulated:next:)`. A type with neither fails with the error `result builder must provide at least one static 'buildBlock' method, or both 'buildPartialBlock(first:)' and 'buildPartialBlock(accumulated:next:)'`. If `buildBlock` exists but is an instance method, the compiler adds the note `did you mean to make instance method 'buildBlock' static?`. A common choice is an enum with no cases, such as `enum EmailBuilder`, because there is nothing to instantiate. ## Where the attribute goes The builder's name then works as a **custom attribute**. Where you write it decides which body the compiler transforms: | Placement | What gets transformed | |---|---| | A parameter of function type, such as `@EmailBuilder content: () -> [String]` | Every closure a caller passes for that argument | | A `func` declaration | The function's body | | A computed property or subscript with a getter | The getter's body | | A stored property of function type in a struct | The matching parameter of the memberwise initializer | | A protocol requirement | The bodies of the conforming implementations, by inference | Elsewhere the compiler refuses it. A stored property such as `@EmailBuilder var parts: [String] = []` fails with `result builder attribute 'EmailBuilder' can only be applied to a property if it defines a getter`. A parameter that is not a function fails with `can only be applied to a parameter of function type`. ## What the compiler generates The **result builder transform** runs at compile time, statement by statement: 1. Each **expression statement**, such as a string literal on its own line, becomes a **partial result**. It is stored in a hidden local constant. 2. **Local declarations** such as `let greeting = "Hi"` are left alone, so you can name sub-values. 3. At the end of the block, the compiler calls **`buildBlock`** with every partial result as an unlabeled argument, in source order. 4. The value `buildBlock` returns is the body's result, so the closure needs no `return`. The hidden constants have no names you can refer to. What you see in a debugger or a stack trace is ordinary calls to the builder's static methods, which is also the easiest way to step through a builder. So the following two are the same program: ```swift let body = emailBody { "Hi Sam," "Your order has shipped." } let manual = EmailBuilder.buildBlock("Hi Sam,", "Your order has shipped.") ``` Calls to build methods are type-checked like calls you wrote yourself, so normal **overload resolution** applies. That is how one builder can accept several input types. ## What the other build methods unlock `buildBlock` alone handles a straight list of expressions. Every other statement form needs its own optional method: - `buildOptional(_:)` for an `if` without `else` - `buildEither(first:)` and `buildEither(second:)` for `if`/`else` and `switch` - `buildArray(_:)` for `for`-`in` - `buildExpression(_:)` to lift each expression into the builder's own type - `buildFinalResult(_:)` to convert the outermost result - `buildLimitedAvailability(_:)` for `if #available` If a closure uses a statement whose method is missing, the compiler rejects it and names the method to add. ## Common misreadings - **It is not a runtime feature.** No reflection is involved and no interpreter runs. The transform produces ordinary static calls. - **The build methods run every time the body runs.** The rewrite happens once, at compile time. The generated calls run whenever the transformed closure, function or getter is called, so expensive work in `buildBlock` is paid on every call. - **It is not a macro.** The rules are built into the compiler. A builder cannot generate arbitrary code; it only receives values. - **The attribute's position changes the contract.** On a parameter, the attribute is part of the function's interface: callers' closures depend on it, although the ABI does not. On a `func` or getter it changes only that one body.

  • How does a conforming type's computed property get a builder when it never writes the attribute?
    When a protocol requirement carries the attribute, such as `@EmailBuilder var lines: [String] { get }`, a conforming type's implementation of that property infers the builder. There are two exceptions: the implementation writes a builder attribute of its own, or its body contains an explicit `return`. A `return` turns it back into an ordinary getter.
  • What does writing @EmailBuilder on a stored closure property of a struct give callers?
    A stored property of function type, such as `@EmailBuilder let lines: () -> [String]`, passes the attribute to the matching parameter of the implicit memberwise initializer. Callers can then write `Footer { "Unsubscribe"; "Privacy" }` and get the builder transform without anyone writing an initializer by hand.

  • A result builder type has to conform to a protocol before the attribute works.
  • The compiler creates an instance of the builder and calls methods on it.
  • The closure's lines are collected and interpreted at run time.
  • buildExpression is required, otherwise plain expression lines will not compile.
  • A builder attribute can go on any stored property, with or without a getter.
open as a page

Why does a Swift result-builder closure reject guard, break and defer, and what does an explicit return do to it?

level: middleimportance: should knowfreq 28%

basics

~20 s

A builder transform needs every statement to map onto partial results in a fixed structure, so guard, break, continue, defer, while and do-catch are rejected. An explicit return turns the transform off, and the body type-checks as ordinary code.

open as a page

In a Swift result builder, what do buildExpression(_:) and buildFinalResult(_:) let an email DSL accept and return?

level: middleimportance: should knowfreq 18%

basics

~10 s

buildExpression(:) lifts each expression line into the builder's component type, so overloads can accept both String and Link lines. buildFinalResult(:) converts the outermost component into the returned type, such as a rendered String.

open as a page

In a Swift result builder, which build methods let the closure use an if without else and a for-in loop, and what does each receive?

level: middleimportance: should knowfreq 30%

basics

~10 s

buildOptional(:) enables an if without else and receives the branch's block result, or nil when the condition is false. buildArray(:) enables for-in and receives an array holding one block result per iteration.

open as a page

In a Swift result builder, how do if/else and switch become nested buildEither calls, and when is buildLimitedAvailability needed?

level: seniorimportance: should knowfreq 22%

basics

~20 s

The compiler puts each branch at a leaf of a binary tree and wraps its result in buildEither(first:) or buildEither(second:) along the path. buildLimitedAvailability erases an if #available branch's type so it does not leak into the result type.

open as a page

Why did Swift 5.7 add buildPartialBlock(first:) and buildPartialBlock(accumulated:next:) to result builders, and when does the compiler call them?

level: seniorimportance: nice to knowfreq 8%

basics

~20 s

buildPartialBlock folds a block one statement at a time, so a typed builder handles any number of differently typed lines without one buildBlock overload per arity. When both methods exist and are available at the call site, the compiler prefers them.

open as a page