What is a result builder (@ViewBuilder, @CommandsBuilder)?

1.5.8 · L3 · Interview

Mental model. A result builder is a compiler that turns a list of statements into one value — a tiny DSL you write in plain Swift.

A type with static methods like buildBlock, buildOptional, buildEither, and buildExpression. The compiler rewrites a block of statements into calls to those methods, producing one value.

SwiftUI’s body is a @ViewBuilder. An if/else becomes _ConditionalContent, which is exactly why the branches do not need to be the same type — and why adding an if can change view identity and cause a re-render.

Common traps

  • “A result builder is a macro.” It is a compiler feature with a protocol-like interface, not a macro. (Result builders predate Swift macros.)
  • Expecting loops to be free. buildArray wraps each element; identity and diffing behave differently from a hand-written ForEach.

They might follow up with

  • Why does if change identity in SwiftUI? Because _ConditionalContent is a different view type in a different position in the tree.
  • What are the limits? A builder block has a fixed maximum arity for buildBlock overloads, and control flow is limited to what the builder implements.

Related questions

  • 1.10.3 Macros vs property wrappers vs result builders — one sentence each.
  • 1.4.2 some View vs any View — what is the difference, and why does SwiftUI use some?

← What is @autoclosure? When is it justified?