Result builders
suggest changeA result builder lets you write a closure or function body as a list of plain expressions, one per line, and have the compiler combine them into a single value. There is no return, no array literal and no +:
let card = Card {
"Ada Lovelace"
"Mathematician"
}
This is the mechanism behind SwiftUI's VStack { ... } and the Regex { ... } blocks of RegexBuilder. It's not specific to Apple frameworks. Any type marked with @resultBuilder can be used this way, and you can write your own to build strings, HTML, SQL, configuration or test data.
Result builders were added in Swift 5.4 (SE-0289). Swift 5.7 added buildPartialBlock (SE-0348).
The examples were compiled and run with Swift 6.4 on Windows:
swiftc -swift-version 6 main.swift -o main.exe
A minimal result builder
A result builder is a type (usually a struct or an enum with no cases) marked @resultBuilder. It has static methods with special names. The only required one is buildBlock, which receives the value of every line in the block:
@resultBuilder
struct LinesBuilder {
static func buildBlock(_ lines: String...) -> String {
lines.joined(separator: "\n")
}
}
@LinesBuilder
func greeting() -> String {
"Hello"
"from a"
"result builder"
}
print(greeting())
func makeText(@LinesBuilder _ content: () -> String) -> String {
content()
}
let text = makeText {
"first"
"second"
}
print(text)
Output:
Hello
from a
result builder
first
second
The builder's name becomes an attribute. There are two ways to use it:
- On a function, method or computed property (
@LinesBuilder func greeting()). Its body is transformed. - On a closure parameter (
@LinesBuilder _ content: () -> String). Every closure passed for that parameter is transformed. This is how DSLs are usually exposed, typically combined with trailing closure syntax.
What the compiler does
A result builder is a source transformation. The compiler stores each line in a local variable and passes them all to buildBlock. The greeting() body above is compiled as if you had written:
func greetingExpanded() -> String {
let v0 = "Hello"
let v1 = "from a"
let v2 = "result builder"
return LinesBuilder.buildBlock(v0, v1, v2)
}
print(greetingExpanded())
Hello
from a
result builder
Everything else follows from this. Every buildXxx method handles one kind of statement, and the compiler only allows a statement if the builder has the method for it. Type checking happens on the transformed code, so if a line's type doesn't match a buildBlock parameter, you get an ordinary type error:
@LinesBuilder
func f() -> String {
"a"
42
}
error: cannot convert value of type 'Int' to expected argument type 'String'
The builder methods
| Method | Enables |
|---|---|
buildBlock(_:...) |
a list of statements (required unless you use buildPartialBlock) |
buildExpression(_:) |
converting each expression before it reaches buildBlock |
buildOptional(_:) |
if without else |
buildEither(first:), buildEither(second:) |
if/else and switch |
buildArray(_:) |
for ... in loops |
buildFinalResult(_:) |
converting the combined value into the value the function returns |
buildLimitedAvailability(_:) |
if #available(...) blocks |
buildPartialBlock(first:), buildPartialBlock(accumulated:next:) |
combining lines pairwise, instead of buildBlock |
All of them are static. You only write the ones you need. Overloading is allowed and common: the compiler picks the overload by type, like for any other call.
Control flow: if, switch and for
Without the extra methods, control flow is rejected. Adding an if to LinesBuilder gives:
@LinesBuilder
func f(flag: Bool) -> String {
"a"
if flag {
"b"
}
}
error: closure containing control flow statement cannot be used with result builder 'LinesBuilder'
note: add 'buildOptional(_:)' to the result builder 'LinesBuilder' to add support for 'if' statements without an 'else'
With control flow, an if can produce zero lines and a for loop can produce many. That's easier to handle if every partial result has the same type. A common design is to make the intermediate type an array ([String]), turn each expression into an array with buildExpression, and turn the final array into the return type with buildFinalResult:
@resultBuilder
struct LinesBuilder {
static func buildBlock(_ lines: [String]...) -> [String] {
lines.flatMap { $0 }
}
static func buildExpression(_ line: String) -> [String] {
[line]
}
static func buildOptional(_ lines: [String]?) -> [String] {
lines ?? []
}
static func buildEither(first lines: [String]) -> [String] {
lines
}
static func buildEither(second lines: [String]) -> [String] {
lines
}
static func buildArray(_ groups: [[String]]) -> [String] {
groups.flatMap { $0 }
}
static func buildFinalResult(_ lines: [String]) -> String {
lines.joined(separator: "\n")
}
}
enum Level { case low, medium, high }
@LinesBuilder
func report(user: String?, level: Level, items: [String], verbose: Bool) -> String {
"Report"
if let user {
"user: \(user)"
}
if verbose {
"mode: verbose"
} else {
"mode: short"
}
switch level {
case .low: "level: low"
case .medium: "level: medium"
case .high: "level: HIGH"
}
for (i, item) in items.enumerated() {
" \(i + 1). \(item)"
}
"end"
}
print(report(user: "ada", level: .high, items: ["milk", "eggs"], verbose: true))
print("---")
print(report(user: nil, level: .low, items: [], verbose: false))
Output:
Report
user: ada
mode: verbose
level: HIGH
1. milk
2. eggs
end
---
Report
mode: short
level: low
end
How each statement is translated:
if let user { ... }builds its body withbuildBlock, then callsbuildOptionalwith the result, or withnilif the condition was false.if let,if caseandelse ifchains all work.if/elsecallsbuildEither(first:)for thethenbranch andbuildEither(second:)for theelsebranch.switchalso usesbuildEither. With more than 2 cases the compiler nests the calls into a balanced binary tree:first(first(...)),first(second(...))and so on.forbuilds the loop body once per iteration and passes all results tobuildArray.buildFinalResultruns once at the end. That's whyreportcan returnStringwhile everything inside is[String].
buildExpression: accepting different types
buildExpression is called on every expression line before it's passed to buildBlock. Overload it to accept several types:
@resultBuilder
struct LinesBuilder {
static func buildBlock(_ lines: [String]...) -> [String] { lines.flatMap { $0 } }
static func buildExpression(_ line: String) -> [String] { [line] }
static func buildExpression(_ number: Int) -> [String] { [String(number)] }
static func buildExpression(_ lines: [String]) -> [String] { lines }
static func buildExpression(_ nothing: Void) -> [String] { [] }
static func buildFinalResult(_ lines: [String]) -> String {
lines.joined(separator: "\n")
}
}
@LinesBuilder
func info() -> String {
let name = "Swift"
let version = 6
"name: \(name)"
version
["a", "b"]
print("side effect while building")
}
print(info())
Output:
side effect while building
name: Swift
6
a
b
Notes:
letandvardeclarations are allowed in a builder body. They're not passed to the builder, they're just local variables.- A call that returns
Void, such asprint, is an expression too. Without theVoidoverload, it would be passed to the builder and fail to type-check. The overload makes it contribute nothing. - The side effect runs while the body is executed, which is before
buildFinalResultjoins the lines, so it's printed first.
You can also use buildExpression to give better error messages. Mark an overload unavailable and the compiler shows your message:
@resultBuilder
enum LinesBuilder {
static func buildBlock(_ lines: String...) -> String { lines.joined(separator: "\n") }
static func buildExpression(_ line: String) -> String { line }
@available(*, unavailable, message: "convert numbers with String(_:) first")
static func buildExpression(_ number: Int) -> String { fatalError() }
}
@LinesBuilder
func f() -> String {
"a"
42
}
error: 'buildExpression' is unavailable: convert numbers with String(_:) first
Statements you can't use
Only declarations, expressions, if, switch, for ... in and do blocks are transformed. Other control flow is an error, no matter which methods the builder has:
@LinesBuilder
func f() -> String {
var i = 0
while i < 3 {
"x"
i += 1
}
}
error: closure containing control flow statement cannot be used with result builder 'LinesBuilder'
The same applies to repeat, break and continue. guard is a special case: its else must exit with return, and an explicit return turns the builder off for the whole body:
@LinesBuilder
func f(name: String?) -> String {
guard let name else { return "" }
"Hello \(name)"
}
warning: application of result builder 'LinesBuilder' disabled by explicit 'return' statement
warning: string literal is unused
error: missing return in global function expected to return 'String'
This is deliberate. Writing return is how you opt out of the builder in a function that has the attribute. Use if let instead of guard let inside builders.
Example: an HTML DSL
Here is a complete builder that produces an HTML tree. The intermediate type is [Node], so a block can produce any number of nodes:
indirect enum Node {
case element(String, [String: String], [Node])
case text(String)
func render(indent: Int = 0) -> String {
let pad = String(repeating: " ", count: indent)
switch self {
case .text(let s):
return pad + escape(s)
case .element(let tag, let attrs, let children):
let a = attrs.sorted { $0.key < $1.key }
.map { " \($0.key)=\"\(escape($0.value))\"" }
.joined()
if children.isEmpty {
return "\(pad)<\(tag)\(a)></\(tag)>"
}
if children.count == 1, case .text(let s) = children[0] {
return "\(pad)<\(tag)\(a)>\(escape(s))</\(tag)>"
}
let inner = children.map { $0.render(indent: indent + 1) }
.joined(separator: "\n")
return "\(pad)<\(tag)\(a)>\n\(inner)\n\(pad)</\(tag)>"
}
}
}
func escape(_ s: String) -> String {
s.replacing("&", with: "&")
.replacing("<", with: "<")
.replacing(">", with: ">")
.replacing("\"", with: """)
}
@resultBuilder
enum HTMLBuilder {
static func buildBlock(_ parts: [Node]...) -> [Node] { parts.flatMap { $0 } }
static func buildExpression(_ node: Node) -> [Node] { [node] }
static func buildExpression(_ text: String) -> [Node] { [.text(text)] }
static func buildExpression(_ nodes: [Node]) -> [Node] { nodes }
static func buildOptional(_ nodes: [Node]?) -> [Node] { nodes ?? [] }
static func buildEither(first nodes: [Node]) -> [Node] { nodes }
static func buildEither(second nodes: [Node]) -> [Node] { nodes }
static func buildArray(_ groups: [[Node]]) -> [Node] { groups.flatMap { $0 } }
}
func element(_ tag: String, _ attrs: [String: String] = [:],
@HTMLBuilder _ content: () -> [Node] = { [] }) -> Node {
.element(tag, attrs, content())
}
func html(@HTMLBuilder _ c: () -> [Node]) -> Node { element("html", [:], c) }
func body(@HTMLBuilder _ c: () -> [Node]) -> Node { element("body", [:], c) }
func h1(_ text: String) -> Node { element("h1") { text } }
func p(@HTMLBuilder _ c: () -> [Node]) -> Node { element("p", [:], c) }
func ul(@HTMLBuilder _ c: () -> [Node]) -> Node { element("ul", [:], c) }
func li(@HTMLBuilder _ c: () -> [Node]) -> Node { element("li", [:], c) }
func a(href: String, @HTMLBuilder _ c: () -> [Node]) -> Node {
element("a", ["href": href], c)
}
struct Book { let title: String; let url: String? }
func page(user: String?, books: [Book]) -> Node {
html {
body {
h1("Reading list")
if let user {
p { "Signed in as \(user)" }
} else {
p { "Not signed in" }
}
if books.isEmpty {
p { "Nothing yet" }
} else {
ul {
for book in books {
li {
if let url = book.url {
a(href: url) { book.title }
} else {
book.title
}
}
}
}
}
}
}
}
let books = [
Book(title: "Essential Swift", url: "https://www.programming-books.io/essential/swift/"),
Book(title: "Tom & Jerry <draft>", url: nil),
]
print(page(user: "ada", books: books).render())
print(page(user: nil, books: []).render())
Output:
<html>
<body>
<h1>Reading list</h1>
<p>Signed in as ada</p>
<ul>
<li>
<a href="https://www.programming-books.io/essential/swift/">Essential Swift</a>
</li>
<li>Tom & Jerry <draft></li>
</ul>
</body>
</html>
<html>
<body>
<h1>Reading list</h1>
<p>Not signed in</p>
<p>Nothing yet</p>
</body>
</html>
Things to notice:
- Each tag is an ordinary function whose last parameter is an
@HTMLBuilderclosure. Nesting the closures nests the elements. Each closure is transformed separately. h1("...")andp { "..." }are both just expressions that return aNode. A builder doesn't care how a value was made.- Text goes through
escape, so user data can't inject tags. Building a tree first and rendering it later makes that easy to guarantee. Concatenating strings doesn't. - Since
HTMLBuilderis never instantiated, it's anenumwith no cases.
Compared to the classic Builder Pattern, there are no builder objects or chained method calls. The structure of the code is the structure of the output.
Inference from protocols and use in initializers
If a protocol requirement has a builder attribute, conforming types get it automatically. You don't have to repeat it. SwiftUI's View.body works this way. A builder parameter on an initializer is the usual way to make a container type:
@resultBuilder
struct LinesBuilder {
static func buildBlock(_ lines: String...) -> String {
lines.joined(separator: "\n")
}
}
protocol Section {
@LinesBuilder var body: String { get }
}
struct Header: Section {
let title: String
var body: String { // @LinesBuilder is inferred from the protocol
"# \(title)"
"=========="
}
}
struct Card {
let content: String
init(@LinesBuilder content: () -> String) {
self.content = content()
}
}
print(Header(title: "News").body)
let card = Card {
"Ada Lovelace"
"Mathematician"
}
print(card.content)
Output:
# News
==========
Ada Lovelace
Mathematician
Card calls the closure right away in init, so the parameter is non-escaping. If you store the closure and call it later, mark it @escaping like any other closure parameter, see Escaping closure.
buildPartialBlock: combining lines one at a time
buildBlock gets all lines at once. That's a problem when each line has a different type and the result type depends on all of them: you'd need one overload for every number of lines. buildPartialBlock (Swift 5.7) solves it differently. The compiler folds the lines from left to right:
@resultBuilder
enum TraceBuilder {
static func buildPartialBlock(first: String) -> String {
print("first(\(first))")
return first
}
static func buildPartialBlock(accumulated: String, next: String) -> String {
print("accumulated(\(accumulated)) + next(\(next))")
return accumulated + next
}
}
@TraceBuilder
func word() -> String {
"a"
"b"
"c"
}
print(word())
Output:
first(a)
accumulated(a) + next(b)
accumulated(ab) + next(c)
abc
If a builder has both buildPartialBlock and buildBlock, the compiler uses buildPartialBlock.
The power comes from generics. The type of the accumulated value can grow with each line. Here a builder combines typed CSV columns into a parser whose result type is a tuple of all column types:
struct Column<Value> {
let name: String
let parse: (String) -> Value?
}
struct Columns<Values> {
let names: [String]
let parse: ([String]) -> Values?
}
@resultBuilder
enum RowBuilder {
static func buildPartialBlock<A>(first: Column<A>) -> Columns<A> {
Columns(names: [first.name]) { fields in
fields.count == 1 ? first.parse(fields[0]) : nil
}
}
static func buildPartialBlock<A, B>(accumulated: Columns<A>,
next: Column<B>) -> Columns<(A, B)> {
let n = accumulated.names.count
return Columns(names: accumulated.names + [next.name]) { fields in
guard fields.count == n + 1,
let a = accumulated.parse(Array(fields.prefix(n))),
let b = next.parse(fields[n]) else { return nil }
return (a, b)
}
}
}
func row<Values>(@RowBuilder _ content: () -> Columns<Values>) -> Columns<Values> {
content()
}
let text = Column<String>(name: "name") { $0 }
let int = Column<Int>(name: "age") { Int($0) }
let bool = Column<Bool>(name: "admin") { Bool($0) }
let person = row {
text
int
bool
}
print(person.names)
if let ((name, age), admin) = person.parse("Ada,36,true".split(separator: ",").map(String.init)) {
print(name, age + 1, admin)
}
print(person.parse(["Bob", "x", "false"]) as Any)
print(type(of: person))
Output:
["name", "age", "admin"]
Ada 37 true
nil
Columns<((String, Int), Bool)>
Two generic methods handle any number of columns, and age is statically an Int. The guard here is fine: it's inside a normal closure, not in a builder body.
The tuples nest as ((String, Int), Bool). To get a flat (String, Int, Bool) you'd add overloads of buildPartialBlock(accumulated:next:) for each accumulated tuple size. That's exactly what RegexBuilder does.
How RegexBuilder uses it
A Regex { ... } block is a result builder (RegexComponentBuilder) passed to Regex.init:
import RegexBuilder
let version = Regex {
"v"
Capture { OneOrMore(.digit) }
"."
Capture { OneOrMore(.digit) }
}
if let m = "swift v6.4".firstMatch(of: version) {
print(m.1, m.2)
}
print(type(of: version))
Output:
6 4
Regex<(Substring, Substring, Substring)>
RegexComponentBuilder uses buildPartialBlock, like RowBuilder above. Each Capture adds one element to the output type, and string literals and OneOrMore add nothing. The library has generated overloads for each combination of capture counts, which keeps the tuple flat. The full DSL is covered in Regex literals and RegexBuilder.
How SwiftUI uses it
SwiftUI's @ViewBuilder is a result builder whose result is a concrete generic type that describes the whole view tree. SwiftUI isn't available on Windows, but here is a small model of how it works. It uses parameter packs so that buildBlock accepts any number of views, each with its own type, and buildEither to encode an if/else in the type:
protocol View {
func render() -> String
}
struct Text: View {
let s: String
init(_ s: String) { self.s = s }
func render() -> String { "Text(\(s))" }
}
struct Spacer: View {
func render() -> String { "Spacer" }
}
struct TupleView<each V: View>: View {
let views: (repeat each V)
func render() -> String {
var parts: [String] = []
for v in repeat each views { parts.append(v.render()) }
return parts.joined(separator: ", ")
}
}
@resultBuilder
enum ViewBuilder {
static func buildBlock<each V: View>(_ views: repeat each V) -> TupleView<repeat each V> {
TupleView(views: (repeat each views))
}
static func buildEither<A: View, B: View>(first: A) -> Either<A, B> { .first(first) }
static func buildEither<A: View, B: View>(second: B) -> Either<A, B> { .second(second) }
}
enum Either<A: View, B: View>: View {
case first(A), second(B)
func render() -> String {
switch self {
case .first(let a): a.render()
case .second(let b): b.render()
}
}
}
struct VStack<Content: View>: View {
let content: Content
init(@ViewBuilder content: () -> Content) { self.content = content() }
func render() -> String { "VStack[\(content.render())]" }
}
let stack = VStack {
Text("Title")
Spacer()
Text("Footer")
}
print(stack.render())
print(type(of: stack))
func badge(loggedIn: Bool) -> some View {
VStack {
if loggedIn {
Text("Welcome back")
} else {
Spacer()
}
}
}
print(badge(loggedIn: true).render())
print(badge(loggedIn: false).render())
print(type(of: badge(loggedIn: true)))
Output:
VStack[Text(Title), Spacer, Text(Footer)]
VStack<TupleView<Pack{Text, Spacer, Text}>>
VStack[Text(Welcome back)]
VStack[Spacer]
VStack<TupleView<Pack{Either<TupleView<Pack{Text}>, TupleView<Pack{Spacer}>>}>>
The real SwiftUI types follow the same idea: TupleView<(Text, Spacer, Text)> for a block and _ConditionalContent<A, B> for if/else. Before Swift 5.9 ViewBuilder.buildBlock had overloads for 1 to 10 views, which is why older SwiftUI code couldn't put more than 10 views in one block. Since iOS 17 / macOS 14 it uses a parameter pack.
Because the type encodes both branches, badge can return some View even though the two branches create different views (see Opaque and existential types: some and any). The actual SwiftUI code looks like this (Apple platforms only, not run on Windows):
import SwiftUI
struct Badge: View {
let loggedIn: Bool
var body: some View { // @ViewBuilder is inferred from View.body
VStack {
if loggedIn {
Text("Welcome back")
} else {
Spacer()
}
}
}
}
Result builders vs. macros
Both let you write code that looks different from plain Swift, but they work at different levels. A result builder can't see your source code. It only gets the values of the lines, in order, and the compiler decides which build methods to call. Macros (Swift 5.9) get the syntax tree and can generate any code. Result builders need no extra package and no separate compile step, so prefer them when the problem is "combine a list of values into one value".
Tips
- Use an
enumwith no cases for the builder. It's never instantiated. - Pick one intermediate type (often an array) and convert with
buildExpressionandbuildFinalResult. Supportingif,switchandforis then one line per method. - Use generics and
buildPartialBlock(or parameter packs) when the result type should depend on the content, like RegexBuilder and SwiftUI. - Keep builder bodies small. Type checking a large builder closure with many overloads can be slow, and errors inside one are sometimes reported on the whole closure. Splitting the content into smaller functions or computed properties helps both.
- If you need
return,guardorwhile, write a normal function and call it from the builder body.
For the basics of closures see Closure basics.