skip to content

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%

answer

  1. fixed-arity overloads before 5.7
  2. fold the block pairwise
  3. a running accumulated value
  4. availability picks the method

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.

solid answer

~40 s

A variadic `buildBlock(_ components: Component...)` forces every line into one `Component` type. A builder that keeps each line's static type had to write generic overloads, `buildBlock<A, B>`, `buildBlock<A, B, C>` and so on, up to a fixed maximum. A body with one more line failed with `extra argument in call`. SE-0348, in Swift 5.7, adds a pairwise fold. The first line goes to `buildPartialBlock(first:)`, and each later line goes to `buildPartialBlock(accumulated:next:)` with the running result. Three lines `Text`, `Int`, `Text` give `Pair<Pair<Text, Int>, Text>` from just two generic methods. When a builder has both forms, the compiler calls `buildPartialBlock` as long as the enclosing declaration is at least as available as both methods. Otherwise it falls back to `buildBlock`. An empty body `{}` still needs a `buildBlock()`.

code

swift · 26 lines
swift
struct Text {
    let content: String
}
struct Pair<A, B> {
    let first: A
    let second: B
}

@resultBuilder
enum PairingBuilder {
    static func buildPartialBlock<A>(first: A) -> A {
        first
    }
    static func buildPartialBlock<A, B>(accumulated: A, next: B) -> Pair<A, B> {
        Pair(first: accumulated, second: next)
    }
}

func compose<R>(@PairingBuilder _ content: () -> R) -> R { content() }

let email = compose {
    Text(content: "Hi Sam,")
    42
    Text(content: "See you soon.")
}
print(type(of: email)) // Pair<Pair<Text, Int>, Text>

go deeper

for a junior

Recall that buildPartialBlock is an alternative to buildBlock that combines a block's lines one at a time.

for a middle

Explain the fold: first: receives the first line, and accumulated:next: receives the running result plus each later line, so the line count is unlimited.

for a senior

Show why typed builders needed it, how availability decides between buildPartialBlock and buildBlock, and why an empty body still needs buildBlock().

for a principal

Choose between a fold, a parameter-pack buildBlock and a plain value builder by the result shape and type-checking cost each puts on every call site.

## The arity problem `buildBlock(_ components: Component...)` is variadic, but a variadic parameter has **one element type**. That suits a builder whose lines all become `[EmailPart]`. It does not suit a **typed builder**, one that keeps each line's static type in the result, as a layout or parsing DSL might. Before Swift 5.7 such a builder had to write **one generic overload per arity**: - `static func buildBlock<A>(_ a: A) -> A` - `static func buildBlock<A, B>(_ a: A, _ b: B) -> Pair<A, B>` - … up to some fixed limit A body with more lines than the largest overload fails. With overloads for one and two lines, a three-line body gives `extra argument in call`. Library authors either generated many overloads or accepted the limit. ## The pairwise fold **SE-0348**, implemented in **Swift 5.7**, adds two methods. The Swift book says to implement both "to support building blocks one component at a time": | Method | Receives | Called for | |---|---|---| | `buildPartialBlock(first:)` | The first line's component | The first statement of a block | | `buildPartialBlock(accumulated:next:)` | The result so far and the next line's component | Every later statement | For a block with lines `e1`, `e2` and `e3`, the transform becomes: 1. `v1 = buildPartialBlock(first: e1)` 2. `v2 = buildPartialBlock(accumulated: v1, next: e2)` 3. `v3 = buildPartialBlock(accumulated: v2, next: e3)` `buildExpression` still runs first on each line, and `buildFinalResult` still runs last, when they are defined. Because each step is its own generic call, the accumulated type can grow with every line. In the code example, `Text`, `42` and `Text` produce `Pair<Pair<Text, Int>, Text>` from two methods, with no arity limit. ## Which method the compiler calls A builder may implement `buildBlock` and both `buildPartialBlock` methods. SE-0348 and the Swift book give the rule: - The compiler uses **`buildPartialBlock`** when both methods exist and the **enclosing declaration is at least as available** as both of them. - Otherwise, it uses **`buildBlock`**. A tracing builder with all three methods confirms the default. A three-line body prints `first(a)`, then `accumulated(a, next: b)` and `accumulated(a+b, next: c)`, and never calls `buildBlock`. Mark both `buildPartialBlock` methods `@available(macOS 99, *)` and the same body calls `buildBlock` instead. A library can use this to ship the new methods without changing how code built for older deployment targets behaves. ## Edge cases worth knowing - **Empty bodies.** The fold needs a first element. A builder with only the `buildPartialBlock` pair rejects `{}` with `result builder 'PairingBuilder' does not implement any 'buildBlock' or a combination of 'buildPartialBlock(first:)' and 'buildPartialBlock(accumulated:next:)' with sufficient availability for this call site`. Adding `static func buildBlock()` handles the empty case. - **Both methods or neither.** The requirement is "either at least one static `buildBlock`, or both" `buildPartialBlock` methods. Defining only `first:` does not satisfy it. - **Nested blocks fold separately.** The body of each `if` or `for` is its own block, so it gets its own fold before `buildEither`, `buildOptional` or `buildArray` sees it. ## Parameter packs as the other answer Swift 5.9's **parameter packs** give a second way to accept any number of differently typed lines. A single `static func buildBlock<each C>(_ c: repeat each C) -> (repeat each C)` compiles a three-line body to the tuple `(Text, Int, Text)`. The two approaches produce different shapes: - **A fold** produces nested pairs and lets the builder react to each step, for example to merge adjacent text. - **A pack** produces one flat tuple in a single call. Either way, the old wall of fixed-arity overloads is no longer needed. ## What it costs - **Deep types.** A ten-line body produces a pair nested ten levels deep. That type appears in diagnostics and symbol names, and the code reading it must unwrap the nesting. - **More calls.** A block of N lines makes N fold calls instead of one `buildBlock` call. For a value builder whose `Component` is an array, the variadic `buildBlock` remains the simpler choice. - **Overloads do not vanish entirely.** A builder whose result depends on each pair of types still overloads `buildPartialBlock(accumulated:next:)`. SE-0348's motivating case needed `O(arity!)` `buildBlock` overloads but only `O(arity^2)` fold overloads: for an arity of 10, about 100 instead of over 3 million.

  • How would a builder that has both buildBlock and buildPartialBlock make older call sites use buildBlock?
    Mark both `buildPartialBlock` methods with an `@available` attribute newer than the call sites that should keep the old behaviour. The compiler uses `buildPartialBlock` only when the enclosing declaration is at least as available as both methods, and falls back to `buildBlock` everywhere else.
  • What happens to an empty closure {} with a builder that only has the buildPartialBlock pair?
    It fails to compile. The compiler reports that the builder `does not implement any 'buildBlock' or a combination of 'buildPartialBlock(first:)' and 'buildPartialBlock(accumulated:next:)' with sufficient availability for this call site`. The fold needs a first element, so the usual fix is to add a `static func buildBlock()` that returns an empty component.

Like a running total on a till: the first item starts the total, and each later item is added to whatever the total already is, so any number of items fits.

  • When both exist, the compiler prefers an exact-arity buildBlock over buildPartialBlock.
  • buildPartialBlock(accumulated:next:) receives every remaining line at once.
  • buildPartialBlock(first:) alone is enough to replace buildBlock.
  • buildPartialBlock also handles an empty body by calling first: with no value.
  • A variadic buildBlock can already keep a different static type for each line.