The ViewBuilder Attribute
Compose complex views
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…