In a Swift result builder, what do buildExpression(_:) and buildFinalResult(_:) let an email DSL accept and return?
answer
- three placeholder types
- the first transform and the last
- overloads per input type
- outermost block only
basics
~10 sbuildExpression(:) 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.
solid answer
~40 sA builder works with three types. `Expression` is what a line may contain, `Component` is what build methods pass around, and `FinalResult` is what the body returns. Without the two optional methods, `Expression` and `FinalResult` default to `Component`. `buildExpression(_:)` is the first transform: each expression line becomes a call to it. Overloads such as `buildExpression(_ text: String)` and `buildExpression(_ link: Link)` let one email DSL accept several input types and lift both into `[EmailPart]`. It also gives the line a contextual type, so `.text("Hi")` can work, and a line of an unsupported type fails with `no exact matches in call to static method 'buildExpression'`. `buildFinalResult(_:)` is the last transform. It runs once, on the outermost block's result, so inner blocks stay in `[EmailPart]` and only the finished body becomes, say, a rendered `String`.
code
swift · 30 linesenum EmailPart {
case text(String)
case link(title: String, url: String)
}
struct Link { let title: String; let url: String }
@resultBuilder
enum EmailBuilder {
static func buildExpression(_ text: String) -> [EmailPart] { [.text(text)] }
static func buildExpression(_ link: Link) -> [EmailPart] {
[.link(title: link.title, url: link.url)]
}
static func buildBlock(_ parts: [EmailPart]...) -> [EmailPart] { parts.flatMap { $0 } }
static func buildFinalResult(_ parts: [EmailPart]) -> String {
parts.map { part in
switch part {
case .text(let text): text
case .link(let title, let url): "\(title) <\(url)>"
}
}.joined(separator: "\n")
}
}
@EmailBuilder
func welcomeEmail(name: String) -> String {
"Hi \(name),"
"Your account is ready."
Link(title: "Open settings", url: "https://example.com/settings")
}
print(welcomeEmail(name: "Sam"))go deeper
Recall that buildExpression handles each line as it is written and buildFinalResult shapes what the whole body returns.
Explain the three placeholder types, why buildExpression overloads let a DSL mix input types, and why buildFinalResult runs only once, on the outermost block.
Use buildExpression for early, readable type errors and for context, and recognise the leading-dot parsing trap and the () value of assignment lines.
Decide what the DSL's public currency is. Keep the internal component type out of the API with buildFinalResult, so it can change without breaking call sites.
## Three types, not one The Swift book describes a result builder's methods using three placeholder types: | Placeholder | Meaning | Default | |---|---|---| | `Expression` | The type of a line written in the body | `Component`, when there is no `buildExpression(_:)` | | `Component` | The type of a partial result passed between build methods | Chosen by the builder | | `FinalResult` | The type the transformed body returns | `Component`, when there is no `buildFinalResult(_:)` | A builder with only `buildBlock` makes all three the same type. That is fine for a list of strings. It is awkward for an email DSL that wants writers to mix text and links, while it builds an `[EmailPart]` internally and hands callers a rendered `String`. ## buildExpression: the first transform `static func buildExpression(_ expression: Expression) -> Component` is, in the book's words, "always first". Each expression line becomes `EmailBuilder.buildExpression(line)` before anything else happens. This gives a builder three abilities: 1. **Accept several input types.** Overloads follow normal overload resolution, so `buildExpression(_ text: String)` and `buildExpression(_ link: Link)` both work. Each lifts its input into `[EmailPart]`. 2. **Reject the wrong ones.** A line like `42` matches no overload and fails with `no exact matches in call to static method 'buildExpression'`. A builder without `buildExpression` reports the same line as a failed conversion to `buildBlock`'s parameter type: `cannot convert value of type 'Int' to expected argument type 'String'`. 3. **Provide context for type inference.** Without it, a line such as `.text("Hi")` fails with `cannot infer contextual base in reference to member 'text'`, because each line is type-checked on its own. With an overload `buildExpression(_ part: EmailPart)`, the line has a contextual type and compiles. An **assignment** in the body is treated as an expression whose value is `()`. A builder that wants to allow assignments can add an overload that takes `()`. Without one, an assignment line fails to convert `()` to the expected type. ## A parsing trap with leading dots A context from `buildExpression` does not change how the parser joins lines. When one line ends with an expression and the next line begins with `.`, Swift reads the second line as a **member access on the first**. In the email builder, the lines `.text("Hi")` and then `.link(title: "Docs", url: ...)` are parsed as one expression. They fail with `enum case 'link' cannot be used as an instance member`. Wrapping the value in a call or a type name, as in `EmailPart.link(...)` or `Link(...)`, avoids the problem. ## buildFinalResult: the last transform `static func buildFinalResult(_ component: Component) -> FinalResult` is "always last". The compiler calls it **once**, on the combined result of the **outermost** block only: - Inner blocks, such as the bodies of `if`, `switch` and `for`, keep returning `Component`, so other build methods can combine them. - The body's declared return type must match `FinalResult`. In the code example, `@EmailBuilder func welcomeEmail(name:) -> String` returns `String` even though every method in between works on `[EmailPart]`. Typical uses: - **Hide the internal currency.** Callers get a `String` or an `Email` value and never see `[EmailPart]`. - **Post-process.** Join, validate or normalise the finished parts in one place. ## How they fit around the other methods For the email body, the order is: 1. `buildExpression` for each line 2. `buildBlock` (or `buildOptional`, `buildEither`, `buildArray` for control flow) at each level 3. `buildFinalResult` once at the top A trace with a `buildFinalResult` that prints confirms it: a body with nested `if let` and `if case` branches prints the final call **once**, with all four parts. ## When to add each one - **Add `buildExpression`** when lines should accept more than one type, when you want errors to name the DSL's inputs, or when lines use implicit members of the builder's own types. - **Skip it** when every line is already a `Component`. Without the method, lines go straight to `buildBlock`, and the error for a wrong line comes from that call instead. - **Add `buildFinalResult`** when the type callers receive should differ from the one the methods pass around, or when the finished result needs one last check. - **Keep both small.** `buildExpression` runs once per line and `buildFinalResult` once per call of the body, every time the body runs.
- Why does an implicit member such as .text("Hi") fail in a builder closure that has no buildExpression?Each expression line is type-checked on its own, as if written `let v = .text("Hi")`, so nothing supplies the base type. The compiler reports `cannot infer contextual base in reference to member 'text'`. An overload `buildExpression(_ part: EmailPart)` makes the line an argument to that method, which gives it the context it needs.
- Can buildFinalResult run on the result of an if branch inside the builder closure?No. The compiler calls it only on the combined result of the outermost block, after every other build method. Branch and loop bodies return `Component` to `buildOptional`, `buildEither` or `buildArray`, so only the finished body is converted to `FinalResult`.
- buildExpression runs after buildBlock to convert the combined result.
- buildFinalResult is applied to every block, including if and for bodies.
- A builder can only accept one type of line because buildExpression cannot be overloaded.
- With buildExpression defined, any implicit member line works anywhere in the body.
- buildFinalResult must return the same type as Component.