Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 46 ยท Getting Started

The SwiftUI Mental Model

Understand declarative UI: a view is a function of state, body returns a view tree, structs make views cheap, and identity lets SwiftUI update only what changed.

Most beginners struggle with SwiftUI not because of the syntax, but because of the idea behind it. Older UI frameworks make you say how to change the screen: find the label, set its text, hide the button. SwiftUI asks you to say what the screen is for the current data, and then it figures out the changes. Once this clicks, the rest of the framework follows.

This lesson builds that mental model in four steps: declarative UI, the View protocol and body, the view tree, and identity. The runnable examples are stand-ins: plain Swift that prints a view tree as text, which is the same shape SwiftUI works with.

Declarative: the screen is a function of state

Imagine a counter app. In the imperative style you write instructions:

Swift
// UIKit-style thinking (illustration)
button.addAction(UIAction { _ in
    count += 1
    label.text = "Count: \(count)"
    if count >= 10 { resetButton.isHidden = false }
}, for: .touchUpInside)

Every place that changes count must remember to update the label and the button. Miss one and the screen lies. With declarative UI you describe the result for any value of the state:

Swift
import SwiftUI

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack {
            Text("Count: \(count)")
            Button("Add") { count += 1 }
            if count >= 10 {
                Button("Reset") { count = 0 }
            }
        }
    }
}

The button's action only changes the data. It never touches the label. SwiftUI sees that count changed, calls body again, and updates the screen. The formula to remember:

UI = f(state)

If two screens have the same state, they look the same. That makes bugs easier to reason about: to know why something is on screen, look at the state.

The SwiftUI loop

State Your data is the source of truth.
Body A function turns state into a view description.
Screen SwiftUI draws and updates what changed.
Action The user taps. Your code changes state.

Then the loop starts again.

1 / 2

Views are small structs with a body

A SwiftUI view is a struct that conforms to the View protocol. The protocol has one requirement, a computed property named body whose type is some View:

Swift
struct Badge: View {
    let title: String

    var body: some View {
        Text(title)
            .padding(8)
            .background(.yellow)
    }
}

Three facts to keep in mind:

  1. A view is a description, not the thing on screen. Creating a Badge does not draw anything. It is a lightweight value that says "a padded, yellow-backed text".
  2. Views are cheap to create. Because they are structs holding just a few properties, SwiftUI creates and throws away thousands of them. Heavy work does not belong in init or body.
  3. body is called when needed. SwiftUI calls it when the view's inputs or state change, not on a timer. You must not rely on how often.

some View is an opaque type: "some specific view type, which I won't spell out". The real type is often a long nested generic like ModifiedContent<Text, _PaddingLayout>. Hiding it keeps the code readable and lets the compiler keep full type information.

The view tree

body returns one view, which may contain other views, which contain others. The result is a tree:

flowchart TD
    A["VStack"] --> B["Text('Count: 3')"]
    A --> C["Button('Add')"]
    A --> D["(if count >= 10) Button('Reset')"]

The counter's view tree. The last branch only exists while the condition is true.

Modifiers like .padding(8) also add nodes: the result of Text("x").padding(8) is a new view that wraps the text. We explore that in View Modifiers and Their Order.

The runnable stand-in below builds a miniature tree and prints it with indentation. It is not SwiftUI, but it has the same ingredients: a View-like protocol, containers that hold children, and a function that turns state into a tree.

Swift Stand-in: a view tree as text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Same function, two states, two trees. At count = 3 the Reset button exists; at 0 it does not. Nothing ever "hides" or "shows" it by hand.

Diffing: how SwiftUI stays fast

If body rebuilds the whole description every time, is SwiftUI slow? No, because the description is cheap and SwiftUI compares the new tree with the previous one. It updates only the parts of the real screen that differ. This comparison is often called diffing, and it relies on identity.

SwiftUI identifies a view in two ways:

  • Structural identity: a view's position in the tree. The first Text inside the VStack is "the first child", whatever its content.
  • Explicit identity: an id you provide, for example the id of a row in a ForEach.

When the new tree has the same kind of view at the same position, SwiftUI keeps the existing view and its state, and only updates properties such as the text. When the kind or the identity changes, the old view is removed and a new one is created, and its @State starts fresh. This is why the shape of body matters: View Identity and Lifecycle returns to it in depth.

The next stand-in compares two trees by position and reports what a toolkit would have to do.

Swift Stand-in: diffing two states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Only the first line causes real work; the second is untouched. Real SwiftUI is more sophisticated, but the principle is the same: describe everything, update only differences.

What this means for how you write code

  • Keep body pure. It should read state and return views. Do not start network calls, change state or write to disk inside it.
  • Put data changes in actions. Button closures, .task and onChange are the places where state changes.
  • Break big views into small ones. Small structs are cheap, and each can have its own state and previews.
  • Do not store views in variables expecting them to be "the screen". They are throwaway descriptions.

Seeing your app as a pipeline from state to tree lets you ask the right debugging question: not "why didn't the label update?" but "what is the state, and what does body return for it?" The next lesson reviews the Swift features that make this syntax possible, in Swift Features SwiftUI Relies On.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the formula UI = f(state) mean in SwiftUI?

    You write body to describe the UI for any state. SwiftUI calls it again when state changes and applies only the differences.
  2. 2. What is a SwiftUI view, technically?

    Views are small value types. Creating one draws nothing; it is only a description that SwiftUI renders and compares.
  3. 3. Why should you avoid starting network requests directly inside body?

    SwiftUI decides when to evaluate body. Side effects there can run repeatedly. Use .task or actions instead.
  4. 4. A view keeps its @State across updates when...

    State lives with the view's identity. If the identity or the kind at that position changes, the old view and its state are discarded.
  5. 5. What is the role of 'some View' in var body: some View?

    some View is an opaque return type: one concrete type, not spelled out. This keeps nested generic types out of your code.

Summary

  • SwiftUI is declarative: UI = f(state). Change the data and the screen follows.
  • A view is a small struct with a body that returns some View; it is a description, not pixels.
  • body produces a tree; modifiers and conditionals add or remove nodes.
  • SwiftUI diffs the new tree against the old using structural and explicit identity.
  • Keep body free of side effects; change state in actions, .task and onChange.

Next: Swift Features SwiftUI Relies On