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.
@resultBuilder attribute in 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.
StringBuilder that joins multiple strings with spaces.@resultBuilder struct StringBuilder { static func buildBlock(_ components: String...) -> String { components.joined(separator: " ") } }
@resultBuilder in a function to combine strings written inside a closure.func makeString(@StringBuilder content: () -> String) -> String { content() } let result = makeString { "Hello" "world!" }
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.
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)
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.
@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.