Introduction
Result builders help SwiftUI create views by combining small pieces of code into a bigger layout easily.
Result builders help SwiftUI create views by combining small pieces of code into a bigger layout easily.
struct ContentView: View { var body: some View { VStack { Text("Hello") Text("World") } } }
The curly braces after VStack use a result builder to combine views.
SwiftUI uses @ViewBuilder behind the scenes to build the view list.
VStack {
Text("Line 1")
Text("Line 2")
}HStack {
Text("Left")
Text("Right")
}Group {
Text("First")
Text("Second")
}This program shows two text lines stacked vertically using SwiftUI's result builder.
import SwiftUI struct ContentView: View { var body: some View { VStack { Text("Hello") Text("SwiftUI") } } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
Result builders let you write multiple views inside braces without commas.
You can create your own result builders for custom DSLs (domain-specific languages).
SwiftUI uses result builders to combine multiple views inside closures.
This makes UI code clean and easy to read.
Common result builder in SwiftUI is @ViewBuilder.
@ViewBuilder in SwiftUI?@ViewBuilder@ViewBuilder is a result builder that allows combining multiple views inside a closure.@ViewBuilder combines views [OK]@ViewBuilder builds multiple views together [OK]@ViewBuilder with animation or data tasks@ViewBuilder in SwiftUI?@ViewBuilder@ViewBuilder is placed before the function declaration.@ViewBuilder before the function name. Others misuse placement.@ViewBuilder goes before func [OK]@ViewBuilder right before the function keyword [OK]@ViewBuilder after the function name or return type@ViewBuilder when combining views@ViewBuilder?
struct ContentView: View {
@ViewBuilder
func buildContent() -> some View {
Text("Hello")
Text("World")
}
var body: some View {
buildContent()
}
}@ViewBuilder behavior@ViewBuilder allows multiple views to be returned as a combined view, typically stacked vertically.Text views "Hello" and "World" will be combined and shown one after another vertically.@ViewBuilder stack vertically by default [OK]@ViewBuilder:
struct MyView: View {
@ViewBuilder
func content() -> some View {
if Bool.random() {
Text("Yes")
} else {
Text("No")
}
Text("Always")
}
var body: some View {
content()
}
}@ViewBuilder rules with conditionals@ViewBuilder, all branches must return views, but multiple views after conditionals need grouping.Bool.random() causes error@ViewBuilder functions@ViewBuilder function to correctly return multiple views including a conditional view?
@ViewBuilder
func build() -> some View {
Text("Start")
if showExtra {
Text("Extra")
}
Text("End")
}
Assuming showExtra is a Boolean variable.VStack to form a single combined view.VStack { ... } groups them and allows conditional views without errors.VStack to group them -> Option BVStack [OK]VStack to group multiple views with conditionals [OK]Pass the test and this pattern moves unknown