Result Builder Basics in Swift

From the Swift cheat sheet · Result Builders · verified Jul 2026

Result Builder Basics

Creating domain-specific languages

swift
// Basic result builder
@resultBuilder
struct ArrayBuilder {
    static func buildBlock<T>(_ components: T...) -> [T] {
        return components
    }
}

@ArrayBuilder
func buildNumbers() -> [Int] {
    1
    2
    3
    4
    5
}

// HTML DSL example
@resultBuilder
struct HTMLBuilder {
    static func buildBlock(_ components: String...) -> String {
        components.joined(separator: "\n")
    }

    static func buildOptional(_ component: String?) -> String {
        component ?? ""
    }

    static func buildEither(first: String) -> String {
        first
    }

    static func buildEither(second: String) -> String {
        second
    }
}

func div(@HTMLBuilder content: () -> String) -> String {
    "<div>\n\(content())\n</div>"
}

func p(_ text: String) -> String {
    "<p>\(text)</p>"
}
💡 Result builders enable SwiftUI-style declarative syntax
⚡ buildBlock is the core method that combines components
📌 buildIf and buildEither handle conditionals
🟢 Use @resultBuilder to create intuitive DSLs
Back to the full Swift cheat sheet