skip to content

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%

answer

  1. branches as leaves of a tree
  2. first means left, second means right
  3. all branches type-checked together
  4. erase a type behind #available

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.

solid answer

~50 s

For `if`/`else` and `switch`, the compiler assigns each result-producing branch a leaf of a binary tree. It then wraps that branch's `buildBlock` result in nested `buildEither(first:)` (left) and `buildEither(second:)` (right) calls along the path from the root. With three `switch` cases, Swift 6.4 emits `first(first(a))`, `first(second(b))` and `second(c)`, writing `first` and `second` for the two methods. Every branch assigns to one variable, so the compiler type-checks all the injections together. A generic builder can therefore return `Either<First, Second>`, and the result type records both branches statically. An `else if` chain with no final `else` gets an extra `buildOptional` around it. That static type is also the risk behind `buildLimitedAvailability(_:)`. If an `if #available` branch holds a type that is unavailable on older systems, that type ends up in the result type. The method erases it before `buildEither` runs. A typed builder without it gets the warning `does not implement 'buildLimitedAvailability'; this code may crash on earlier versions of the OS`.

code

swift · 22 lines
swift
@resultBuilder
enum TraceBuilder {
    static func buildBlock(_ parts: String...) -> String {
        parts.joined(separator: " ")
    }
    static func buildEither(first part: String) -> String { "first(\(part))" }
    static func buildEither(second part: String) -> String { "second(\(part))" }
}

func trace(@TraceBuilder _ content: () -> String) -> String { content() }

enum Plan { case free, trial, paid }

for plan in [Plan.free, .trial, .paid] {
    print(trace {
        switch plan {
        case .free: "Upgrade to read the full issue."
        case .trial: "Your trial ends Friday."
        case .paid: "Thanks for subscribing."
        }
    })
}

go deeper

for a junior

Recall that if/else and switch inside a builder closure need the pair buildEither(first:) and buildEither(second:), and that buildOptional alone is not enough.

for a middle

Explain the tree: each branch is a leaf, and its result is wrapped in first and second calls along the path, so a three-case switch nests two calls deep for two of its cases.

for a senior

Show why all injections type-check together, how a generic Either keeps branch types, and why that same static type needs buildLimitedAvailability behind if #available.

for a principal

Weigh a typed builder that keeps branch types, and pays for it in nested generics and availability erasure, against a value-based builder that stays simple.

## Why a builder needs a special shape for branches A result builder turns each statement of a closure into a **partial result** of a single type that the builder chooses, its `Component`. An `if`/`else` or `switch` produces a value on every path, but each path may produce a **different type**. For example, a typed email builder might return `Paragraph` on one path and `PreviewCard` on another. The builder needs one result type for the whole statement, and it should keep the information about which branch ran. The `buildEither` pair solves this: - `static func buildEither(first component: Component) -> Component` - `static func buildEither(second component: Component) -> Component` The Swift book says to implement both of them "to support `switch` statements and `if` statements that include an `else` clause". ## The injection tree The compiler treats the branches of one statement as the **leaves of a binary tree**: 1. It counts the cases that can produce a result, N. 2. It builds a tree with N leaves and assigns each case to one leaf. 3. In each case, the body is transformed and combined by `buildBlock`. The result is then wrapped once per edge on the path from the root: `buildEither(first:)` for a left edge, `buildEither(second:)` for a right edge. 4. Every case assigns its wrapped value to the **same hidden variable**, which becomes one partial result of the enclosing block. The proposal leaves the exact tree shape to the implementation. The Swift 6.4 compiler produces these shapes, with `first(x)` short for `buildEither(first: x)` and `second(x)` for `buildEither(second: x)`: | Statement | Calls emitted | |---|---| | `if` / `else` | `first(a)`, `second(b)` | | `switch` with 3 cases | `first(first(a))`, `first(second(b))`, `second(c)` | | `switch` with 4 cases | `first(first(a))`, `first(second(b))`, `second(first(c))`, `second(second(d))` | | `if` / `else if` with no final `else` | `buildOptional` around `first(a)` or `second(b)`, and `nil` when neither matches | ## Why the tree keeps types All the assignments to the shared variable are **type-checked together**. A generic builder can declare: - `static func buildEither<F, S>(first: F) -> Either<F, S>` - `static func buildEither<F, S>(second: S) -> Either<F, S>` The compiler then infers `F` from one branch and `S` from the other, so the statement's static type is `Either<Paragraph, PreviewCard>`. Nested `Either` types encode every branch of a `switch`. A UI library can use that to tell two layouts apart without dynamic checks. A builder whose `Component` is a plain array has no such problem: both methods return their argument unchanged. The tree then costs nothing but two trivial calls, and which branch ran is no longer visible in the result. That is the trade between a **typed** builder and a **value** builder: static information about the structure, against simpler types and diagnostics. ## The availability trap That static type is also the hazard. Suppose one branch of an `if #available` uses a type marked `@available(macOS 99, *)`. The type becomes part of the result's generic signature, for example `Either<PreviewCard, Paragraph>`, even on a system where that branch never runs. The Swift book warns that this "could cause your program to crash" if the type isn't available at run time. `static func buildLimitedAvailability(_ component: Component) -> Component` fixes it: - The compiler calls it on the result of a branch that checks an **availability condition**. - That call happens **before** the `buildEither` or `buildOptional` wrapping. - The method returns an always-available type, such as a type-erasing `AnyComponent`, so the less-available type stops at that boundary. After adding it, the example's result type becomes `Either<AnyComponent, Paragraph>`. If a builder that carries types lacks the method, Swift 6.4 warns that the result builder `does not implement 'buildLimitedAvailability'; this code may crash on earlier versions of the OS`, in the `ResultBuilderMethods` diagnostic group. A builder whose components are plain values, like `[String]`, gets no warning, because nothing about the branch reaches the result type. ## What goes wrong in practice - **Only `buildOptional` defined.** An `if` with an `else` is rejected, with a note to add `buildEither(first:)` and `buildEither(second:)`. - **Unrelated return types.** If `buildEither(first:)` and `buildEither(second:)` return unrelated concrete types, the shared variable has no single type. The statement fails to type-check, and Swift 6.4's diagnostic for that case can be unhelpful. - **Deep nesting in the type.** A long `switch` produces deeply nested `Either` types. They are legal, but they show up in diagnostics and symbol names.

  • How do you add buildLimitedAvailability to the typed email builder so the warning goes away?
    Add `static func buildLimitedAvailability(_ component: some EmailComponent) -> AnyComponent`, which wraps the component in a type-erasing struct. The `#available` branch's result now passes through it before `buildEither`. The footer's type becomes `Either<AnyComponent, Paragraph>`, and `PreviewCard` no longer appears in it.
  • In a Swift result builder, what happens to an if / else if chain that has no final else?
    The two result-producing branches still get `buildEither(first:)` and `buildEither(second:)`. Because the chain may also produce nothing, the merged value is wrapped as an optional and passed to `buildOptional(_:)`, which receives `nil` when no condition matches. So such a chain needs both the `buildEither` pair and `buildOptional`.

Like giving directions through a tournament bracket: to reach the second of three teams you say left, then right. buildEither(first:) and buildEither(second:) are those left and right turns, written outermost first.

  • buildOptional is enough for if/else, because the else branch is just another optional.
  • buildEither(first:) and buildEither(second:) must return different types so the branches can be told apart.
  • A three-case switch calls buildEither once with the index of the matching case.
  • buildLimitedAvailability checks the operating system version at run time.
  • Every result builder needs buildLimitedAvailability before it can contain an if #available.