Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 146 ยท Functions and Closures

Result Builders

Learn Swift result builders - @resultBuilder, buildBlock, buildOptional, buildEither and buildArray - and build a small HTML DSL step by step, with compiler errors and design advice.

Look at how SwiftUI code reads: a VStack contains a Text, then an Image, then maybe a Button if some condition holds. There are no commas, no append calls and no return. You just list things. That list-like syntax is not a special SwiftUI feature. It is a general Swift feature called result builders, and you can use it to create your own small languages inside Swift, called domain-specific languages (DSLs): for HTML, for configuration, for test descriptions, for menus.

This lesson explains what a result builder is, shows exactly how the compiler rewrites your code (so there is no magic left), and builds a working HTML generator in a few dozen lines. It assumes you know closures, functions and generics, and it pairs well with Property Wrappers, the other "custom attribute" feature.

The problem: lists of things written as code

Suppose you want to describe a shopping list so that the code looks like the list. With ordinary Swift you pass an array:

Swift The ordinary way: arrays and commas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This is fine for flat data. But as soon as you want conditions or loops inside the list, you must build the array by hand with var and append. A result builder lets the closure body itself be the list.

Your first result builder

A result builder is a type marked @resultBuilder that has at least one static method named buildBlock. When you apply it to a closure or function parameter, Swift takes each statement in the body that produces a value, passes all those values to buildBlock, and uses its result as the closure's result.

Swift A tiny TextBuilder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

There is no return, no commas and no array in the closure: just three string literals, one after another. The attribute @TextBuilder on the parameter says "the closure passed here is a builder closure." Swift transforms the closure body into this:

Swift
// What the compiler effectively writes for you (read-only illustration)
let list = shoppingList {
    let v0 = "milk"
    let v1 = "eggs"
    let v2 = "bread"
    return TextBuilder.buildBlock(v0, v1, v2)
}

That is the whole idea. Each statement's value is saved in a temporary, and buildBlock combines them. A type declared with @resultBuilder is typically an enum with no cases, because it is only a namespace for static methods and never instantiated.

You can also attach the builder to a function's body or to a property:

Swift Builder on a function and on a computed property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Placing @NumberBuilder on a function means its whole body is built by the builder, and there is no return.

Not every statement is a value

Inside a builder closure, only some statements are allowed to produce values. A plain expression like "milk" is turned into a value. Declarations (let x = 3) work normally and are not passed to the builder. But an expression whose type the builder cannot handle is a type error. The most common stumble is a call that returns Void, such as print(...):

Swift A Void statement in the block (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports cannot convert value of type '()' to expected argument type 'String': print returns (), and buildBlock accepts only strings. Remove the print, or add a buildExpression that can turn other types into the builder's component type, as shown later.

Control flow: if, if-else and for

A builder only supports if, switch and for if it provides the matching methods. Without them, you get a clear error:

Swift An if without buildOptional (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The message is closure containing control flow statement cannot be used with result builder 'TextBuilder'. To support these statements, a good builder uses a component type: one type that every piece is converted to, usually an array. Then each method is simple:

Method Called for Typical job
buildExpression(_:) each expression statement convert a value into the component type
buildBlock(_:...) the statements of a block combine components into one
buildOptional(_:) if without else nil when the condition is false
buildEither(first:) / buildEither(second:) if/else and switch pick the branch that ran
buildArray(_:) for ... in combine the components of every iteration
buildLimitedAvailability(_:) if #available hide platform-specific types
buildFinalResult(_:) the whole body convert the component type to the final type

Here is a builder that uses a [String] component type and supports all of the common statements:

Swift A complete list builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Walk through what each statement turned into:

  • "milk" and "eggs" went through buildExpression(_ line: String) and became ["milk"], ["eggs"].
  • if hasGuests produced an optional component. Because the condition is true, buildOptional received the inner block's lines; with false it would have received nil and returned an empty array.
  • if weekend { ... } else { ... } used buildEither(first:) for the first branch and buildEither(second:) for the second. Only the chosen branch runs, and it is wrapped accordingly.
  • for index in 1...3 produced one component per iteration, collected into an array of arrays and passed to buildArray.
  • extras is already [String], which the second buildExpression overload accepts.
  • Finally, buildFinalResult converted the [String] into the printable text that makeList returns.

That is why the closure looks like a plain list but can use variables, conditions and loops freely.

Result builders transform the syntax of the closure at compile time. They do not change the meaning of if or for themselves: the condition is evaluated and the loop runs as usual. The builder simply collects the values that each branch or iteration produces.

A small HTML DSL

Now for the classic demonstration: generating HTML. We need a node type, a few functions that create elements, and a builder that gathers child nodes.

Swift Building HTML with a result builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the page declaration at the bottom. It has the same shape as the HTML it produces: nesting by braces, an if to choose a paragraph and a for to produce list items. Each tag function takes a builder closure and wraps whatever the closure produces into an element. The builder's job is only to collect the children; the functions give them structure; and render turns the tree into text.

Because everything is ordinary Swift, the compiler checks your page for you. Nothing here is a string template that could contain an unclosed tag.

Why this is safer than string concatenation

With strings you would write "<ul>" + items.joined() + "</ul>" and forget a closing tag now and then. With the DSL, an unbalanced tag is impossible: each element is a function call with braces that the compiler matches. You could also escape text inside render, so that user input can never inject markup. Typed builders move whole categories of mistakes from run time to compile time.

Passing values with attributes

Real HTML needs attributes. Add them as ordinary function parameters, which keeps the builder unchanged:

Swift Attributes as normal parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The attributes dictionary is sorted before rendering, so the output is the same on every run. (Dictionary order in Swift varies from run to run, so always sort before printing.)

Design notes and pitfalls

  • Choose one component type. Converting everything to an array (or to your own enum) in buildExpression keeps the other methods trivial.
  • Only add the methods you need. A builder without buildArray simply rejects for loops with a clear message. That is a feature if your DSL should not allow loops.
  • Result builders are not a loop replacement. Use them when the code should read like the output and nest naturally. For plain data, an array literal or map is simpler.
  • Compile times and errors. Large builder closures make the type checker work hard. Error messages inside a builder can point at the whole closure rather than the bad line. Keep closures short, and extract pieces into helper functions.
  • Declarations are not components. let x = 3 in the body is just a local variable and is never passed to the builder, which is handy for computing values before you use them.
  • Design for readers. A DSL saves typing only if it is obvious. Name functions like the concepts in your domain and document what each one means.

Result builders are an advanced feature. SwiftUI and Swift's string-processing RegexBuilder both use them, and you will meet them often, but most application code only uses builders and rarely defines them. Define your own when you notice many nested constructor calls that you wish read like an outline.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the minimum a type needs to be a result builder?

    A type marked @resultBuilder with at least one static buildBlock method is enough. There is no protocol to adopt, and the other methods are optional.
  2. 2. A builder closure contains an if statement but the builder has no buildOptional or buildEither. What happens?

    Control flow support is opt-in. Without the matching build methods, the compiler rejects the statement with an error.
  3. 3. Which method handles the two branches of an if-else inside a builder closure?

    if-else and switch use buildEither(first:) for one branch and buildEither(second:) for the other; buildOptional is for an if without else.
  4. 4. What does a for-in loop inside a builder closure produce?

    Each iteration yields a component; the array of components is passed to buildArray, which combines them.
  5. 5. Why is let total = 3 allowed in a builder closure without affecting the result?

    Only expression statements become components. Declarations such as let and var stay ordinary local variables that later lines can use.

Summary

  • A result builder is a type marked @resultBuilder with a static buildBlock; attach it to a closure parameter, a function or a property to build a value from a list of statements.
  • The compiler rewrites each value-producing statement into a temporary and calls buildBlock with all of them.
  • Support for if, if-else and for is opt-in through buildOptional, buildEither(first:/second:) and buildArray.
  • buildExpression converts individual statements into your component type, and buildFinalResult converts the finished component to the result type.
  • Declarations (let, var) inside the closure stay ordinary local code.
  • Nesting plus ordinary Swift (conditions, loops, attributes as parameters) makes typed DSLs for HTML, configuration and UI.
  • Keep builders small, document them, and use them where the code should read like the structure it produces.

Next: Collections Overview