Why does a Swift result-builder closure reject guard, break and defer, and what does an explicit return do to it?
answer
- strictly structural statements only
- every path must yield partial results
- return switches the transform off
- one-way type checking per line
basics
~20 sA 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.
solid answer
~50 sThe transform maps each statement onto partial results in a fixed tree. Expression lines, local declarations, `if`, `switch`, `for`-`in` and `do` without `catch` fit that tree, and so does `throw` when the closure's type is throwing. `guard`, `break`, `continue`, `defer`, `while`, `repeat`-`while` and `do`-`catch` would skip or reorder partial results, so the compiler rejects them with `closure containing control flow statement cannot be used with result builder`. An explicit `return` switches the transform off. In a closure there is no builder diagnostic for that, only `unused` warnings on the lines before it, and the closure must return the whole result itself. In a `func` or getter that carries the attribute, Swift warns `application of result builder 'EmailBuilder' disabled by explicit 'return' statement`. The fix for `guard let` is usually `if let` with an `else`. Each line is also type-checked on its own, which keeps large bodies tractable but limits inference across lines.
code
swift · 15 lines@resultBuilder
enum EmailBuilder {
static func buildBlock(_ parts: [String]...) -> [String] { parts.flatMap { $0 } }
static func buildExpression(_ line: String) -> [String] { [line] }
static func buildOptional(_ part: [String]?) -> [String] { part ?? [] }
}
func emailBody(@EmailBuilder _ content: () -> [String]) -> [String] { content() }
let recipient: String? = nil
let body = emailBody {
guard let recipient else { "Hi there," }
"Hi \(recipient),"
}go deeper
Recall which statements a builder closure accepts: expressions, let, if, switch and for-in. Rewrite guard as if let with else.
Explain why skipping or jumping statements cannot map onto partial results, and how an explicit return disables the transform with or without a warning.
Diagnose return statements that quietly disable a builder, and slow type checks in large builder bodies. Measure with the long-expression warning and split bodies into smaller builder functions.
Set house rules for builder bodies, such as size limits and extracted sub-builders, so compile times and readability stay predictable as DSL use grows.
## The design rule: strictly structural SE-0289 limits builder bodies to statements that are "strictly structural". Each statement must map onto partial results in a fixed shape that build methods can combine: - An expression line produces one partial result. - `if` produces an optional result or an `Either` tree. - `for`-`in` produces an array of results. - Everything else is either left alone or rejected. A statement that could **skip** later lines, **jump** out of a block or **reorder** evaluation has no place in that shape. | Statement | In a builder closure (Swift 6.4) | |---|---| | Expression line | Becomes a partial result | | `let` / `var` declaration | Left alone (since Swift 5.8, also without an initializer or with a property wrapper) | | `if`, `if let`, `if case`, `switch` | Allowed if the builder has `buildOptional` / `buildEither` | | `for`-`in`, including `where` | Allowed if the builder has `buildArray` | | `do` without `catch` | Treated as a nested block | | `throw` | Left alone; the closure's function type must be throwing | | `#warning`, `#error` | Left alone | | `guard`, `break`, `continue`, `defer` | Rejected | | `while`, `repeat`-`while`, `do`-`catch` | Rejected | The rejected statements all produce the same error: `closure containing control flow statement cannot be used with result builder 'EmailBuilder'`. The proposal records that some of them "may be supported in the future". None is supported in Swift 6.4. ## Rewriting the common cases - **`guard let`** becomes `if let ... { } else { }`. The happy path moves inside the `if`, and the builder needs the `buildEither` pair. - **An early exit from a loop** becomes a filter: `for item in items where item.isVisible`, or a `prefix` on the sequence before the loop. - **`while` loops** become `for`-`in` over a sequence computed beforehand. - **Error handling with `do`-`catch`** moves outside the builder. Compute the value first, then use it in the body. ## What an explicit return does `return` is not rejected. It **disables the transform**: - **In a closure** passed to a builder parameter, the transform is suppressed with no diagnostic about the builder. The closure is then type-checked as an ordinary closure, so its `return` must produce the parameter's full return type. Each expression line before the `return` only gets an ordinary warning, such as `string literal is unused`. - **In a `func`, property or subscript** that explicitly carries the attribute, Swift 6.4 warns `application of result builder 'LinesBuilder' disabled by explicit 'return' statement`. It offers two notes: remove the attribute, or remove the `return` statements. The other lines then become unused values and are also flagged. - **For a builder inferred from a protocol requirement**, a `return` in the conforming body is the documented way to opt out of the inferred builder. The closure case causes confusing bugs. Someone adds a `return` while debugging, and the lines before it stop contributing. The only signal is an `unused` warning that is easy to miss among others. ## Type checking: one way, line by line Each expression line is type-checked **on its own**, as if it were `let v = <line>`, and `buildBlock` cannot influence those types afterwards. SE-0289 shows the effect. With `buildBlock<T>(_ a: T, _ b: T)`, the lines `42` and `3.5` fail with `conflicting arguments to generic parameter 'T' ('Int' vs. 'Double')`, even though `42` could have been a `Double`. The proposal explains why the rule exists. The first implementation propagated types backwards, which made type-checking time grow exponentially with body size. The one-way rule resolved most reports of the compiler's "unable to type-check this expression in reasonable time" error in large bodies. That error's full text is `the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions`. The rule keeps bodies tractable, but a long builder body can still type-check slowly. Practical steps: 1. Measure with `-Xfrontend -warn-long-expression-type-checking=<ms>`, which warns about each expression that takes longer than the limit. 2. Move sub-sections into separate functions or properties with their own builder attribute and an explicit return type. 3. Give generic results explicit types where inference has many candidates. Because each line is checked on its own, an error in one line usually stays on that line. A wrong type in the middle of a long email body is reported where it is written, not at the end of the closure.
- Can a builder closure throw an error from inside an if branch?Yes, if the closure's function type is throwing. `throw` is left alone by the transform, so `if name == nil { throw ValidationError.missingName }` works when the parameter is `() throws -> [String]`. With a non-throwing parameter type, the compiler reports an invalid conversion from a throwing function type.
- Why might adding a return while debugging a builder closure change its output without a compile error?A `return` in a closure passed to a builder parameter suppresses the transform with no diagnostic about the builder. The closure becomes ordinary code. If the `return` value still matches the parameter's return type, it compiles, and every expression line before the `return` stops contributing; each one only gets an `unused` warning. Only the returned value is used.
- guard works in a builder closure as long as the else branch produces a value.
- An explicit return always produces a compile error inside a builder closure.
- while loops work in a builder closure as long as the builder defines buildArray.
- Local let declarations are forbidden inside a builder closure.
- buildBlock's generic signature helps infer the types of the lines before it.