skip to content

In SwiftUI, what does some View on body promise, and how can if/else or switch inside body return different view types?

level: middleimportance: must knowfreq 70%

answer

  1. one concrete type, kept hidden
  2. body carries the builder attribute
  3. branches fold into one wrapper type
  4. helper properties need the attribute too

basics

~20 s

The some View type promises one concrete view type that the compiler infers and hides. Because body is a view builder, if/else and switch branches fold into a single conditional type, so each branch may hold a different view.

solid answer

~40 s

`some View` is an opaque return type: `body` must produce exactly one concrete type, which Swift infers and hides. The `View` protocol declares `body` with SwiftUI's view builder (`@ViewBuilder`, spelled `ContentBuilder` in the iOS 27 SDK, a type alias of it), so several statements combine into a `TupleView`, an `if`/`else` becomes one conditional type holding either branch, an `if` without `else` becomes an optional view that shows nothing when false, and a `switch` nests those conditionals. That one type covers every branch, so the opaque-type promise holds. A helper property or function returning `some View` doesn't get the attribute automatically: with branches of different types it fails to compile until I mark it `@ViewBuilder` and drop the `return`s. `Group` lets one modifier reach whichever branch appears, and `EmptyView` stands for no content.

code

swift · 28 lines
swift
import SwiftUI

enum Condition {
    case sunny
    case rain(chance: Int)
    case unknown
}

struct ForecastBadge: View {
    let condition: Condition

    var body: some View {
        icon
            .font(.title2)
    }

    @ViewBuilder
    private var icon: some View {
        switch condition {
        case .sunny:
            Image(systemName: "sun.max")
        case .rain(let chance):
            Label(String(chance) + "%", systemImage: "cloud.rain")
        case .unknown:
            EmptyView()
        }
    }
}

go deeper

for a junior

Recall that body returns some View, that you can write if and switch inside it, and that helper properties need @ViewBuilder for the same thing.

for a middle

Explain the opaque-type rule and the types the builder produces: TupleView for a sequence, a conditional type for if/else and switch, an optional for if without else.

for a senior

Show judgment in review: replace erased helpers with @ViewBuilder conditionals, read inferred types as a map of possible content, and know where SwiftUI itself erases, as with if #available.

for a principal

Frame builder conditionals versus erasure as a codebase convention, weighing readability and static type information against the occasional need for open-ended view types.

## What `some View` promises `some View` is an **opaque return type**. It promises callers that `body` returns a value of **one concrete type** that conforms to `View`, while hiding which type that is. The compiler infers the type from the body's content — `VStack<TupleView<(Text, Text)>>`, say — and the `View` protocol's associated type `Body` is set to it. The promise is about the *type*, not the value: the same property may produce different values on different reads, but always of that one type. How opaque and existential types work as a language feature is covered with Swift's generics; the SwiftUI question is how a body with branches still has one type. ## Body is a view builder In the iOS 27 SDK the `View` protocol declares its requirement as `@ContentBuilder @MainActor var body: Self.Body { get }`. `ContentBuilder` is a type alias of `ViewBuilder`, SwiftUI's result builder, so the body you write is not an ordinary getter: each statement becomes a piece of content, and the builder combines the pieces into one value. Code written with `@ViewBuilder` is unchanged by the alias. The builder's rules decide the resulting type: | What you write in a builder | What the builder produces | |---|---| | Several views in a row | A `TupleView` holding all of them | | `if` / `else` | A conditional type holding either branch (`_ConditionalContent<A, B>`) | | `if` with no `else` | An optional of the branch's view, which shows nothing when `nil` | | `switch` with several cases | Nested conditional types that cover every case | | `if #available(...)` | The guarded content wrapped in `AnyView` by `buildLimitedAvailability` | | An empty block | `EmptyView` (the SDK's `EmptyContent` is an alias of it) | Because a conditional type names **both** branch types, `Text` in one branch and `Image` in the other still give the body a single static type, and the opaque-type promise holds. The general mechanics of `buildEither` and `buildOptional` belong to the Swift language material on result builders; what matters here is the view types SwiftUI ends up with. ## Helpers outside body need the attribute too Only `body` gets the builder automatically, through the protocol requirement. A computed property or function you add yourself is an ordinary Swift declaration: ```swift // Fails: the returns do not have matching underlying types var badge: some View { if isPremium { return Text("Pro") } return Image(systemName: "star") } // Compiles: one conditional type covers both branches @ViewBuilder var badge: some View { if isPremium { Text("Pro") } else { Image(systemName: "star") } } ``` Two details catch people: - **Remove the `return` statements.** An explicit `return` turns the builder off for that body; the compiler warns or errors and suggests removing the returns. - **Do not reach for `AnyView` to silence the error.** Erasing each branch compiles, but it hides the types that `@ViewBuilder` would have kept; its costs are covered in the AnyView question. ## Group and EmptyView - **`Group`** collects content into one unit **without affecting layout** the way a stack would. A modifier applied to a `Group` applies to its members, so wrapping an `if`/`else` in `Group` lets one `.navigationTitle(...)` or `.font(...)` reach whichever branch is produced. - **`EmptyView`** represents the absence of a view. You rarely write it directly: an `if` without `else` already shows nothing when false, and SwiftUI uses `EmptyView` as the type of an absent child — `ProgressView()` with no label is a `ProgressView<EmptyView, EmptyView>`, and `ContentUnavailableView`'s `description` and `actions` parameters default to `{ EmptyView() }`. Writing it explicitly is useful in a `switch` case that should show nothing. ## Why this matters in a SwiftUI codebase 1. Prefer builder conditionals in `body` and in `@ViewBuilder` helpers over returning erased types. 2. Read the inferred type as documentation: it records every view a body can produce. 3. Keep a branch's views small and extract subviews when a `switch` grows, so each case stays readable. 4. Remember that which branch is showing is part of a view's structure; how that affects state across branches is covered in the lesson on view identity and lifetime. Interviewers usually probe the helper-property error and the `if`-without-`else` case, so be ready to name the conditional type the builder produces and to explain why a missing `@ViewBuilder` fails.

  • Why does adding return statements inside a @ViewBuilder property cause trouble?
    An explicit `return` disables the result builder for that body, so the statements are no longer combined into one conditional type and the different branch types clash again. The compiler warns or errors and suggests removing the `return` statements; in a builder you simply list the views.
  • What happens to the type of a branch guarded by if #available in a SwiftUI body?
    `ViewBuilder` handles availability checks with `buildLimitedAvailability`, which wraps the guarded content in `AnyView` so the body's static type doesn't mention a type that older OS versions lack. It is one of the few places SwiftUI erases a type for you; the rest of the body keeps its concrete types.
  • When would you write EmptyView explicitly rather than rely on an if without else?
    In a `switch` where one case should show nothing, every case still needs content, so `EmptyView()` fills it. It also appears as the default for absent child content in SwiftUI's own types, such as a `ProgressView` with no label. For a simple optional piece of UI, an `if` without `else` is clearer.

  • some View lets body return a different type on each read.
  • some View and any View are interchangeable as the body type.
  • An if without else in body needs an explicit EmptyView branch.
  • Any computed property returning some View accepts mixed if/else branches automatically.
  • SwiftUI wraps each if/else branch in AnyView at runtime to make it compile.

Assumes the iOS 27 SDK in Xcode 27, which declares body with ContentBuilder, a type alias of ViewBuilder; @ViewBuilder code compiles unchanged.