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
- Read any small SwiftUI screen and say what it shows
- Pick the right tool:
@State,@Bindingor@Observable - Build the classic practical app: a form, a list and a detail screen
- Answer the most common viva questions in one or two sentences
Contents
- How a SwiftUI screen works
- Layout: stacks and modifiers
- @State: data that changes the screen
- @Binding and the $ sign
- Forms and controls
- Lists of data
- Navigation: push, sheet and alert
- Sharing data between screens: @Observable
- Struct vs class (always asked)
- 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.
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()
}
}struct WelcomeView: View: a view is a value type (struct), cheap to create and throw away.var body: some View:some Viewmeans "one specific view type, the compiler knows which". You don't have to write the long real type.Image(systemName:)shows an SF Symbol, Apple's built-in icon set..font,.bold(),.padding()are modifiers: each returns a new, changed view.
Layout: stacks and modifiers
| Container | Arranges children | Think of it as |
|---|---|---|
VStack | top to bottom | a column |
HStack | left to right | a row |
ZStack | on top of each other | layers |
Spacer() | pushes things apart | a spring |
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.
import SwiftUI
struct OrderDemo: View {
var body: some View {
VStack(spacing: 30) {
Text("Padding first")
.padding()
.background(.yellow)
Text("Background first")
.background(.yellow)
.padding()
}
}
}@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.
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
}
}
}
}- Mark it
private: the state belongs to this view only. - Use
@Statefor simple values this one screen owns: numbers, text, true/false. - Without
@State,glasses += 1doesn't even compile: "self is immutable".
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.
@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 write | You get | Used for |
|---|---|---|
name | the value ("Asha") | showing it: Text(name) |
$name | a Binding (read + write) | editing it: TextField("Name", text: $name) |
$isOn (to write), the Text reads isOn: flip either oneimport 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.
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)
}
}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.
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)
}
}
}
}| Control | Binding type |
|---|---|
TextField, SecureField | Binding<String> |
Toggle | Binding<Bool> |
Stepper, Slider | a number (Int / Double) |
Picker | the type of the .tag values |
DatePicker | Binding<Date> |
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.
id: \.selfimport 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:
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:
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)
}
}
}Identifiable= the type has anidproperty that is unique.UUID()makes a new unique id.List(items) { item in ... }builds one row per item.ForEachdoes the same inside any container.- To delete rows:
ForEach(...) { }.onDelete { offsets in items.remove(atOffsets: offsets) }, and the array must be@State.
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:
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
- SwiftUI views are structs: cheap, copied, recreated often.
- Shared, changing data (the
@Observablemodel) is a class. leton a class still lets you change itsvarproperties;leton a struct does not.
When code runs: onAppear and task
.onAppear { }: runs when the view appears on screen. Good for setting up or logging..task { }: likeonAppearbut forasyncwork (loading data); it's cancelled automatically when the view goes away..onDisappear { }: when the view leaves the screen..onChange(of: value) { }: runs when a value changes.
.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.
Exam traps
| Code or claim | What 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 view | Compile error: self is immutable. Use @State |
TextField("Name", text: name) | Compile error: needs a binding, $name |
@Binding var x = false | Wrong: a binding has no default; the parent passes it |
List(strings) { } | Error: String isn't Identifiable. Add id: \.self |
.navigationTitle on the NavigationStack | Does nothing: put it on the view inside |
NavigationView | Deprecated: use NavigationStack |
| Struct copy then change the copy | The original is unchanged |
| Class copy then change the copy | Both names see the change: same object |
Picker tags of a different type than the selection | Nothing 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
What does
some Viewmean invar 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.
Which container places views on top of each other?
Show the answer
ZStack
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;.backgroundthen fills that bigger view.Why does a view need
@Stateto change a counter?Show the answer
Because
bodycan't change the struct's own stored propertiesWhat does
$namegive you whennameis@State var name = ""?Show the answer
A
Binding<String>that reads and writesnameA child view must edit a Bool owned by its parent. The child declares:
Show the answer
@Binding var isOn: BoolList(names) { Text($0) }wherenames: [String]fails because…Show the answer
String isn't Identifiable; add
id: \.selfWhich property makes a struct
Identifiable?Show the answer
idWhich is the current way to push a detail screen?
Show the answer
NavigationStack+NavigationLinkWhere should
.navigationTitle("Home")go?Show the answer
On the view inside the
NavigationStackHow is a
.sheet(isPresented: $show)opened?Show the answer
By setting
show = trueSeveral screens share a shopping cart. The best iOS 17 choice is:
Show the answer
An
@Observableclass created once with@Statevar b = a; b.points = 10whereais a struct withpoints = 0. What isa.points?Show the answer
0
Structs are copied on assignment.
Same code, but
ais an instance of a class. What isa.points?Show the answer
10
Classes are shared references:
bandaare the same object.Which runs async work and is cancelled automatically when the view disappears?
Show the answer
.taskWhich control needs a
Binding<Bool>?Show the answer
Toggle