Contents

ContentBuilder

A custom parameter attribute that constructs views and other content types from closures.

Declaration

typealias ContentBuilder = ViewBuilder

Discussion

You apply ContentBuilder, a type alias for ViewBuilder, as a parameter attribute to closure parameters, computed properties, or protocol requirements. Then, SwiftUI builds content from multiple statements in the closures you provide. For example, the following contextMenu function accepts a closure that produces one or more views from the content builder.

func contextMenu<MenuItems: View>(
    @ContentBuilder menuItems: () -> MenuItems
) -> some View

You can use multiple-statement closures to provide several subviews, as the following example shows:

myView.contextMenu {
    Text("Cut")
    Text("Copy")
    Text("Paste")
    if isSymbol {
        Text("Jump to Definition")
    }
}

You can also use ContentBuilder with other SwiftUI-style result builders. For example, the following computed property iterates over cases in an enumeration to produce toolbar items.

@ContentBuilder
var editingToolbarItems: some ToolbarContent {
    ForEach(EditingOptions.toolbarItems, id: \.self) { editingOption in
        ToolbarItem {
            Button(editingOption.title) {
                editingOption.action()
            }
        }
    }
}

SwiftUI constructs type-agnostic content from closures that you mark with ContentBuilder, which serves as the unified replacement for type-specific builders like ToolbarContentBuilder and CommandsBuilder.

In its build functions, ContentBuilder doesn’t enforce protocol conformance. Instead, it maintains type safety through conditional conformances on the content types it produces. For example, TupleContent conditionally conforms to content types based on which types the content items it contains conform to. This allows a single, shared set of initializers on Group, ForEach, and Section to serve all content types, rather than a separate overloaded initializer per builder.

See Also

Creating a view