What is a result builder (@ViewBuilder, @CommandsBuilder)?
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.
buildArraywraps each element; identity and diffing behave differently from a hand-writtenForEach.
They might follow up with
- Why does
ifchange identity in SwiftUI? Because_ConditionalContentis a different view type in a different position in the tree. - What are the limits? A builder block has a fixed maximum arity for
buildBlockoverloads, and control flow is limited to what the builder implements.