Skip to content
Tutorials Center
My learning

Topics

Lesson 122 of 146 ยท Platforms and Ecosystem

SwiftUI Overview

Understand SwiftUI before you open Xcode: declarative views, state and bindings, modifiers and their order, @Observable models, layout, and a minimal app, with runnable models.

SwiftUI is Apple's framework for building user interfaces on iOS, iPadOS, macOS, watchOS, tvOS and visionOS. Instead of creating buttons and labels and updating them by hand when something changes, you write a description of what the screen should look like for the current data. When the data changes, SwiftUI calls your description again and updates only what is different. It is almost entirely made of Swift features you already know: structs, protocols, generics, opaque return types, property wrappers, result builders and, newer, macros.

That is why this lesson is possible on a site that cannot run SwiftUI. You will learn how SwiftUI works by building small stand-ins with the language features it is made from, then reading the real SwiftUI code (read-only) with confidence. Real SwiftUI needs an Apple platform and Xcode; see Swift on Apple platforms.

Every SwiftUI listing in this lesson is a read-only example. Every runnable example uses stand-in types that we wrote ourselves (a Text that is not SwiftUI's Text, and so on) and says so. They teach the idea, not the exact API.

The core idea: the screen is a function of state

Declarative UI is one equation: screen = function(state). You never say "change this label's text". You say what the screen is for a given count, and let the framework work out what changed.

A SwiftUI view is a struct with one required property, body, that returns the content. A tiny real example (read-only):

Swift
// Read-only example: needs SwiftUI.
import SwiftUI

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

    var body: some View {
        VStack(spacing: 12) {
            Text("Count: \(count)")
                .font(.title)
            Button("Add one") {
                count += 1
            }
            if count > 2 {
                Text("That is a lot of taps")
            }
        }
        .padding()
    }
}

Tapping the button changes count. @State tells SwiftUI that count affects the screen, so SwiftUI calls body again, compares the new description with the old, and updates the pixels that differ. Nothing in the code mentions updating the label or showing or hiding the second Text. Here is the same idea as a model you can run. The Text, VStack and modifiers are stand-ins that print a tree instead of drawing:

Swift A view is a function of state (stand-in types)

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.

Study the pieces, because they are exactly how SwiftUI is built:

  • Views are small value types. Creating Text("...") costs almost nothing, because it is only a description, not a widget. SwiftUI creates and throws away views all the time.
  • The if inside VStack { ... } works because of a result builder (see result builders). The builder turns a list of statements and conditionals into one value. That is why SwiftUI code has no commas or return between children.
  • Modifiers return a new, wrapped view. .bold() does not change the text; it returns a Modified value around it. That is the generic type you see in SwiftUI's error messages, like ModifiedContent<Text, _PaddingLayout>.
  • Order matters. The last two trees differ: .padding().background() wraps the padded text in a background, so the background covers the padding. .background().padding() colors only the text and then adds empty space outside it. In real SwiftUI that is the difference between a button with a colored pill and one with a colored label inside a margin.

Why some View

A view's body has the type some View, an opaque return type (see opaque types): "a specific type that conforms to View, and the compiler knows which." The restriction that surprises beginners is that all return paths must produce the same type. This real compile error is the reason SwiftUI needs Group, @ViewBuilder and if in builders instead of plain return statements:

Swift One opaque type per function (fails on purpose)

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.

The compiler says function declares an opaque return type 'some Shape', but the return statements in its body do not have matching underlying types and notes that one return has type Circle and the other Square. Inside a @ViewBuilder this problem disappears, because the builder turns the if/else into a single type that remembers both branches (that is what buildEither does in our stand-in).

State, bindings and the single source of truth

Every piece of changing data should have one owner. SwiftUI offers property wrappers for the common cases:

Wrapper What it is Typical use
@State Value owned by this view, kept by SwiftUI between redraws Toggles, text field contents, selection
@Binding A read/write reference to state owned by a parent Passing a value down to a control
@Observable class (plain property) A model object shared by many views App data, view models
@Environment A value injected from above Color scheme, locale, dismiss action, your own services
@Bindable Makes $ bindings to properties of an @Observable object Editing a model in a form

A binding is just a getter and a setter bundled together. A control such as a text field does not own its text; it receives a binding to the parent's state. Here is the whole idea in plain Swift:

Swift A binding is a getter and a setter (stand-in types)

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.

In real SwiftUI the property wrapper @State does what StateBox does and the $ prefix gives you projected, the binding. The rule of thumb: pass values down, pass bindings when the child must edit, keep state as low in the tree as possible but as high as needed to be shared.

Observable models

For data shared by several screens, make a class marked @Observable. The macro (see macros overview) rewrites each stored property so reads and writes are tracked. SwiftUI records which properties each body reads and re-runs only the views that read a changed property. The Observation module is part of the Swift standard distribution, so we can watch the real mechanism work here:

Swift Observation: tracking only what was read

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.

The output shows three things SwiftUI relies on. The label change does not fire, because the render never read label. The first count change fires the callback (just before the new value is stored). And tracking is one-shot: after the callback, SwiftUI re-runs body, which sets up tracking again. In a real app all of this is automatic: you write a plain @Observable class and read its properties in body.

Older code uses ObservableObject with @Published and @StateObject/@ObservedObject. It still works, but it re-renders a view when any published property changes. For new code, prefer @Observable.

Layout and the common building blocks

SwiftUI layout is a negotiation: a parent proposes a size to each child, the child picks its own size, and the parent places it. You compose it with containers:

  • VStack, HStack, ZStack stack children vertically, horizontally or on top of each other. Spacer() takes all remaining room.
  • List and ForEach show collections; each element needs a stable identity (Identifiable or id:).
  • NavigationStack with NavigationLink pushes screens; .sheet presents modals.
  • Form, TextField, Toggle, Picker, Slider build settings and input screens.
  • LazyVStack, LazyVGrid create children only as they scroll into view.
  • .frame, .padding, .background, .font, .foregroundStyle, .onTapGesture are modifiers; they apply in the order you write them.

A minimal app (read-only)

A complete app is a type marked @main that conforms to App. This listing uses an @Observable model, a List and a NavigationStack:

Swift
// Read-only example: needs SwiftUI and Xcode.
import SwiftUI
import Observation

struct Todo: Identifiable {
    let id = UUID()
    var title: String
    var isDone = false
}

@Observable
final class TodoStore {
    var todos: [Todo] = [Todo(title: "Learn Swift"), Todo(title: "Read about SwiftUI")]
}

struct ContentView: View {
    @Bindable var store: TodoStore

    var body: some View {
        NavigationStack {
            List($store.todos) { $todo in
                Toggle(todo.title, isOn: $todo.isDone)
            }
            .navigationTitle("To do")
        }
    }
}

@main
struct TodoApp: App {
    @State private var store = TodoStore()

    var body: some Scene {
        WindowGroup {
            ContentView(store: store)
        }
    }
}

Read it from the bottom. TodoApp is the entry point; WindowGroup creates a window with ContentView. The model is created once with @State and passed in. List($store.todos) hands every row a binding, so flipping a Toggle writes isDone back into the store, which tracks the change and redraws only the rows that read it.

Pitfalls and good habits

  • Do not do heavy work in body. It can run many times. Compute in the model and read the result.
  • Give list items stable identity. Using the array index as an id makes SwiftUI confuse rows when the list changes.
  • Do not store derived data in @State. Compute it from the source of truth.
  • Use @MainActor for models that the UI reads, and do slow work in a Task or an actor (see actors).
  • Previews: #Preview { ContentView(store: TodoStore()) } shows a live canvas in Xcode with sample data; give every view an easy way to be created with fake data.
  • Mix with UIKit when you must. SwiftUI is the default, not a religion.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does declarative UI mean in SwiftUI?

    The screen is a function of state. When state changes, SwiftUI calls body again and applies the difference.
  2. 2. Why does .padding().background() look different from .background().padding()?

    Modifiers return new wrapped views. A background applied after padding covers the padding; applied before, it covers only the content.
  3. 3. What is a Binding?

    A binding is a reference to a value owned elsewhere. $name gives you the binding for a @State property.
  4. 4. Why can a function returning some View not return Text(...) in one branch and return Image(...) in another?

    The compiler reports that the return statements do not have matching underlying types. @ViewBuilder merges the branches into one type.
  5. 5. What advantage does an @Observable model have over ObservableObject?

    Observation tracks which properties each body reads, so unrelated changes do not trigger updates.

Summary

  • SwiftUI describes the screen as a function of state; views are small value types with a body.
  • It is built from Swift features: structs and protocols, opaque some View, result builders for the container syntax, property wrappers (@State, @Binding), and macros (@Observable).
  • Modifiers wrap views, so their order matters.
  • Keep one owner per piece of data; pass values down and bindings when a child edits.
  • @Observable models are tracked per property by the Observation module, which runs on this site.
  • An app is an @main type conforming to App with a WindowGroup scene.
  • All real SwiftUI code needs Xcode on an Apple platform; use stand-ins like those in this lesson to understand it anywhere.

Next: Swift on the Server