ViewLab

Swift & SwiftUI course › Session 0

Exam essentials (start here)

Short on time? This lesson covers the topics that come up most in the MCQ, the Xcode practical and the viva, in plain words, with a live app preview beside every example.

About 60 minutes · covers Views, stacks, modifiers, @State, @Binding, forms, List, NavigationStack, sheets, @Observable

Open the interactive lesson (live previews, quizzes) →

What you'll learn

Contents

  1. How a SwiftUI screen works
  2. Layout: stacks and modifiers
  3. @State: data that changes the screen
  4. @Binding and the $ sign
  5. Forms and controls
  6. Lists of data
  7. Navigation: push, sheet and alert
  8. Sharing data between screens: @Observable
  9. Struct vs class (always asked)
  10. When code runs: onAppear and task

How a SwiftUI screen works

A screen is a struct that conforms to View. It has one required property, body, which describes what to show. You never change the screen directly: you change data, and SwiftUI calls body again to redraw.

The smallest useful screen
import SwiftUI

struct WelcomeView: View {
    var body: some View {
        VStack(spacing: 12) {
            Image(systemName: "graduationcap.fill")
                .font(.largeTitle)
                .foregroundStyle(.blue)
            Text("Hello, student!")
                .font(.title)
                .bold()
            Text("Your exam is easier than it looks.")
                .foregroundStyle(.secondary)
        }
        .padding()
    }
}

Try “How a SwiftUI screen works” with live code →

Layout: stacks and modifiers

ContainerArranges childrenThink of it as
VStacktop to bottoma column
HStackleft to righta row
ZStackon top of each otherlayers
Spacer()pushes things aparta spring
VStack inside an HStack: the most common row layout
import SwiftUI

struct ContactRow: View {
    var body: some View {
        VStack(spacing: 16) {
            HStack {
                Image(systemName: "person.crop.circle.fill")
                    .font(.largeTitle)
                    .foregroundStyle(.teal)
                VStack(alignment: .leading) {
                    Text("Riya Sharma")
                        .font(.headline)
                    Text("Class monitor")
                        .foregroundStyle(.secondary)
                }
                Spacer()
                Image(systemName: "phone.fill")
                    .foregroundStyle(.green)
            }
            .padding()
            .background(.gray.opacity(0.15))
            .clipShape(RoundedRectangle(cornerRadius: 14))
            Spacer()
        }
        .padding()
    }
}

Modifier order matters

Each modifier wraps the view so far. .padding().background(.yellow) colours the padding too; .background(.yellow).padding() colours only the text and adds empty space outside.

Same two modifiers, different order, different result
import SwiftUI

struct OrderDemo: View {
    var body: some View {
        VStack(spacing: 30) {
            Text("Padding first")
                .padding()
                .background(.yellow)
            Text("Background first")
                .background(.yellow)
                .padding()
        }
    }
}

Try “Layout: stacks and modifiers” with live code →

@State: data that changes the screen

A view struct can't change its own normal properties. @State gives the view a small piece of storage that SwiftUI keeps outside the struct. When it changes, body runs again and the screen updates.

Starts at 0; in Xcode each tap adds one
import SwiftUI

struct WaterCounter: View {
    @State private var glasses = 0

    var body: some View {
        VStack(spacing: 20) {
            Text("\(glasses) glasses today")
                .font(.title)
            Button("Drink a glass") {
                glasses += 1
            }
            .buttonStyle(.borderedProminent)
            Button("Reset", role: .destructive) {
                glasses = 0
            }
        }
    }
}
If glasses were a plain var (no @State), what happens when you build?
Show the answer

A compile error: Left side of mutating operator isn't mutable: 'self' is immutable. body can't change the struct's own properties.

Try “@State: data that changes the screen” with live code →

@Binding and the $ sign

Controls like TextField and Toggle must both read and write your state. You give them a binding with $: $name means "a two-way link to name", not its value.

You writeYou getUsed for
namethe value ("Asha")showing it: Text(name)
$namea Binding (read + write)editing it: TextField("Name", text: $name)
The Toggle gets $isOn (to write), the Text reads isOn: flip either one
import SwiftUI

struct LampView: View {
    @State private var isOn = false

    var body: some View {
        VStack(spacing: 20) {
            Text(isOn ? "Light is ON" : "Light is OFF")
                .font(.title)
            Toggle("Light", isOn: $isOn)
            Button("Flip it") {
                isOn.toggle()
            }
            .buttonStyle(.bordered)
        }
        .padding()
    }
}

A child view that should edit its parent's state declares @Binding var x, and the parent passes $x. The parent stays the single source of truth.

Parent owns the data with @State; the child edits it through @Binding
struct ParentView: View {
    @State private var isOn = false          // the source of truth
    var body: some View {
        VStack {
            Text(isOn ? "Light is ON" : "Light is OFF")
            LightSwitch(isOn: $isOn)          // pass a binding with $
        }
    }
}

struct LightSwitch: View {
    @Binding var isOn: Bool                  // no default value, no private
    var body: some View {
        Toggle("Light", isOn: $isOn)
    }
}

Try “@Binding and the $ sign” with live code →

Forms and controls

Almost every practical includes a form. Form gives you the grouped iOS settings look for free. Every control takes a binding to a @State value.

Register stays disabled until a name is typed
import SwiftUI

struct RegisterView: View {
    @State private var name = ""
    @State private var year = 2
    @State private var hostel = false
    @State private var branch = "CSE"

    var body: some View {
        Form {
            Section("Student") {
                TextField("Full name", text: $name)
                Text("Hello, \(name)")
                Stepper("Year: \(year)", value: $year, in: 1...4)
                Picker("Branch", selection: $branch) {
                    Text("CSE").tag("CSE")
                    Text("ECE").tag("ECE")
                    Text("ME").tag("ME")
                }
            }
            Section {
                Toggle("Needs hostel", isOn: $hostel)
            }
            Section {
                Button("Register") {
                    print("Registered \(name)")
                }
                .disabled(name.isEmpty)
            }
        }
    }
}
ControlBinding type
TextField, SecureFieldBinding<String>
ToggleBinding<Bool>
Stepper, Slidera number (Int / Double)
Pickerthe type of the .tag values
DatePickerBinding<Date>

Try “Forms and controls” with live code →

Lists of data

List shows rows that scroll. Give it an array, and tell SwiftUI how to tell items apart: either the items are Identifiable (they have an id), or you say id: \.self for simple values like strings.

Simple values: tell List how to tell them apart with id: \.self
import SwiftUI

struct SubjectsView: View {
    var body: some View {
        List {
            ForEach(["Maths", "Physics", "Swift"], id: \.self) { subject in
                Label("\(subject)", systemImage: "book.fill")
            }
        }
    }
}

A list that changes: keep the array in @State, and the buttons edit it. Tap them:

Changing the @State array redraws the list
import SwiftUI

struct TasksView: View {
    @State private var tasks = ["Revise @State", "Build a List"]

    var body: some View {
        VStack {
            Text("\(tasks.count) tasks left")
                .font(.headline)
            List {
                ForEach(tasks, id: \.self) { task in
                    Label("\(task)", systemImage: "checkmark.circle")
                }
            }
            Button("Add task") {
                tasks.append("Practise navigation")
            }
            Button("Clear all") {
                tasks.removeAll()
            }
        }
    }
}

For your own data, make the type Identifiable. This is what you write in the practical:

Identifiable structs in a List
struct Subject: Identifiable {
    let id = UUID()          // a new unique id for every subject
    let name: String
    let icon: String
}

struct SubjectsView: View {
    let subjects = [
        Subject(name: "Maths", icon: "function"),
        Subject(name: "Physics", icon: "atom"),
        Subject(name: "Swift", icon: "swift")
    ]

    var body: some View {
        List(subjects) { subject in            // no id: needed, Subject is Identifiable
            Label(subject.name, systemImage: subject.icon)
        }
    }
}

Try “Lists of data” with live code →

Sharing data between screens: @Observable

When several screens need the same data (a cart, a to-do list), put it in a class marked @Observable. Views that read its properties update automatically when they change.

Create with @State, pass it down as a plain property
import SwiftUI
import Observation

@Observable
class Cart {
    var items: [String] = []
    var count: Int { items.count }
}

struct ShopView: View {
    @State private var cart = Cart()          // the screen that CREATES it uses @State

    var body: some View {
        NavigationStack {
            VStack {
                Text("Items: \(cart.count)")
                Button("Add apple") { cart.items.append("Apple") }
                NavigationLink("View cart") { CartView(cart: cart) }
            }
        }
    }
}

struct CartView: View {
    var cart: Cart                             // just a normal property: it's a class
    var body: some View {
        List(cart.items, id: \.self) { Text($0) }
    }
}
SituationUse
One screen, simple value@State private var
Child edits parent's value@Binding var
Many screens share an object@Observable class, created with @State
Need $ on an observable passed in@Bindable var model
Whole app needs it.environment(model) + @Environment(Model.self)

Try “Sharing data between screens: @Observable” with live code →

Struct vs class (always asked)

A struct is copied when you assign it: two separate values. A class is shared: two names for the same object. Try it:

What does this print?
struct Score { var points = 0 }
class Player { var points = 0 }

var a = Score()
var b = a
b.points = 10

let p = Player()
let q = p
q.points = 10

print(a.points, p.points)
Show the answer
0 10

Try “Struct vs class (always asked)” with live code →

When code runs: onAppear and task

A list pushes a detail screen that has .onAppear { print("detail") }. You open it, go back, and open it again. How many times is "detail" printed?
Show the answer

Twice: onAppear runs every time the view comes on screen, not only the first time.

Try “When code runs: onAppear and task” with live code →

Exam traps

Code or claimWhat really happens
.padding().background(.red) vs .background(.red).padding()First colours the padding too; second only behind the content
var count = 0 then count += 1 in a viewCompile error: self is immutable. Use @State
TextField("Name", text: name)Compile error: needs a binding, $name
@Binding var x = falseWrong: a binding has no default; the parent passes it
List(strings) { }Error: String isn't Identifiable. Add id: \.self
.navigationTitle on the NavigationStackDoes nothing: put it on the view inside
NavigationViewDeprecated: use NavigationStack
Struct copy then change the copyThe original is unchanged
Class copy then change the copyBoth names see the change: same object
Picker tags of a different type than the selectionNothing gets selected

Viva questions and answers

What is SwiftUI?

Apple's declarative UI framework: I describe what the screen should look like for the current data, and SwiftUI updates it when the data changes.

Why are SwiftUI views structs?

They are lightweight descriptions that are cheap to create and copy; SwiftUI rebuilds them often. Structs are value types, so there are no shared-state surprises.

What is @State?

A property wrapper that stores a value owned by the view outside the struct. Changing it makes SwiftUI recompute body.

Difference between @State and @Binding?

@State owns the data (source of truth). @Binding is a two-way reference to data owned by someone else, usually the parent.

What does the $ do?

It gives the projected value of a property wrapper: for @State that is a Binding, so a control can read and write it.

What is some View?

An opaque return type: body returns one concrete view type, which the compiler knows but I don't have to write.

What is a modifier?

A method like .padding() that returns a new view wrapping the old one. Order matters because each wraps the previous result.

Why must items in a List be Identifiable?

SwiftUI needs a stable id to know which row is which when items are added, removed or moved.

Difference between NavigationLink and .sheet?

A link pushes a screen onto the navigation stack with a back button; a sheet slides a separate screen up over the current one.

What is @Observable?

A macro (iOS 17) that makes a class's properties observable, so any view reading them updates when they change.

Struct vs class?

A struct is a value type and is copied; a class is a reference type and is shared. Classes support inheritance; structs don't.

onAppear vs task?

Both run when the view appears; task supports async code and is cancelled automatically when the view disappears.

Quiz

  1. What does some View mean in var body: some View?

    Show the answer

    One specific view type that the compiler knows

    It's an opaque type: one concrete type, hidden from you but known to the compiler.

  2. Which container places views on top of each other?

    Show the answer

    ZStack

  3. Which modifier order puts the yellow colour behind the padding as well as the text?

    Show the answer

    .padding().background(.yellow)

    .padding() first makes the view bigger; .background then fills that bigger view.

  4. Why does a view need @State to change a counter?

    Show the answer

    Because body can't change the struct's own stored properties

  5. What does $name give you when name is @State var name = ""?

    Show the answer

    A Binding<String> that reads and writes name

  6. A child view must edit a Bool owned by its parent. The child declares:

    Show the answer

    @Binding var isOn: Bool

  7. List(names) { Text($0) } where names: [String] fails because…

    Show the answer

    String isn't Identifiable; add id: \.self

  8. Which property makes a struct Identifiable?

    Show the answer

    id

  9. Which is the current way to push a detail screen?

    Show the answer

    NavigationStack + NavigationLink

  10. Where should .navigationTitle("Home") go?

    Show the answer

    On the view inside the NavigationStack

  11. How is a .sheet(isPresented: $show) opened?

    Show the answer

    By setting show = true

  12. Several screens share a shopping cart. The best iOS 17 choice is:

    Show the answer

    An @Observable class created once with @State

  13. var b = a; b.points = 10 where a is a struct with points = 0. What is a.points?

    Show the answer

    0

    Structs are copied on assignment.

  14. Same code, but a is an instance of a class. What is a.points?

    Show the answer

    10

    Classes are shared references: b and a are the same object.

  15. Which runs async work and is cancelled automatically when the view disappears?

    Show the answer

    .task

  16. Which control needs a Binding<Bool>?

    Show the answer

    Toggle

Swift fundamentals →

Practise this lesson interactively →