skip to content

Views and Composition

A view is a cheap value that describes the screen, identity decides what survives an update, and small reusable views compose into screens. Every SwiftUI interview starts here.

on this pageshow

explore

questions

17

In SwiftUI, why is a view a lightweight struct whose body SwiftUI reads repeatedly, rather than a long-lived object you update?

level: juniorimportance: must knowfreq 80%

answer

  1. description, not a screen object
  2. the View protocol's one requirement
  3. body read again on updates
  4. recreated often, so init stays light

basics

~20 s

A SwiftUI view is a value describing what to show for its current inputs. SwiftUI reads its body whenever an update needs it and redraws only the affected parts, so view structs are recreated often and must stay cheap.

solid answer

~40 s

A type conforms to `View` by providing a `body` computed property, and that body is a *description* of the UI for the view's current inputs, not a handle on something drawn. SwiftUI reads `body` any time it needs to update — typically after user input or a data change — and redraws only the parts of the interface that changed, so the framework, not my code, does the add, remove and update work. Because the system may reinitialize a view struct at any time, I keep initializers trivial and avoid significant work there; real state lives in storage SwiftUI manages for `@State`, or in models, not in the struct's plain properties. The protocol is also `@MainActor`, so `body` is read on the main actor.

code

swift · 25 lines
swift
import SwiftUI

struct TemperatureLabel: View {
    let city: String
    let celsius: Int

    var body: some View {
        VStack(alignment: .leading) {
            Text(city)
                .font(.headline)
            Text("\(celsius)°")
                .font(.largeTitle)
        }
    }
}

struct CityRow: View {
    let celsius: Int

    var body: some View {
        // A new TemperatureLabel value is created on every read of this body;
        // that is expected and cheap.
        TemperatureLabel(city: "Lisbon", celsius: celsius)
    }
}

go deeper

for a junior

Recall that a view is a struct conforming to View with one required body property, and that body describes the UI for the current inputs rather than drawing it.

for a middle

Explain that SwiftUI reads body again when inputs change, may reinitialize the struct at any time, and keeps state storage outside the struct, so init and body stay light.

for a senior

Turn the model into review rules: side-effect-free bodies, no heavy work in init, narrow inputs per subview, and state kept in SwiftUI-managed storage or models rather than plain properties.

for a principal

Present the value-description model as what lets the framework own update work, and say how that shapes a team's review checklist and the onboarding of engineers used to mutating view objects.

## What a SwiftUI view is In SwiftUI, a **view** is any type that conforms to the `View` protocol. The protocol's main requirement is a `body` computed property, and Apple's documentation describes what that property holds: each view contains **a description of what to display for a given state**. A view is therefore not a box drawn on screen that you keep and adjust; it is a small value — almost always a `struct` — whose stored properties are its inputs and whose `body` turns those inputs into more views. The `body` property is declared as `some View`. That tells Swift the property returns one concrete view type without spelling it out; the compiler infers it from whatever the body contains. Built-in views such as `Text`, `Image`, `VStack` and `ProgressView` are views in exactly the same sense, so a screen is a tree of small descriptions nested inside each other. The protocol is also declared `@MainActor`. A type that declares its `View` conformance in its original declaration inherits that isolation, so a view's `body` is read on the main actor. ## How SwiftUI uses body The documented cycle is short: 1. You declare the hierarchy: a root view whose `body` contains other views, configured with modifiers and given their inputs. 2. Something changes — the user taps, a model publishes new data, a parent passes a different value. 3. SwiftUI notices which inputs changed and reads `body` again where it needs to. Apple's documentation says it reads the property "any time it needs to update the view, which can happen repeatedly during the life of the view". 4. SwiftUI **redraws only the affected parts** of the interface. Doing that may involve reinitializing the view struct, and SwiftUI manages that for you. Modifiers follow the same idea. Calling `.font(.title)` or `.opacity(0.5)` does not change a property on an existing object; it returns a **new view that wraps the original** and takes its place in the hierarchy. ## Why a struct and not an object - **Cheap to create.** A struct with a couple of `let` properties costs almost nothing to build, so SwiftUI can create it as often as updates require. - **No hidden mutable state.** A plain stored property cannot drift out of sync with the screen, because the screen is recomputed from the value rather than patched by hand. - **Identity is not the struct's job.** A value has no reference identity of its own; SwiftUI decides whether two descriptions are the same view from their position in the tree or an explicit ID, which is the subject of the lesson on view identity. - **Main-actor reads.** Because `View` is `@MainActor`, `body` is read on the main actor, where UI updates happen. ## Who owns what | Piece | Owner | Lifetime | |---|---|---| | The view struct | Your code | Recreated whenever SwiftUI needs it | | What is drawn on screen | SwiftUI | Updated in place where inputs changed | | `@State` storage | SwiftUI manages it | Kept while the view keeps its identity | | Models and services | Your app | However long your app keeps them | The table explains the most common surprise for newcomers: a plain `var` on a view struct is not state. `body` is a non-mutating getter, so a button action inside it cannot assign to a stored property — the compiler rejects it — and any value you did manage to change would be replaced the next time the parent recreates the struct. View-owned values live in `@State`, whose storage SwiftUI manages outside the struct; how the state wrappers work belongs to the lessons on state. ## Rules that follow from the model - **Keep initializers trivial.** Apple's documentation warns that the system may reinitialize a view at any time, so significant work in `init` can run many times. It is often best to let Swift synthesize the memberwise initializer. - **Keep `body` cheap and free of side effects.** It can be read many times; starting network calls or heavy formatting there repeats them. Work that should run when a view appears belongs to the lesson on appearance and async work, and measuring redraws belongs to the performance lesson. - **Pass narrow inputs.** A subview that receives only the values it shows gives SwiftUI a precise picture of what changed. - **Extract subviews freely.** Splitting a long `body` into small view structs costs little, because the structs themselves are cheap values. ## How to answer in an interview Say that a SwiftUI view is a value describing UI for its current inputs, that SwiftUI reads `body` whenever an update needs it and updates only what changed, and that this is why views are structs, why initializers stay light, and why real state lives in storage SwiftUI manages rather than in the struct.

  • Can you keep a tap counter in a plain var on a SwiftUI view and increment it from a Button?
    No. `body` is a non-mutating getter of a struct, so assigning to a plain stored property from a closure inside it doesn't compile, and a changed value would not survive the parent recreating the struct anyway. A view-owned value goes in `@State`, whose storage SwiftUI manages outside the struct and keeps for as long as the view keeps its identity.
  • Does SwiftUI re-read every view's body in the app whenever any data changes?
    No. Apple's documentation says SwiftUI notices which input changed and redraws only the affected parts of the interface. That is why small subviews with narrow inputs help: a subview whose inputs and dependencies did not change gives SwiftUI no reason to update it. Measuring how often bodies actually run is a profiling task covered with SwiftUI performance.

A view is like an order ticket handed to a kitchen: when the order changes you write a fresh ticket, and the kitchen works out which dishes actually need changing instead of cooking the whole meal again.

  • A SwiftUI view struct is the object drawn on screen and lives while visible.
  • Body runs once when the view first appears, like a load callback.
  • Expensive setup belongs in a view's init because it runs only once.
  • Changing a plain var on the view struct updates the screen.
  • Every data change makes SwiftUI rebuild the whole window from scratch.
open as a page

In SwiftUI, a view struct is recreated on every parent update, so why does its @State value survive, and what makes it start over?

level: juniorimportance: must knowfreq 66%

basics

~20 s

SwiftUI keeps @State storage outside the view struct and ties it to the view's identity, not the struct instance. A recreated struct reuses that storage; removing the view or changing its identity discards it, so the next view starts fresh.

open as a page

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%

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.

open as a page

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%

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.

open as a page

In a SwiftUI chat thread built with ForEach, why do message rows lose their expanded state, and how should each row be identified?

level: middleimportance: must knowfreq 64%

basics

~20 s

ForEach ties each row's identity, and so its @State, to the element's ID. Index IDs, id: .self on mutable values, fresh UUIDs per fetch and duplicate IDs all break that; conform messages to Identifiable with a stable, unique server ID.

open as a page

In SwiftUI, what is the difference between structural identity and explicit identity, and how does each decide whether a view keeps its state?

level: middleimportance: must knowfreq 72%

basics

~20 s

Structural identity is a view's type and position in the hierarchy, including which if branch it sits in; explicit identity is a Hashable value from id(_:) or a ForEach element's ID. Same identity keeps state; a new identity starts fresh.

open as a page

In SwiftUI, how does a custom ButtonStyle differ from a PrimitiveButtonStyle, and how does a ButtonStyle draw the pressed state?

level: middleimportance: must knowfreq 58%

basics

~20 s

ButtonStyle replaces a button's appearance but keeps the platform's standard interaction, and its configuration's isPressed flag lets the style draw the pressed look. PrimitiveButtonStyle also takes over interaction: the style decides when to call configuration.trigger().

open as a page

In SwiftUI, how do you write a custom ViewModifier, and when is it better than a View extension that only chains modifiers?

level: middleimportance: must knowfreq 62%

basics

~20 s

A ViewModifier is a struct whose body(content:) wraps the incoming view; a View extension that calls modifier(_:) exposes it. A plain extension suffices for a stateless chain; the struct earns its place when it keeps @State or reads the environment.

open as a page

When porting a UIKit weather screen with loading, error and loaded states to SwiftUI, how does one body replace the view controller's update code?

level: middleimportance: should knowfreq 60%

basics

~20 s

Model the screen's state as one enum and switch over it in body, each case describing its whole UI. SwiftUI reads body again when the phase changes and updates the screen, replacing the controller's show, hide and reload calls.

open as a page

How does a custom SwiftUI LabeledContentStyle applied once to a container restyle every LabeledContent inside, and which style wins when nested?

level: middleimportance: should knowfreq 40%

basics

~20 s

A custom style conforms to a style protocol such as LabeledContentStyle and builds the view in makeBody(configuration:) from the configuration's pieces. Its style modifier propagates down the hierarchy, so every matching view below uses it, and a style set closer to a view wins.

open as a page

In a SwiftUI code review, a helper returns AnyView for each weather card variant; what does that erasure cost, and when is AnyView acceptable?

level: seniorimportance: should knowfreq 45%

basics

~20 s

AnyView hides the concrete view type, and when the wrapped type changes SwiftUI destroys the old hierarchy and builds a new one, resetting its state. Prefer a @ViewBuilder switch or generics; keep AnyView for genuinely open-ended view types.

open as a page

For a new iOS screen, how do you choose between SwiftUI and UIKit, and when is dropping to UIKit inside SwiftUI justified?

level: seniorimportance: should knowfreq 65%

basics

~20 s

Default to SwiftUI when its APIs at your deployment target cover the screen, since it removes manual update code. Use UIKit, or wrap a UIKit view, when you need an API or control SwiftUI lacks at that target.

open as a page

When would you deliberately change a SwiftUI view's id(_:) value to reset it, and what side effects come with that reset?

level: seniorimportance: should knowfreq 46%

basics

~20 s

Change id(_:) when state derived once from an input must start over as that input changes, like a per-conversation composer. The reset is total: state, focus and owned models restart, onAppear and task run again, and inner changes don't animate.

open as a page

In SwiftUI, a text field empties whenever its parent toggles a highlight using if/else around the same child view; why, and how do you fix it?

level: seniorimportance: should knowfreq 56%

basics

~20 s

Each if/else branch is a separate structural identity, so flipping the condition replaces the child with a new one whose @State starts empty. Keep one view and put the condition inside the modifier's argument, or hoist the text into the parent.

open as a page

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%

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.

open as a page

As the lead of a list-heavy SwiftUI app with recurring lost-state bugs, which identity rules would you put into code review, and how would you enforce them?

level: principalimportance: should knowfreq 25%

basics

~20 s

Identity decides how long state lives, so review it like data ownership: stable model IDs in ForEach, no generated or positional IDs, conditional values instead of if/else around one view, id(_:) only for deliberate resets, and no needless AnyView.

open as a page

A SwiftUI design system's primary button, card and labelled-value row serve twenty screens; how do you decide between style protocols, wrapper views and view modifiers for each?

level: principalimportance: should knowfreq 35%

basics

~20 s

Style the standard control when SwiftUI has one (ButtonStyle, LabeledContentStyle), so screens keep its semantics; build a generic container view when the component owns structure and slots; use a view modifier for treatments any view can take.

open as a page