The Power of Function Builder: Swift VS SwiftUI

Eniela P. Vela
4 min readMay 18
Picture by Arnold Francisca in Unsplash.

Function builders are an incredibly powerful feature that enhance the expressiveness and readability of code in both Swift and SwiftUI. Introduced in Swift 5.4, function builders allow developers to create DSLs (Domain-Specific Languages) and simplify the creation of complex structures using a more concise syntax. In this comprehensive blog post, we will explore the usage and differences of function builders in plain Swift and SwiftUI, providing you with detailed examples and insights. By understanding these differences, you’ll be able to make informed decisions on when and how to leverage each approach in your iOS development projects.

What is a Function Builder?

Function builders, at their core, enable the composition of multiple function calls into a single construct. They are designed to make code more readable and maintainable by providing a declarative and intuitive syntax for building complex data structures. By leveraging custom attributes and result builders, function builders transform a series of function calls into a well-defined structure.

Function Builders in Plain Swift:

In plain Swift, you can use function builders with custom attributes to define your own DSLs. Let’s start by exploring how to define a function builder in plain Swift using the @resultBuilder attribute. Consider the following example:

@resultBuilder
struct MyBuilder {
static func buildBlock(_ components: Int...) -> [Int] {
return components
}
}

@MyBuilder
func buildIntArray() -> [Int] {
1
2
3
}

let result = buildIntArray() // [1, 2, 3]

We initially define a custom function builder called MyBuilder using the @resultBuilder attribute. The buildBlock function within the builder specifies how the individual function calls are combined into a final result. We then use the buildIntArray function with the @MyBuilder attribute to create an array of integers.

Function Builders in SwiftUI:

SwiftUI takes function builders to the next level by seamlessly integrating them into the framework itself. SwiftUI’s ViewBuilder is a built-in function builder that simplifies the creation of complex view hierarchies…

Eniela P. Vela

iOS Developer | Tech Creator | Technical Writer | Software Developer https://ynnenu.medium.com/membership