The ViewBuilder Attribute

Compose complex views

Steven Curtis
3 min readAug 31

--

Photo by Drew Saurus on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 14.2, and Swift 5.7.2

Prerequisites:

You need to be able to code in Swift, perhaps using

Playgrounds and be able to use SwiftUI

You might need to know something about result builders in order to happily follow this article

Terminology

@resultBuilder: An attribute that transforms a sequence of statements into a single combined value

View: In SwiftUI a view is a protocol that defines a piece of user interface and is a building block for creating UI in SwiftUI

ViewBuilder: A SwiftUI attribute that enables the dynamic composition of views based on conditions without explicitly returning them

Why?

Simplified syntax

Put simply you want to use @ViewBuilder to create child views for a SwiftUI view without having to use return.

You will notice that something like this View avoids ugly use of return or commas in between the Text views:

struct MyView: View {
var body: some View {
VStack {
Text("Hello")
Text("World")
}
}
}

That is, without @ViewBuilder you’d need to wrap the views in a container view and use the return keyword with a comma between each item.

Conditional views

@ViewBuilder constructs views from closures. With @ViewBuilder you can handle conditional views to display views based on conditions. Apple’s documentation has the following example:

func contextMenu<MenuItems: View>(
@ViewBuilder menuItems: () -> MenuItems
) -> some View
myView.contextMenu {
Text("Cut")
Text("Copy")
Text("Paste")
if isSymbol {
Text("Jump to Definition")
}
}

which is a nice use of SwiftUI DSL (Domain Specific Language). We can also extend this idea to build adaptive user interfaces using these language features.

--

--