← Back to Swift Course | Chapter 12: Generics & Advanced Types | Lesson 7 of 7

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

markup
@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)

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

markup
@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)
Common Mistakes
  1. Assuming result builders are only for SwiftUI; they are a general Swift language feature usable in any plain command-line code.
  2. Forgetting a result builder type needs at least a static buildBlock method to combine multiple components into one.
  3. Applying @resultBuilder to a function's parameter incorrectly; it should annotate the closure PARAMETER'S type, e.g. @MyBuilder () -> String.
Chapter Summary
  • @resultBuilder marks a type that defines how to combine multiple expressions in a special block into one value.
  • A minimal result builder implements a static buildBlock method.
  • The builder is applied to a closure parameter with @BuilderName before 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.