SwiftUI’s @ViewBuilder is a powerful attribute that enables us to create custom view components with a declarative and flexible syntax — just like native SwiftUI containers (VStack, HStack, etc.).
In this article, we’ll explore:
- What is
@ViewBuilderand why it matters - How to create a custom view that accepts a
@ViewBuilderclosure - What happens under the hood when SwiftUI processes a
@ViewBuilderclosure - Practical use cases and benefits
What is @ViewBuilder?
@ViewBuilder is a special attribute that lets you write multiple views inside a closure, and SwiftUI will automatically combine them into a single view result. It acts like a function builder specialized for views.
For example, you can write:
VStack {
Text("Hello")
Text("World")
}and SwiftUI uses @ViewBuilder to convert these two views into a TupleView under the hood.
Creating a Custom View with @ViewBuilder
Say you want to create a reusable card component that can display any content inside:
struct CardView<Content: View>: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
VStack {
content()
}
.padding()
.background(Color.white)
.cornerRadius(10)
.shadow(radius: 5)
}
}You can use it like this:
CardView {
Text("Title")
.font(.headline)
Text("This is a card description.")
.font(.subheadline)
}The @ViewBuilder allows you to pass multiple views inside the closure without manually wrapping them in containers like VStack.
What Happens Under the Hood?
When you use @ViewBuilder, SwiftUI compiles the closure into a combined view type, often a TupleView when you have multiple views.
For example:
HStack {
Image(systemName: "star")
Text("Hello")
Spacer()
}is transformed roughly into:
TupleView<(
Image,
Text,
Spacer
)>SwiftUI also supports conditionals inside @ViewBuilder closures, using buildIf and buildEither methods behind the scenes.
Conclusion
Mastering @ViewBuilder unlocks a new level of custom component design in SwiftUI, making your code more expressive and easier to maintain.