0
0
Swiftprogramming~5 mins

Custom result builder declaration in Swift

Choose your learning style9 modes available
Introduction

Custom result builders help you create a special way to build complex values step-by-step using simple code blocks.

When you want to write clean code that builds complex data like HTML or UI layouts.
When you want to let others write simple code that creates complicated results behind the scenes.
When you want to combine multiple pieces of data or views in a clear and readable way.
When you want to create your own mini-language inside Swift for building things.
When you want to avoid writing repetitive code for assembling parts into a whole.
Syntax
Swift
@resultBuilder
struct BuilderName {
    static func buildBlock(_ components: ComponentType...) -> ResultType {
        // Combine components into one result
    }

    // Optional: other static build methods like buildIf, buildEither, buildArray
}

The @resultBuilder attribute marks a type as a result builder.

Inside, you define static methods to tell Swift how to combine parts.

Examples
This builder joins multiple strings with commas.
Swift
@resultBuilder
struct StringBuilder {
    static func buildBlock(_ components: String...) -> String {
        components.joined(separator: ", ")
    }
}
This builder adds up all integer parts.
Swift
@resultBuilder
struct IntSumBuilder {
    static func buildBlock(_ components: Int...) -> Int {
        components.reduce(0, +)
    }
}
Sample Program

This program defines a custom result builder called StringBuilder that joins strings with spaces. It also supports optional parts with buildIf. The makeSentence function uses this builder to create a sentence from code blocks.

Swift
import Foundation

@resultBuilder
struct StringBuilder {
    static func buildBlock(_ components: String...) -> String {
        components.joined(separator: " ")
    }

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

func makeSentence(@StringBuilder content: () -> String) -> String {
    content()
}

let sentence = makeSentence {
    "Hello"
    if true {
        "world!"
    }
}

print(sentence)
OutputSuccess
Important Notes

Result builders let you write code that looks like normal blocks but creates complex results.

You can add methods like buildIf, buildEither, and buildArray to handle conditions and loops.

Use @resultBuilder before your builder struct to tell Swift it is a builder.

Summary

Custom result builders let you create special ways to combine code parts into one result.

They make your code cleaner and easier to read when building complex data.

Define static methods inside a @resultBuilder struct to control how parts combine.