skip to content

On iOS 18 and later, how do SwiftUI's ForEach(subviews:) and Group(subviews:) let a custom container style each child, and where do they fall short?

level: seniorimportance: should knowfreq 30%

answer

  1. resolved pieces, not declared lines
  2. Subview is a View and Identifiable
  3. a collection you can count and slice
  4. per-child flags that stop at the container
  5. proxies resolve in the container's environment

basics

~20 s

Since iOS 18, ForEach(subviews:) and Group(subviews:) give a container each resolved child as a Subview to wrap, separate or count, with per-child containerValues. Subviews resolve in the container's environment, and a style applied to one may not take effect.

solid answer

~40 s

`ForEach(subviews:content:)` calls my closure once per resolved child of a view, and `Group(subviews:transform:)` gives me the whole `SubviewsCollection`, a random-access collection, so I can count children, treat the first one differently or put a `Divider` between them. Each element is a `Subview`, which is both a `View` and `Identifiable`; a `ForEach` inside the caller's content contributes one subview per element, while a nested `VStack` stays one subview. Callers pass per-child flags with `containerValue(_:_:)` on a `ContainerValues` entry declared with `@Entry`, and those values stop at the closest container. The limits, from Apple's documentation: a subview is a proxy, so modifiers on the original view apply first, it resolves in its container's environment rather than the proxy's, and a style applied to it may have no effect. All of this needs iOS 18.

code

swift · 32 lines
swift
import SwiftUI

extension ContainerValues {
    @Entry var isEmphasized: Bool = false
}

extension View {
    func emphasized(_ value: Bool = true) -> some View {
        containerValue(\.isEmphasized, value)
    }
}

struct DetailCard<Content: View>: View {
    @ViewBuilder var content: Content

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            Group(subviews: content) { subviews in
                ForEach(subviews) { subview in
                    subview
                        .padding(.vertical, 10)
                        .background(subview.containerValues.isEmphasized ? Color.yellow.opacity(0.15) : Color.clear)
                    if subview.id != subviews.last?.id {
                        Divider()
                    }
                }
            }
        }
        .padding(.horizontal, 16)
        .background(.background, in: .rect(cornerRadius: 12))
    }
}

go deeper

for a junior

Know that iOS 18 lets a custom container loop over its caller's children with ForEach(subviews:) and that each child arrives as a Subview.

for a middle

Explain the difference between ForEach(subviews:) and Group(subviews:), what counts as one subview, and how containerValue(::) passes a per-child flag.

for a senior

Diagnose why a container value reads as default or a style does not apply, using the documented rules: closest container only, proxies resolve in the container's environment, styles may already be applied.

for a principal

Weigh the subview API against a data-driven container given the deployment target, and decide which design-system containers justify the iOS 18 requirement.

## What these initializers add Before iOS 18, public API gave a container view no way to iterate its caller's content as separate views. The `Layout` protocol, from iOS 16, can measure and place each child, but it cannot wrap children in new views or insert a separator between them; otherwise the container's API had to take an array of data and a row builder instead of free-form content. iOS 18 added, among others, two initializers, both declared `@available(iOS 18.0, ...)` in the SDK: - **`ForEach(subviews:content:)`** iterates the subviews of a view, calling your closure with one `Subview` at a time. - **`Group(subviews:transform:)`** hands your closure the whole **`SubviewsCollection`**, a `RandomAccessCollection`, so you can use `count`, `first`, `last`, `dropFirst()` and indices. Apple's sample project *Creating custom container views*, associated with the WWDC24 session *Demystify SwiftUI containers*, covers this ground. The same release added `ForEach(sections:content:)` and `Group(sections:transform:)`, whose `SectionConfiguration` exposes `header`, `footer` and `content`, for containers that honour `Section`. ## What counts as a subview The collection holds the **resolved** pieces of the content, not the lines the caller typed. Apple's documentation says the elements "are the pieces that make up the given view" and that a subview represents "a single leaf view, or container". In practice: - a `Text` or `LabeledContent` the caller lists is one subview; - a `ForEach` over five transfers contributes five subviews; - a `VStack` the caller wraps around two rows is one subview, because the stack is itself a container. `SubviewsCollection` "constructs subviews on demand", so a container should access only the part it needs. ## Passing per-child options with container values Callers often need to flag one child: emphasise the available balance, pin a row. **`ContainerValues`** carries such per-child data: 1. Declare an entry: `extension ContainerValues { @Entry var isEmphasized: Bool = false }`. 2. Offer a modifier that calls `containerValue(\.isEmphasized, true)`. 3. In the container, read `subview.containerValues.isEmphasized`. | Mechanism | Direction | Where it stops | |---|---|---| | Environment values | Down to descendants | At the edge of the subtree they are set on | | Preferences | Up to ancestors, merged | Readable above containers | | Container values | Up to the direct container | The closest container; no merging | Apple's documentation is explicit that container values "don't escape their closest container", even a stack with one child. A value set on a `Text` wrapped in a `VStack` is therefore invisible to the outer custom container: the `VStack` is the direct subview, and it reads as the default. ## Where they fall short - **Proxies, not the original.** Modifiers applied to the original view are applied before modifiers you apply to the subview. - **The container's environment.** Apple's documentation says a subview is resolved using the environment of its container, not the environment of the subview proxy. Setting an environment-driven value on the proxy, such as a font, is not a reliable way to restyle a child; put the value on the container, or let the caller set it. - **Styles may not stick.** Because a subview can represent a view after its styles were applied, Apple's documentation warns that applying a style to a subview may have no effect. - **Availability.** An app that deploys back to iOS 17 must keep a fallback, typically a data-driven initializer that takes a collection and a row builder. - **Lazy containers.** Inside `List` or `LazyVStack`, Apple's `ForEach` documentation recommends that each element produce a constant number of views for best performance, so keep per-child decoration inside one view when the container is lazy. ## A worked shape A fintech detail card lays out labelled values with a divider between rows and a highlighted background on the emphasised one. The container uses `Group(subviews:)` to know which subview is last, and wraps each in padding and a background, which are not environment-driven, so they apply as written. Step by step: 1. The caller lists `LabeledContent` rows, possibly with a `ForEach` over pending transfers, and marks one row with `.emphasized()`. 2. The container receives the content through a `@ViewBuilder` property and passes it to `Group(subviews:)`. 3. For each subview it adds vertical padding and a background chosen from `containerValues.isEmphasized`. 4. It inserts a `Divider` after every subview except the last, which it finds by comparing `id` with `subviews.last?.id`. The caller never learns about dividers, and the container never learns what a row contains: each side owns exactly one concern.

  • When would you choose Group(subviews:) over ForEach(subviews:)?
    When the container needs the collection as a whole: its `count`, its first or last element, or a slice. `Group(subviews:transform:)` hands over the `SubviewsCollection`, so you can show the first child as a hero and the rest in a grid, or end with a footer that counts the remaining children. `ForEach(subviews:)` is enough when each child is treated the same way.
  • How would you support Section headers inside such a container?
    Use `ForEach(sections:content:)` or `Group(sections:transform:)`, also iOS 18. Each `SectionConfiguration` exposes `header`, `footer` and `content` as subview collections, so the container can draw its own header style and lay out each section's rows.
  • What do you ship for an app that still supports iOS 17?
    Gate the subview-based container with `if #available(iOS 18.0, *)` or keep a data-driven API for older systems: an initializer taking a collection and a row builder, which a `ForEach` inside the container can iterate with dividers. Both share the row styling, so the visual result matches.

  • Group(subviews:) gives one subview per line the caller typed.
  • Container values travel up through every ancestor, like preferences.
  • A font set on a Subview proxy reliably restyles that child.
  • A ForEach in the content counts as one subview.
  • ForEach(subviews:) works on iOS 17 because ForEach has existed since iOS 13.

Assumes iOS 18 or later: ForEach(subviews:content:), Group(subviews:transform:), Subview and ContainerValues are all declared @available(iOS 18.0) in the SDK.