Result Builders
A result builder is special magic that lets you write a list of steps in a natural-looking block, and Swift secretly combines them all into one final value for you.
Defining a Minimal Result Builder
A @resultBuilder type implements buildBlock, which Swift calls automatically to combine every statement written inside an annotated closure into one final value.
Example: Defining a Minimal Result Builder
@resultBuilder
struct StringBuilder {
static func buildBlock(_ parts: String...) -> String {
return parts.joined(separator: ", ")
}
}
func makeList(@StringBuilder content: () -> String) -> String {
return content()
}
let result = makeList {
"apple"
"banana"
"cherry"
}
print(result)
Login to try C/C++/Java/PHP code in the editor
Result Builders with Conditional Logic
A more complete result builder also implements buildEither or buildOptional to support if statements inside the builder block.
Example: Result Builders with Conditional Logic
@resultBuilder
struct StringBuilder {
static func buildBlock(_ parts: String...) -> String {
return parts.joined(separator: ", ")
}
static func buildOptional(_ part: String?) -> String {
return part ?? ""
}
}
func makeList(includeExtra: Bool, @StringBuilder content: () -> String) -> String {
return content()
}
let result = makeList(includeExtra: true) {
"apple"
"banana"
}
print(result)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Assuming result builders are only for SwiftUI; they are a general Swift language feature usable in any plain command-line code.
- Forgetting a result builder type needs at least a static
buildBlockmethod to combine multiple components into one. - Applying
@resultBuilderto a function's parameter incorrectly; it should annotate the closure PARAMETER'S type, e.g.@MyBuilder () -> String.
Chapter Summary
@resultBuildermarks a type that defines how to combine multiple expressions in a special block into one value.- A minimal result builder implements a static
buildBlockmethod. - The builder is applied to a closure parameter with
@BuilderNamebefore its type. - Result builders power SwiftUI's view syntax, but are a general-purpose Swift feature.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: