How it works
AnyTabContent is a type-erasing wrapper that hides the concrete type of a piece of tab content behind a single, uniform type. Because builders like Tab and the tab content inside a TabView each have their own distinct static types, you can't normally return or store them through one common type or mix them freely across branches. AnyTabContent erases those differences while preserving the selection value type, so its generic parameter records the type used to identify each tab. Reach for it when you need to compute tab content dynamically, return it from a property or function, or collect heterogeneous tabs into one value that a TabView can consume.
Erase a tab's type by wrapping it in AnyTabContent
The initializer takes any tab content value and produces an AnyTabContent that no longer exposes the wrapped type. In the example, AnyTabContent wraps a Tab("Profile", systemImage: "person.crop.circle", value: 3) so the result is a single, named type rather than the specific Tab specialization underneath.
Carry the selection type through the generic parameter
AnyTabContent is generic over the value that identifies its tabs, written here as AnyTabContent<Int>. That parameter must match the selection type the TabView uses, so a tab carrying value: 3 must be erased as AnyTabContent<Int> to stay compatible with the $selection binding of type Int.
Return erased content from a computed property
Because the erased type is concrete and nameable, you can declare it as the return type of a property or function. The dynamicTab computed property is typed as AnyTabContent<Int> and returns the wrapped Tab, which would be impossible to express cleanly with the underlying opaque tab type.
Drop the erased value into the TabView body
An AnyTabContent participates in a TabView's content exactly like a literal Tab does. Inside the TabView(selection: $selection) body, dynamicTab sits alongside the inline Tab entries for "Home" and "Search", and SwiftUI renders it as just another selectable tab keyed by its value.
Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct AnyTabContentDemo: View {
@State private var selection = 1
private var dynamicTab: AnyTabContent<Int> {
AnyTabContent(
Tab("Profile", systemImage: "person.crop.circle", value: 3) {
Text("Profile").font(.title).padding()
}
)
}
var body: some View {
TabView(selection: $selection) {
Tab("Home", systemImage: "house", value: 1) {
Text("Home").font(.title).padding()
}
Tab("Search", systemImage: "magnifyingglass", value: 2) {
Text("Search").font(.title).padding()
}
dynamicTab
}
.padding()
}
}