skip to content

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%

answer

  1. one method per statement form
  2. a branch that may produce nothing
  3. Optional of a component
  4. one component per iteration

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.

solid answer

~50 s

Every statement form in a builder closure needs its own build method. An `if` without `else`, including `if let` and `if case`, needs `static func buildOptional(_ component: Component?) -> Component`. When the condition holds, the branch body runs through `buildBlock` and that result is passed in. Otherwise the compiler passes `nil`, and the builder decides what nothing looks like, typically an empty array. A `for`-`in` loop needs `static func buildArray(_ components: [Component]) -> Component`. Each iteration's body goes through `buildBlock`, the results are appended to a temporary array, and that array, with one element per iteration, is passed in once. Without these methods the compiler rejects the closure with `closure containing control flow statement cannot be used with result builder` and a note naming the method to add. An `if` with an `else` needs the `buildEither` pair instead.

code

swift · 31 lines
swift
@resultBuilder
enum DigestBuilder {
    static func buildExpression(_ line: String) -> [String] { [line] }
    static func buildBlock(_ parts: [String]...) -> [String] {
        print("buildBlock(\(parts.count) parts)")
        return parts.flatMap { $0 }
    }
    static func buildOptional(_ part: [String]?) -> [String] {
        print("buildOptional(\(part == nil ? "nil" : "value"))")
        return part ?? []
    }
    static func buildArray(_ parts: [[String]]) -> [String] {
        print("buildArray(\(parts.count) iterations)")
        return parts.flatMap { $0 }
    }
}

func digest(@DigestBuilder _ body: () -> [String]) -> [String] { body() }

let unread = ["Release notes", "Survey"]
let hasCoupon = false
let lines = digest {
    "Your weekly digest"
    for title in unread {
        "New: \(title)"
    }
    if hasCoupon {
        "Here is 10% off."
    }
}
print(lines)

go deeper

for a junior

Remember the pairing: an if without else needs buildOptional, and a for-in loop needs buildArray. Without them the closure does not compile.

for a middle

Explain the rewrite: buildOptional receives nil or the branch's buildBlock result, and buildArray receives an array of per-iteration buildBlock results, collected once after the loop.

for a senior

Read the compiler's note to know which method is missing, pick deliberate empty values, and know that buildOptional never covers if/else or while loops.

for a principal

Decide how much control flow a DSL should accept: each supported statement form is another build method to maintain and another way for call sites to grow complicated.

## The problem these methods solve A result builder combines a block's **partial results**, the values its expression lines produce, with `buildBlock(_:)`. A straight list of lines always produces one partial result per line. Control flow breaks that pattern: - An **`if` without `else`** may produce a value or produce nothing. - A **`for`-`in` loop** produces one value per iteration, and the count is known only at run time. `buildBlock` alone cannot express either case, so the builder opts in to each statement form with a dedicated `static` method. The Swift book defines both, in its own words: | Method | Signature | Enables | |---|---|---| | `buildOptional(_:)` | `(Component?) -> Component` | `if` statements that don't include an `else` clause | | `buildArray(_:)` | `([Component]) -> Component` | `for` loops | `Component` is the builder's type for a partial result. In an email DSL it might be `[String]` or `[EmailPart]`. ## How an if without else is rewritten The compiler turns the `if` into a hidden optional variable: 1. It declares a local `Component?` initialised to `nil`. 2. If the condition holds, the branch body is transformed recursively. Its lines become partial results, `buildBlock` combines them, and the result is assigned to the variable. 3. After the `if`, the compiler calls **`buildOptional`** with that variable, whether it holds a value or `nil`. The return value is one partial result of the enclosing block. A branch body with several lines still contributes one partial result to the enclosing block, because its lines are combined by `buildBlock` first. The call happens on both paths, so `buildOptional` must decide what a missing branch contributes. For an array-based builder that is usually `[]`. The same rewrite covers `if let`, `if case` and an `else if` chain without a final `else`. In that last case the chain's `buildEither` result is wrapped before `buildOptional` sees it. ## How a for-in loop is rewritten The compiler keeps the loop and adds an array around it: 1. It declares a temporary array of components before the loop. 2. In each iteration, the body is transformed like any block, and its `buildBlock` result is **appended** to the array. 3. After the loop, **`buildArray`** receives the whole array, and its result is one partial result of the enclosing block. A loop over two unread articles calls `buildBlock` twice, once per iteration, and then `buildArray` once with two elements. A `where` clause on the loop works as usual and only skips iterations. `while` and `repeat`-`while` are not supported, even if the builder has `buildArray`. Written by hand, the digest from the code example looks like this; comparing `manual` with the builder's output prints `true`: ```swift var iterations: [[String]] = [] for title in unread { iterations.append(DigestBuilder.buildBlock(DigestBuilder.buildExpression("New: \(title)"))) } var couponPart: [String]? = nil if hasCoupon { couponPart = DigestBuilder.buildBlock(DigestBuilder.buildExpression("Here is 10% off.")) } let manual = DigestBuilder.buildBlock( DigestBuilder.buildExpression("Your weekly digest"), DigestBuilder.buildArray(iterations), DigestBuilder.buildOptional(couponPart) ) ``` ## What the compiler says when a method is missing Swift 6.4 reports the same error for each unsupported statement, `closure containing control flow statement cannot be used with result builder 'LinesBuilder'`, and attaches a note on the builder type that names the fix: - `add 'buildOptional(_:)' to the result builder 'LinesBuilder' to add support for 'if' statements without an 'else'` - `add 'buildArray(_:)' to the result builder 'LinesBuilder' to add support for 'for'..'in' loops` - `add 'buildEither(first:)' and 'buildEither(second:)' to the result builder 'LinesBuilder' to add support for 'if'-'else' and 'switch'` The third note matters because **`buildOptional` does not cover `if`/`else`**. A builder with only `buildBlock` and `buildOptional` still rejects an `if` that has an `else`. ## Design choices inside the methods - **Choose the empty value deliberately.** Returning `[]` from `buildOptional(nil)` is natural for a list. A typed builder might return an optional wrapper instead, so the result type records that the content can be absent. - **Flatten in `buildArray`.** With `[String]` components the method usually returns `components.flatMap { $0 }`, so the loop contributes its lines in order. - **Keep the methods cheap.** They run every time the closure runs, once per iteration for the loop body's `buildBlock`. - **Test them directly.** They are ordinary static functions, so a unit test can call `DigestBuilder.buildOptional(nil)` or `DigestBuilder.buildArray([["a"], ["b"]])` and check the result without writing a builder closure.

  • Does an if let in a builder closure use a different method from a plain if without else?
    No. `if let`, `if case` and a plain `if` without `else` all go through `buildOptional(_:)`. The binding is visible inside the branch body, whose lines are combined by `buildBlock` before `buildOptional` receives them. When the binding fails, `buildOptional` receives `nil`.
  • In a result builder, why does a loop body with two lines still give buildArray one element per iteration?
    Each iteration's body is a block, so its two partial results are first combined by `buildBlock`. That combined value is what gets appended to the temporary array. `buildArray` therefore receives one element per iteration, each already holding both lines.

  • buildOptional is called only when the if condition is true.
  • buildOptional also makes if/else compile, so buildEither is optional.
  • buildArray is called once per iteration of the loop.
  • With buildArray defined, while loops work inside builder closures too.
  • buildArray receives one element per expression line in the loop body.