Result Builders

Builder methods: buildBlock, buildPartialBlock(first:)/(accumulated:next:), buildOptional, buildEither, buildArray, buildExpression, buildFinalResult, buildLimitedAvailability.

Powers SwiftUI (@ViewBuilder), RegexBuilder, Swift Testing traits-style DSLs, and HTML DSLs (Plot, Elementary).

@resultBuilder
struct HTMLBuilder {
    static func buildBlock(_ components: String...) -> String { components.joined() }
    static func buildOptional(_ component: String?) -> String { component ?? "" }
    static func buildEither(first component: String) -> String { component }
    static func buildEither(second component: String) -> String { component }
    static func buildArray(_ components: [String]) -> String { components.joined() }
    static func buildExpression(_ expression: String) -> String { expression }
}

func html(@HTMLBuilder _ content: () -> String) -> String { "<html>\(content())</html>" }
func ul(@HTMLBuilder _ content: () -> String) -> String { "<ul>\(content())</ul>" }
func li(_ text: String) -> String { "<li>\(text)</li>" }

let isLoggedIn = true
let fruits = ["Apple", "Mango"]
let page = html {
    "<h1>Welcome</h1>"
    if isLoggedIn {
        "<p>Hello again!</p>"
    } else {
        "<p>Please log in</p>"
    }
    ul {
        for fruit in fruits {
            li(fruit)
        }
    }
}
print(page)