Custom result builders help you create a special way to build complex values step-by-step using simple code blocks.
Custom result builder declaration in 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.
@resultBuilder struct StringBuilder { static func buildBlock(_ components: String...) -> String { components.joined(separator: ", ") } }
@resultBuilder struct IntSumBuilder { static func buildBlock(_ components: Int...) -> Int { components.reduce(0, +) } }
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.
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)
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.
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.