What is a result builder?
The idea
A result builder (@resultBuilder) is a type with static methods by which the compiler rewrites a closure body: every expression line becomes a call to buildExpression, their list becomes buildBlock, an if without else becomes buildOptional, if/else becomes buildEither(first:/second:), for becomes buildArray, if #available becomes buildLimitedAvailability. The result is a declarative DSL with ordinary Swift code inside. @ViewBuilder, RegexBuilder and @CommandsBuilder are built on it.
@resultBuilder
enum ListBuilder {
static func buildExpression(_ s: String) -> [String] { [s] }
static func buildBlock(_ parts: [String]...) -> [String] {
parts.flatMap { $0 }
}
static func buildOptional(_ part: [String]?) -> [String] { part ?? [] }
static func buildEither(first: [String]) -> [String] { first }
static func buildEither(second: [String]) -> [String] { second }
static func buildArray(_ parts: [[String]]) -> [String] {
parts.flatMap { $0 }
}
}
func menu(@ListBuilder _ content: () -> [String]) -> [String] { content() }
let isAdmin = true
let items = menu {
"Home"
if isAdmin { "Admin" } // buildOptional
for i in 1...2 { "Item \(i)" } // buildArray
}
print(items) // ["Home", "Admin", "Item 1", "Item 2"]
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep