Swift Result Builders
Have you wondered how SwiftUI lets you list views one after another inside VStack { … } without commas, arrays or return? The magic is a language feature called result builders. A result builder collects the separate expressions of a closure body and combines them into one value. You rarely write your own, but understanding them makes SwiftUI far less mysterious.
The idea
Normally a closure that lists several expressions only returns the last one (or nothing). Inside a closure marked with a result builder, every expression statement is collected:
// What you write in SwiftUI…
VStack {
Text("Title")
Text("Subtitle")
Image(systemName: "star")
}
// …is turned by the @ViewBuilder result builder into roughly:
VStack {
ViewBuilder.buildBlock(Text("Title"), Text("Subtitle"), Image(systemName: "star"))
}Building a tiny result builder
A result builder is a type marked @resultBuilder with static build… methods. The only required one is buildBlock. Let's make a builder that collects lines of text:
@resultBuilder
struct LinesBuilder {
static func buildBlock(_ lines: String...) -> [String] {
lines
}
}
@LinesBuilder
func shoppingList() -> [String] {
"Milk"
"Eggs"
"Coffee"
}
let items = shoppingList()
print(items)
print("\(items.count) items")["Milk", "Eggs", "Coffee"]
3 items
Each string on its own line becomes one argument to buildBlock. No commas, no array brackets, no return.
Supporting if and for
To allow if, if/else and for inside the builder body, add more static methods. Using arrays as the building block makes this simple:
| Method | Enables |
|---|---|
buildBlock(_:) |
listing statements (required) |
buildExpression(_:) |
converting each single expression into the component type |
buildOptional(_:) |
if without else |
buildEither(first:) / buildEither(second:) |
if/else and switch |
buildArray(_:) |
for … in loops |
buildFinalResult(_:) |
converting the final component into the returned type |
@resultBuilder
struct HTMLBuilder {
static func buildExpression(_ text: String) -> [String] { [text] }
static func buildBlock(_ parts: [String]...) -> [String] { parts.flatMap { $0 } }
static func buildOptional(_ part: [String]?) -> [String] { part ?? [] }
static func buildEither(first part: [String]) -> [String] { part }
static func buildEither(second part: [String]) -> [String] { part }
static func buildArray(_ parts: [[String]]) -> [String] { parts.flatMap { $0 } }
static func buildFinalResult(_ parts: [String]) -> String { parts.joined(separator: "\n") }
}
@HTMLBuilder
func page(user: String?, tags: [String]) -> String {
"<h1>Blog</h1>"
if let user {
"<p>Welcome back, \(user)!</p>"
} else {
"<p>Please sign in.</p>"
}
for tag in tags {
"<span>#\(tag)</span>"
}
}
print(page(user: "Ada", tags: ["swift", "ios"]))
print("---")
print(page(user: nil, tags: []))<h1>Blog</h1>
<p>Welcome back, Ada!</p>
<span>#swift</span>
<span>#ios</span>
---
<h1>Blog</h1>
<p>Please sign in.</p>
The body of page reads like a template, yet it is fully type-checked Swift code.
Using a builder as a closure parameter
Builders shine when they are applied to a closure parameter — that is exactly how VStack(content:) is declared in SwiftUI. Mark the parameter with the builder attribute:
@resultBuilder
struct ListBuilder {
static func buildBlock(_ items: String...) -> [String] { items }
}
struct Menu {
let title: String
let items: [String]
init(_ title: String, @ListBuilder items: () -> [String]) {
self.title = title
self.items = items()
}
func show() {
print("== \(title) ==")
for (i, item) in items.enumerated() {
print("\(i + 1). \(item)")
}
}
}
let breakfast = Menu("Breakfast") {
"Pancakes"
"Fruit salad"
"Orange juice"
}
breakfast.show()== Breakfast ==
1. Pancakes
2. Fruit salad
3. Orange juice
Compare with SwiftUI: struct VStack<Content: View> { init(@ViewBuilder content: () -> Content) }. Same pattern!
Where you'll see result builders
| Builder | Framework | Used in |
|---|---|---|
@ViewBuilder |
SwiftUI | body, VStack { }, HStack { }, … |
@SceneBuilder |
SwiftUI | App.body |
@ToolbarContentBuilder |
SwiftUI | .toolbar { } |
@RegexComponentBuilder |
Swift Regex | Regex { … } DSL |
Note: Inside a builder body you can't use arbitrary statements like
returnor awhileloop — only the constructs the builder supports. That's why SwiftUI usesForEachinstead ofwhile.
Tip: A view's
bodyproperty is implicitly a@ViewBuilder, which is why you can put anifin it to show different views.
Test yourself
Which static method must every result builder provide?
- buildArray
- buildBlock
- buildOptional
- buildFinalResult
Which builder method makes if/else work inside a builder body?
- buildOptional
- buildArray
- buildEither(first:) and buildEither(second:)
- buildExpression
What SwiftUI feature is built on result builders?
- @State
- Listing child views inside VStack { } without commas
- NavigationStack paths
- Property observers