0
0
Swiftprogramming~7 mins

@resultBuilder attribute in Swift

Choose your learning style9 modes available
Introduction

The @resultBuilder attribute helps you create special functions that build complex values step-by-step using simple code blocks. It makes your code easier to read and write by letting you write multiple statements that combine into one result.

When you want to create a custom way to build user interface layouts by writing simple code blocks.
When you want to combine multiple pieces of data or views into one result without writing complex loops or conditionals.
When you want to make your code look clean and readable while building complex structures like HTML, JSON, or UI elements.
When you want to let others write simple code blocks that your function will transform into a final value.
Syntax
Swift
@resultBuilder struct BuilderName {
    static func buildBlock(_ components: ComponentType...) -> ResultType {
        // Combine components into one result
    }
    // Optional: other build methods like buildIf, buildEither, buildArray
}

The @resultBuilder attribute is placed before a struct or enum that defines how to combine code blocks.

You define static methods like buildBlock to tell Swift how to combine parts.

Examples
This example creates a StringBuilder that joins multiple strings with spaces.
Swift
@resultBuilder
struct StringBuilder {
    static func buildBlock(_ components: String...) -> String {
        components.joined(separator: " ")
    }
}
This shows how to use the @resultBuilder in a function to combine strings written inside a closure.
Swift
func makeString(@StringBuilder content: () -> String) -> String {
    content()
}

let result = makeString {
    "Hello"
    "world!"
}
Sample Program

This program defines an @resultBuilder called ArrayBuilder that combines arrays of integers. The makeArray function uses it to build one array from multiple parts, including an if condition.

Swift
import Foundation

@resultBuilder
struct ArrayBuilder {
    static func buildBlock<T>(_ components: [T]...) -> [T] {
        components.flatMap { $0 }
    }
    static func buildIf<T>(_ component: [T]?) -> [T] {
        component ?? []
    }
}

func makeArray(@ArrayBuilder content: () -> [Int]) -> [Int] {
    content()
}

let numbers = makeArray {
    [1, 2]
    if true {
        [3, 4]
    }
    [5]
}

print(numbers)
OutputSuccess
Important Notes

You can add special methods like buildIf to handle optional code blocks (like if statements).

Result builders let you write code that looks like normal statements but actually builds a value behind the scenes.

They are very useful for creating domain-specific languages (DSLs) inside Swift.

Summary

@resultBuilder helps combine multiple code lines into one result.

It makes code cleaner and easier to write for building complex data or UI.

You define how to combine parts by writing static methods inside a builder type.