Hub/swift

Swift Result Builder for HTML

A simple result builder for generating HTML strings.

result-builderdslhtml
D
Demo User
|Feb 22, 2026|7 views6 imports
View Raw
swift
@resultBuilder
struct HTMLBuilder {
    static func buildBlock(_ components: String...) -> String {
        components.joined(separator: "\n")
    }

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

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

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

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

let page = html {
    "<head><title>Hello</title></head>"
    "<body>"
    "<h1>Welcome</h1>"
    "</body>"
}