Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 46 ยท Practice and Interview

Practice: SwiftUI Exercises

Twelve SwiftUI exercises on state, bindings, layout, navigation and data flow, each with a runnable stand-in check and a solution in real SwiftUI code.

Reading about SwiftUI is not the same as thinking in it. This page gives you twelve exercises that train the habits behind every good SwiftUI app: keep one source of truth, derive everything else, let the parent decide sizes, and describe navigation as data.

SwiftUI cannot run in this site's editors, so each exercise has two parts. The stand-in is plain Swift that captures the logic of the problem (a counter that stops at a limit, a layout calculation, a navigation stack) and ends with automatic PASS/FAIL checks you can run. The SwiftUI version is shown as read-only code, so you see how the same idea looks in a real app. Try each exercise yourself first: delete the body of a function in the editor, write your own, and run the checks.

How to work through these

Read the task Know what must be true at the end.
Write your own Blank the function, then type it.
Run the checks Every PASS line is a proof.
Compare Read the SwiftUI version last.
1 / 2

Part 1: State, bindings and layout

Exercise 1: A bounded counter. A counter has a limit. increment() does nothing once the limit is reached, canIncrement says whether the button should be enabled, and reset() returns to zero. In SwiftUI this is a @State value with .disabled(!canIncrement) on the button. Keep the rule in one place so the button and the model never disagree.

Exercise 2: A derived binding. You have a Binding<Int> holding a quantity and a child view that wants a Binding<Bool> ("is anything selected?"). Write map so reading gives count > 0 and writing true/false sets the count to 1 or 0. In real SwiftUI you build it with Binding(get:set:). Revisit @State and @Binding if the projected value $ is still hazy.

Exercise 3: Stack layout math. An HStack of width 300 with spacing 8 holds a fixed 80-point view, a Spacer and a fixed 60-point view. Compute each child's x position and width. A flexible child gets whatever space the fixed ones and the gaps leave over. See how SwiftUI layout works.

Exercise 4: Modifier order. Text("Hi").padding(10).background(.yellow) and Text("Hi").background(.yellow).padding(10) take the same space but paint different areas. Write a function that applies a list of modifiers in order and returns both the final layout size and the size of the background. Details are in view modifiers and their order.

Exercise 5: Diff a list by id. Given the old and new arrays of rows, report which ids were inserted, removed and updated. This is exactly what SwiftUI does with ForEach(items) to animate changes, and it is why ids must be stable (List, ForEach and Identifiable).

Exercise 6: A navigation model. Model the path of a NavigationStack as an array of a Route enum. Support push (ignore it if that route is already on top), pop and popToRoot. In SwiftUI the array is the path binding (NavigationStack).

Swift Exercises 1 to 6: stand-in checks

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 SwiftUI versions of 1 to 4

Swift
struct CounterView: View {
    @State private var value = 0
    let limit = 10

    var body: some View {
        VStack(spacing: 12) {
            Text("\(value)").font(.largeTitle)
            Button("Add") { value += 1 }
                .disabled(value >= limit)
            Button("Reset") { value = 0 }
        }
    }
}

struct SelectionFlag: View {
    @Binding var quantity: Int

    var body: some View {
        let hasSelection = Binding(
            get: { quantity > 0 },
            set: { quantity = $0 ? 1 : 0 }
        )
        Toggle("In cart", isOn: hasSelection)
    }
}

struct Row3: View {
    var body: some View {
        HStack(spacing: 8) {
            Text("Left").frame(width: 80)
            Spacer()
            Text("Right").frame(width: 60)
        }
        .frame(width: 300)
    }
}

struct Chip: View {
    var body: some View {
        VStack {
            Text("Hi").padding(10).background(.yellow)   // yellow includes the padding
            Text("Hi").background(.yellow).padding(10)   // yellow hugs the text
        }
    }
}

Notice that exercise 1 needs no extra state for "disabled": it is computed from value. That is the single-source-of-truth rule in miniature.

Part 2: Data flow and architecture

Exercise 7: A URL router. Turn myapp://item/42 into the path [.list, .detail(42)], myapp://settings into [.settings], and reject any other scheme or unknown host. The result feeds NavigationStack(path:) from an .onOpenURL handler (Deep links).

Exercise 8: Load states. Model a screen with an enum (idle, loading, loaded, failed) instead of three booleans. Write the function that runs a throwing fetch and produces the final state, and one that turns any state into the text the screen shows, including a special message for an empty result.

Exercise 9: A view model with derived data. A task list has a "show completed" toggle and a search query. visible must be computed from the stored inputs, never stored itself.

Exercise 10: Inject a dependency. A greeting depends on the current hour. Put the clock behind a protocol so a test (or a preview) can supply a fixed hour. This is the idea behind the environment and dependency injection.

Exercise 11: Identity and state. SwiftUI keeps @State per view identity. Simulate a storage keyed by id where state exists only while that id is on screen. Switch from view a to view b and back: the counter on a must start from zero again. See view identity and lifecycle.

Exercise 12: Form validation. An email and password form is valid when the email contains exactly one @ with text on both sides and the password has at least 8 characters including a digit. Return a list of messages, and let the submit button depend on that list being empty.

Swift Exercises 7 to 12: stand-in checks

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 SwiftUI versions of 7 to 12

Swift
@Observable
final class TaskListModel {
    var tasks: [TaskItem] = []
    var showCompleted = false
    var query = ""

    var visible: [TaskItem] {
        tasks
            .filter { showCompleted || !$0.isDone }
            .filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
    }
}

struct RootView: View {
    @State private var path: [Route] = []

    var body: some View {
        NavigationStack(path: $path) {
            ListScreen()
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .list: ListScreen()
                    case .detail(let id): DetailScreen(id: id)
                    case .settings: SettingsScreen()
                    }
                }
        }
        .onOpenURL { url in
            if let newPath = route(from: url.absoluteString) { path = newPath }
        }
    }
}

struct ResultsView: View {
    let state: LoadState

    var body: some View {
        switch state {
        case .idle: Text("Pull to load")
        case .loading: ProgressView()
        case .loaded(let items) where items.isEmpty: ContentUnavailableView("No results", systemImage: "magnifyingglass")
        case .loaded(let items): List(items, id: \.self) { Text($0) }
        case .failed(let reason): Text("Failed: \(reason)")
        }
    }
}

struct SignUpForm: View {
    @State private var email = ""
    @State private var password = ""

    var body: some View {
        let messages = problems(email: email, password: password)
        Form {
            TextField("Email", text: $email).textInputAutocapitalization(.never)
            SecureField("Password", text: $password)
            ForEach(messages, id: \.self) { Text($0).foregroundStyle(.red) }
            Button("Create account") { /* submit */ }
                .disabled(!messages.isEmpty)
        }
    }
}

For exercise 11 the real behavior is the same idea with a built-in storage: change .id(...) on a view, or show a different view in the same position, and SwiftUI throws away the old @State.

How to score yourself

Count the exercises where you wrote the function before looking at the solution and every check passed on the first or second run. Ten or more means you are ready for the interview questions. Fewer than eight is a clear sign: reread choosing the right property wrapper and how SwiftUI layout works, then try again from a blank editor.

Two good extensions: add a seventh route to exercise 7 (myapp://item/42/edit) and update the tests first; and change exercise 8 so a second call while loading is ignored (a classic double-tap bug).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the bounded counter, why compute the disabled state from the value instead of storing a separate isDisabled flag?

    Derived data should be derived. One source of truth means the button can never disagree with the counter.
  2. 2. Text('Hi').background(.yellow).padding(10) differs from .padding(10).background(.yellow) because...

    Modifiers wrap the view in order. Background fills the size produced so far, so it either includes the padding or not.
  3. 3. What does a stable id give SwiftUI in a ForEach?

    Identity is how SwiftUI decides that a row is the same row after an update.
  4. 4. Why model a loading screen as one enum instead of isLoading, error and items variables?

    An enum has exactly the states you list, so the screen cannot end up in a contradictory combination.

Summary

  • Keep one source of truth and compute everything derived from it.
  • Layout is negotiation: fixed children take their size, flexible ones share the rest.
  • Modifier order changes what a modifier sees, so read chains from the inside out.
  • Navigation is an array of values, which makes deep links and testing easy.
  • Enums remove impossible UI states; protocols make dependencies replaceable in tests and previews.
  • State belongs to a view's identity, and a changed identity means fresh state.

Next: iOS and SwiftUI Interview Questions