skip to content

How do you build a reusable SwiftUI container view, such as a card, that takes caller-supplied content through a @ViewBuilder parameter?

level: juniorimportance: must knowfreq 60%

answer

  1. generic over Content: View
  2. builder attribute on the init parameter
  3. call the closure, store the result
  4. constrained extension for an optional slot

basics

~10 s

Make the container generic over Content: View, mark its initializer's closure parameter @ViewBuilder, call the closure and store the result, then place that content inside the container's own layout and decoration in body.

solid answer

~40 s

I declare `struct Card<Content: View>: View`, give it an initializer that takes `@ViewBuilder content: () -> Content`, call the closure once and store the resulting `content`, and place it in `body` inside the card's padding, background and stack. The builder attribute lets callers write several views and `if` statements in the closure, and the generic parameter keeps their concrete view type instead of erasing it. For more than one slot I add a second generic, such as `Header`, and offer a constrained extension `where Header == EmptyView` so the header is optional. With Xcode 27 the iOS 27 SDK spells this builder `ContentBuilder`, a type alias of `ViewBuilder`, and Apple's documentation recommends that name for closures in new code; existing `@ViewBuilder` code compiles unchanged.

code

swift · 29 lines
swift
import SwiftUI

struct Card<Header: View, Content: View>: View {
    private let header: Header
    private let content: Content

    init(@ViewBuilder header: () -> Header,
         @ViewBuilder content: () -> Content) {
        self.header = header()
        self.content = content()
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            header
                .font(.headline)
            content
        }
        .padding(16)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(.background, in: .rect(cornerRadius: 12))
    }
}

extension Card where Header == EmptyView {
    init(@ViewBuilder content: () -> Content) {
        self.init(header: { EmptyView() }, content: content)
    }
}

go deeper

for a junior

Recall the recipe: a generic Content: View, an init taking a @ViewBuilder closure, call it and store the result, place it in body.

for a middle

Explain why the generic beats AnyView, how multiple slots and multiple trailing closures work, and why an optional slot needs a constrained extension rather than a default argument.

for a senior

Design containers so layout and decoration stay inside them and callers own only content, and know that ContentBuilder in the iOS 27 SDK is an alias, not a migration.

for a principal

Decide which components become containers versus styles or modifiers, and keep their slot APIs small and stable because twenty screens will depend on them.

## The problem a container view solves A design system rarely needs only modifiers. A **card** in a fintech app has its own structure: a header line, a body, padding, a background and a corner radius. Twenty screens put different things inside it: a balance, a list of pending transfers, a chart. A **container view** is a view whose job is to arrange and decorate content that its caller supplies, the same way `VStack`, `GroupBox` or `Section` take a closure of views. ## The building blocks 1. **A generic parameter.** `struct Card<Content: View>: View` lets the card hold any view type the caller builds, while keeping that concrete type. Erasing it with `AnyView` would also compile, but gives SwiftUI less type information to work with; the generic is the idiomatic form. 2. **A builder attribute on the closure parameter.** `init(@ViewBuilder content: () -> Content)` turns the caller's closure into a result builder. Callers can then list several views, use `if`/`else` and `switch`, and the builder combines them into one `Content` value. 3. **Calling the closure in the initializer.** `self.content = content()` stores the built view value. Apple's own container examples follow this pattern, and the closure does not need to be `@escaping` because it is used immediately. 4. **Placing the content in `body`.** The container decides layout: putting `content` inside a `VStack` lays out each child the caller listed vertically; inside an `HStack`, horizontally. ## Several slots and optional slots Real components often have more than one slot. Each slot gets its own generic parameter and its own builder closure: ```swift struct Card<Header: View, Content: View>: View { init(@ViewBuilder header: () -> Header, @ViewBuilder content: () -> Content) { /* store both */ } } ``` Callers then use multiple trailing closures: `Card { Text("Savings") } content: { ... }`. To make the header optional, add a **constrained extension** with a second initializer: ```swift extension Card where Header == EmptyView { init(@ViewBuilder content: () -> Content) { self.init(header: { EmptyView() }, content: content) } } ``` A default argument such as `header: () -> Header = { EmptyView() }` does not type-check, because `Header` is a generic parameter chosen by the caller, not `EmptyView`. The constrained extension is the standard workaround. ## ViewBuilder and ContentBuilder in the iOS 27 SDK | Spelling | What it is | Where you see it | |---|---|---| | `@ViewBuilder` | The result builder struct SwiftUI has shipped since iOS 13 | Existing code, older documentation | | `@ContentBuilder` | A type alias of `ViewBuilder` | Signatures in the iOS 27 SDK | Apple's documentation says that when you build with Xcode 27 or later, `ViewBuilder` closures construct type-agnostic content, and recommends marking such closures with `ContentBuilder` to say where your code expects that. Because one is an alias of the other, a container written with `@ViewBuilder` keeps compiling; the choice is a matter of spelling for new code. ## Design choices that matter - **Keep layout inside the container.** The card should own padding, background and spacing so callers cannot drift; callers own only what goes inside. - **Expose configuration as parameters, not more modifiers.** A `style` or `isHighlighted` parameter is clearer than asking callers to remember a modifier. - **Avoid stringly or `AnyView` slots.** A `title: String` parameter is fine for text, but anything richer belongs in a builder slot so callers can pass any view. - **Prefer a builder property for small containers.** `@ViewBuilder var content: Content` on a stored property gives the memberwise initializer a builder closure for free. ## Common mistakes 1. **Forgetting the builder attribute.** Without `@ViewBuilder`, the closure must return a single view, so callers cannot list two rows without wrapping them in a stack themselves, and both branches of an `if` must produce the same type. 2. **Erasing to `AnyView` by reflex.** It compiles, but it discards the type information the generic keeps for free, and it is not needed just to accept "any view". 3. **Letting callers style the shell.** If callers add `.padding()` or `.background()` to the card from outside, the card's look varies by screen; put those inside the container and expose a parameter for the variants you actually support. 4. **Doing work in the initializer.** The initializer can run every time the parent's body is re-evaluated, so it should only store the built content, never fetch data or start tasks. A reviewer reading a pull request that adds a container should be able to answer three questions from its signature alone: which slots exist, which are optional, and which visual variants are allowed.

  • Why store the built content rather than the closure itself?
    Calling the closure in the initializer and storing the view value matches Apple's own container examples, avoids making the parameter `@escaping`, and keeps the container a plain value of known type. Storing the closure works too, but it defers building the content to `body` and captures whatever the closure captured, which is rarely what a simple container needs.
  • What happens if a caller passes two views but the container places content directly in its body without a stack?
    Both views are still there, combined into one builder value. Their arrangement then depends on the container that ends up holding them: placed at the top of `body` they behave like the children of whatever stack or list the card itself sits in. A container that wants a fixed arrangement should wrap `content` in its own stack.

  • A container must store its content as AnyView to accept different views.
  • A container must mark its builder closure @escaping to accept content.
  • A builder closure keeps only its last view expression.
  • An optional slot is done with a default closure returning EmptyView.
  • ContentBuilder in the iOS 27 SDK is a separate builder that replaces ViewBuilder.

Assumes Xcode 27 with the iOS 27 SDK, where ContentBuilder is a type alias of ViewBuilder; @ViewBuilder containers compile unchanged.