The Analogy: The Stadium Scoreboard and the Official Scorer's Book
At a ballgame, the giant scoreboard shows the score, the inning, the outs, and the count on the batter. But nobody climbs the scoreboard to flip those numbers by hand. There is one official record -- the scorer's book down at the desk -- and the board is wired to display exactly whatever that book says. The book is the single source of truth; the board is a faithful picture of it. This is the whole idea behind declarative UI: you keep the facts in one place, and the display is defined as a picture of those facts rather than a pile of instructions for poking the display.
Because the board is defined as a picture of the book, the operator never writes "increase the home score by one." Instead the board's wiring declares, once and for all, "the home panel shows book.homeScore, the out lights show book.outs, the count shows book.balls and book.strikes." That standing description is a view's body: a rule that turns the current facts into a layout. The operator's only job is to keep the book accurate. Describing the end result instead of the steps to get there is exactly what "declarative" means, and it is why a SwiftUI view is written as a function of its state.
When a run scores, the scorer changes one number in the book, and every part of the board that depends on that number redraws itself to match; the parts that do not depend on it are left alone. That automatic, targeted refresh is reactivity. In SwiftUI the book is the view's state, marked @State; mutating a state value invalidates the body, and the framework re-runs it and updates only the pieces that actually changed. Facts flow down from the book to the board, and events -- a play on the field -- flow up to the scorer who records them, never straight onto the board.
The trouble starts the moment someone bypasses the book and climbs up to hand-flip a digit on the board directly. Now the board and the book disagree, and there are two competing sources of truth. The next legitimate update redraws the board from the book and silently wipes out the hand-set digit, or, worse, the stale hand-set value sits there misleading the whole stadium until then. That is what happens when you mutate the view directly, or keep a second private copy of data inside a view and change that instead of the real model: the framework, which only ever draws from the true state, will either clobber your change or be thrown out of sync with it. In a declarative system the display is only ever a projection of the state, and the instant you treat it as a place to store facts, you have built a liar into the machine.
Syntax or Core Structure
A SwiftUI view is a type conforming to the View protocol, and its one required piece is a body that describes what to show. The view owns its private facts with @State; reading a state value inside body ties the display to it, and mutating that value causes body to run again.
import SwiftUI
struct Counter: View {
@State private var count = 0 // the single source of truth
var body: some View { // a description, not a script
VStack {
Text("Count: \(count)") // reads state -> redraws on change
Button("Add") { count += 1 } // an event mutates state
}
}
}
You never write "set the label's text." You change count, and because body describes the label as "Count: \(count)", SwiftUI recomputes it for you. Appearance is layered on with view modifiers, each of which returns a new, wrapped view, so they chain.
Text("Hello")
.padding() // wraps Text in padding
.background(Color.yellow) // wraps that in a colored box
.cornerRadius(8) // wraps that with rounded corners
Facts flow one way: a parent holds state and passes plain values down to child views, while children send events back up through closures or a @Binding. A child never reaches up and edits the parent's stored data directly.
struct Parent: View {
@State private var name = "world"
var body: some View {
Greeting(name: name) // value flows down
}
}
struct Greeting: View {
let name: String // read-only copy
var body: some View { Text("Hello, \(name)") }
}
Technical Depth: How SwiftUI Turns State Into Views
A view is a function of its state
The mental model that makes SwiftUI click is that body is a pure function: given the same state, it produces the same layout. The framework calls it whenever the state changes and compares the result to what is on screen. To make that idea concrete and testable without a device, pull the display logic into a plain function and check its output directly -- the view's Text would show exactly this string.
func label(for count: Int) -> String {
return "Count: \(count)"
}
print(label(for: 0))
print(label(for: 3))
Output:
Count: 0
Count: 3
When count goes from 0 to 3, the label is not edited in place; body reruns and produces a fresh "Count: 3", and SwiftUI swaps in only what differs. Same input, same output, every time.
| Aspect | Imperative UI (UIKit) | Declarative UI (SwiftUI) |
|---|---|---|
| You write | steps that mutate widgets | a description of the result |
| On a state change | update each widget by hand | body reruns, framework diffs |
| Where truth lives | scattered across widgets | in the state values |
@State is the single source of truth
A value marked @State is owned by the view and stored by SwiftUI across redraws. Mutating it is the signal that the display is stale, which triggers a recompute. You flip the fact; the framework redraws the picture.
func statusText(_ isOn: Bool) -> String {
return isOn ? "Light: ON" : "Light: OFF"
}
print(statusText(false))
print(statusText(true))
Output:
Light: OFF
Light: ON
In a real view a Button would call isOn.toggle(). You would never write label.text = "Light: ON"; there is no label to poke. The only lever is the isOn fact, and the Text is defined as statusText(isOn), so changing the fact is what changes the display.
Derived values are computed from state, not stored
Anything the UI shows that can be calculated from the state should be calculated, not stored as a second fact. If a cart is the source of truth, the item count and the total are pure functions of it, so they can never drift out of sync with the cart.
struct Item {
let name: String
let cents: Int
}
func totalCents(_ items: [Item]) -> Int {
return items.reduce(0) { running, item in running + item.cents }
}
let cart = [Item(name: "Coffee", cents: 350), Item(name: "Muffin", cents: 275)]
print("items: \(cart.count)")
print("total cents: \(totalCents(cart))")
Output:
items: 2
total cents: 625
The cart array would be the @State; the count and total shown in the view are derived on the spot each time body runs. Add an item and both numbers update together because they read from one place. A child row receives its Item as a plain let and reports taps back up; it does not reach into the array itself.
View modifiers wrap, so order matters
Each modifier takes the view it is called on and returns a new view that contains it. Chaining modifiers builds a nested wrapping from the inside out, which is why the order you write them in changes the result. This nesting can be modelled exactly with a string builder.
func styled(_ base: String, steps: [String]) -> String {
var result = base
for step in steps {
result = "\(step)(\(result))"
}
return result
}
print(styled("Text", steps: ["padding", "background", "cornerRadius"]))
Output:
cornerRadius(background(padding(Text)))
Read the output inside out: the Text is padded, the padded view is given a background, and that is given rounded corners. Swap padding and background and you would color the text tightly first and pad outside the color instead -- a visibly different result from the same two modifiers.
Real World Example: A Tip Calculator View
A tip calculator is the smallest complete example of the whole pattern: two facts held as state (the bill and the tip percentage), and three lines of display that are pure functions of those facts. Change either fact through a control and all three lines recompute. Here is the view, followed by the pure helpers that produce exactly the text it shows.
import SwiftUI
struct TipCalculator: View {
@State private var billCents = 4800
@State private var tipPercent = 18
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(billLine(billCents))
Text(tipLine(billCents, tipPercent))
Text(totalLine(billCents, tipPercent))
Stepper("Tip: \(tipPercent)%", value: $tipPercent, in: 0...30)
}
.padding()
}
}
func dollars(_ cents: Int) -> String {
let d = cents / 100
let c = cents % 100
let padded = c < 10 ? "0\(c)" : "\(c)"
return "$\(d).\(padded)"
}
func tipCents(_ bill: Int, _ percent: Int) -> Int {
return bill * percent / 100
}
func billLine(_ bill: Int) -> String {
return "Bill: \(dollars(bill))"
}
func tipLine(_ bill: Int, _ percent: Int) -> String {
return "Tip (\(percent)%): \(dollars(tipCents(bill, percent)))"
}
func totalLine(_ bill: Int, _ percent: Int) -> String {
return "Total: \(dollars(bill + tipCents(bill, percent)))"
}
// What the view displays for its initial state:
print(billLine(4800))
print(tipLine(4800, 18))
print(totalLine(4800, 18))
Output:
Bill: $48.00
Tip (18%): $8.64
Total: $56.64
The view holds two facts and nothing else. The three Text lines are defined as functions of those facts: billLine formats 4800 cents as $48.00, tipCents computes 4800 times 18 divided by 100 as 864 cents which tipLine renders as $8.64, and totalLine adds bill and tip to get 5664 cents, $56.64. Nothing here is stored twice; the tip and total exist only as computed projections of the bill and the percentage.
This is why the Stepper is enough to make the screen feel alive. It is bound to tipPercent with $tipPercent, so tapping it mutates that one fact. SwiftUI sees the state change, reruns body, and the tip and total lines redraw from the new percentage -- without a single line of code that says "update the tip label." The control edits the source of truth; the display follows.
The one-way flow keeps the whole thing honest. If this view handed a row off to a subview, it would pass a formatted string or a plain number down, and the subview would have no way to secretly change the bill. Every path that alters what is on screen goes through billCents or tipPercent, which is precisely the guarantee that keeps the board and the book agreeing.
The design flaw is in the money math. tipCents uses integer division, which truncates toward zero, so a bill of 999 cents at 18 percent computes 999 times 18 as 17982, divided by 100 as 179 cents -- it silently drops the .82 and under-tips by a cent, with no rounding policy anywhere. The second weakness is that billCents is state the UI can never change: only the Stepper for tipPercent exists, so the "bill" is effectively hard-coded and the source of truth is only half-wired to the interface. A production version would round the tip to the nearest cent (add 50 before dividing, or use a decimal type) and give the bill a real input control so the user can edit the fact the whole screen depends on.
Common Mistakes
- Copying model data into local @State and mutating the copy. Duplicating a value that already lives in a model into a view's
@Statecreates a second source of truth. The two drift apart, and the next redraw from the model overwrites your edit. Pass the value in, or bind to the real source, instead of snapshotting it.
- Trying to update the UI imperatively. Reaching for "set this label" or "hide that button" is UIKit thinking. In SwiftUI there is nothing to set; you change a state value and let
bodyrerun. Code that hunts for a widget to mutate is fighting the framework.
- Doing heavy work directly inside body.
bodycan run many times, so an expensive computation or a network call placed in it repeats needlessly and can stutter the UI. Compute derived values cheaply, cache with the right property wrapper, and start async work from.taskrather than inbody.
- Using @State for data the view does not own.
@Stateis for a view's own private, transient facts. Shared or externally owned data belongs in a@Binding, an observable model, or a value passed in. Marking passed-in data as@Statequietly forks it into a private copy.
- Expecting body to run in a guaranteed order or count. SwiftUI decides when and how often to call
body. Relying on it running exactly once, or in a particular sequence relative to another view, leads to bugs. Treatbodyas a pure description that may be evaluated at any time.
- Getting modifier order wrong. Because each modifier wraps the previous view,
.padding().background()and.background().padding()produce different results. Applying.frameafter a background, or padding on the wrong side of a color, is a common source of layouts that look almost right.
- Putting mutating side effects in a computed body. Assigning to state or triggering work as a side effect of computing
bodycan cause redraw loops or runtime warnings. Side effects belong in event handlers,.onChange, or.task, not in the description of the view.
- Forgetting that value-type views are cheap and identity matters for lists. Views are structs, recreated freely, so holding a reference to one is meaningless. In a
ListorForEach, failing to give elements a stable identity makes SwiftUI lose track of rows and animate or reuse them incorrectly.
- Blocking the main actor with synchronous work. UI updates run on the main actor; a long synchronous call there freezes the screen. Move slow work off with
async/awaitand update state when it returns, so the interface stays responsive.
Best Practices
- Keep one source of truth for every fact. Decide where each piece of data lives -- a view's
@State, a shared model, or a value passed in -- and let everything else derive from it. If two places can hold the same fact, they will eventually disagree.
- Derive, do not duplicate. Compute counts, totals, and formatted strings from state each time
bodyruns instead of storing them alongside. Derived values cannot drift because they have no independent existence.
- Keep body pure and cheap. Treat
bodyas a description that may run often: no side effects, no heavy computation, no network calls. Push work into event handlers,.onChange, and.taskso redraws stay fast.
- Choose the right state tool for ownership. Use
@Statefor a view's own private data,@Bindingfor two-way access to a parent's state, and an observable model for shared app state. Matching the tool to who owns the data prevents accidental private copies.
- Let data flow down and events flow up. Pass plain values into child views and hand them closures to report back. A child that never mutates its parent's storage directly keeps the data flow easy to trace.
- Mind modifier order. Remember that modifiers wrap, so apply them in the order that produces the layout you want -- padding, then background, then corner radius reads outside-in on screen. When a layout looks off, check the order before adding more modifiers.
- Give list content stable identity. Make list and
ForEachelementsIdentifiablewith an id that does not change, so SwiftUI can track rows across updates and animate them correctly.
- Do slow work off the main actor. Start long-running tasks with
async/await(often from.task), and mutate state when they finish. Keeping the main actor free is what makes a declarative UI feel instant.
Practice Exercises
- State-driven label: Write a
toggleLabel(_ isOn: Bool) -> Stringthat returns"On"or"Off", and sketch a view with an@StateBooland aButtonthat flips it. Explain, in terms of the source of truth, why the label updates without any code that sets the label's text.
- Derived total: Given an array of
(name, cents)items held as state, write a pure function that returns the formatted total (for example"$12.50"). Describe why computing the total on eachbodyrun is safer than storing it in a separate@Statevalue.
- Modifier order: Using the
styled(_:steps:)wrapping model from the lesson, predict the output forsteps: ["background", "padding", "border"], then explain in plain words how the on-screen result would differ ifpaddingcame beforebackground.
- Fix the tip rounding: Take
tipCents(_ bill: Int, _ percent: Int)from the Real World Example and rewrite it to round to the nearest cent instead of truncating. Show the new result for a bill of 999 cents at 18 percent, and state what the original returned for the same input.