A quiz is a small state machine. At any moment the app is showing one question, waiting for an answer, showing feedback, or showing the final score. If you write the rules in one place, the screen becomes easy. If you scatter them across buttons, you get bugs such as scoring twice when a user taps fast. This project puts every rule in a QuizEngine class and keeps the view free of logic.
Because the engine is a plain @Observable class with no UI code, the tests can play a full game in a few lines. This is the same separation you used for the calculator, applied to a game.
Concepts in this project
- A state machine: current question, selected answer, score and finished are enough to describe the whole game.
- private(set): the view can read
scoreandindexbut only the engine can change them. - Guarding rules:
chooseignores a second tap, andnextdoes nothing before an answer. - Feedback colours: green for the right answer, red for the chosen wrong answer, grey for the rest.
- ProgressView: shows how far through the quiz the user is.
- Shuffling on restart:
questions.shuffle()gives a new order each time.
Create the project
- In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product SwiftQuiz.
- Delete the default ContentView.swift and the default @main file, then add the files below.
SwiftQuiz/
QuizApp.swift @main
Question.swift model and sample questions
QuizEngine.swift rules and score
QuizView.swift question, feedback, result
SwiftQuizTests/
QuizTests.swift
The code
`Question.swift`
import Foundation
struct Question: Identifiable, Equatable {
let id = UUID()
let text: String
let options: [String]
let answerIndex: Int
let explanation: String
}
enum SampleQuestions {
static let all: [Question] = [
Question(text: "Which keyword makes a constant in Swift?",
options: ["let", "var", "const"],
answerIndex: 0,
explanation: "let makes a value that cannot be reassigned. var makes one that can."),
Question(text: "What does an optional such as String? hold?",
options: ["A String or nil", "Always a String", "Only numbers"],
answerIndex: 0,
explanation: "An optional is either a value or nil, and Swift makes you handle both."),
Question(text: "Which property wrapper stores state owned by a SwiftUI view?",
options: ["@State", "@Published", "@Model"],
answerIndex: 0,
explanation: "@State keeps a value that the view owns and redraws when it changes."),
Question(text: "What is the difference between a struct and a class?",
options: ["Structs are copied, classes are shared", "Structs cannot have functions", "There is none"],
answerIndex: 0,
explanation: "Structs are value types and are copied. Classes are reference types and are shared."),
Question(text: "Which call starts an async function?",
options: ["await", "async let only", "defer"],
answerIndex: 0,
explanation: "You call an async function with await, inside an async context such as a Task.")
]
}
`QuizEngine.swift`
import Foundation
import Observation
@Observable
final class QuizEngine {
private(set) var questions: [Question]
private(set) var index = 0
private(set) var score = 0
private(set) var selected: Int?
init(questions: [Question] = SampleQuestions.all) {
self.questions = questions
}
var current: Question? {
index < questions.count ? questions[index] : nil
}
var isFinished: Bool { index >= questions.count }
var hasAnswered: Bool { selected != nil }
// The first tap counts. Later taps on the same question are ignored.
func choose(_ option: Int) {
guard let question = current, selected == nil else { return }
selected = option
if option == question.answerIndex { score += 1 }
}
func next() {
guard selected != nil else { return }
selected = nil
index += 1
}
func restart() {
questions.shuffle()
index = 0
score = 0
selected = nil
}
}
`QuizView.swift`
import SwiftUI
struct QuizView: View {
@State private var engine = QuizEngine()
var body: some View {
NavigationStack {
Group {
if let question = engine.current {
questionView(question)
} else {
finishedView
}
}
.padding()
.navigationTitle("Swift Quiz")
}
}
private func questionView(_ question: Question) -> some View {
VStack(alignment: .leading, spacing: 16) {
ProgressView(value: Double(engine.index), total: Double(engine.questions.count))
Text("Question \(engine.index + 1) of \(engine.questions.count)")
.font(.caption)
.foregroundStyle(.secondary)
Text(question.text)
.font(.title3.bold())
ForEach(question.options.indices, id: \.self) { option in
Button {
engine.choose(option)
} label: {
HStack {
Text(question.options[option])
Spacer()
if engine.hasAnswered {
if option == question.answerIndex {
Image(systemName: "checkmark.circle.fill")
} else if option == engine.selected {
Image(systemName: "xmark.circle.fill")
}
}
}
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.tint(tint(for: option, in: question))
.disabled(engine.hasAnswered)
}
if engine.hasAnswered {
Text(question.explanation)
.font(.callout)
.padding(.top, 4)
Button(engine.index + 1 == engine.questions.count ? "See result" : "Next") {
engine.next()
}
.buttonStyle(.borderedProminent)
}
Spacer()
}
}
private var finishedView: some View {
VStack(spacing: 16) {
Spacer()
Text("You scored \(engine.score) out of \(engine.questions.count)")
.font(.title2.bold())
Button("Play again") { engine.restart() }
.buttonStyle(.borderedProminent)
Spacer()
}
}
private func tint(for option: Int, in question: Question) -> Color {
guard engine.hasAnswered else { return .blue }
if option == question.answerIndex { return .green }
if option == engine.selected { return .red }
return .gray
}
}
`QuizApp.swift`
import SwiftUI
@main
struct QuizApp: App {
var body: some Scene {
WindowGroup {
QuizView()
}
}
}
`QuizTests.swift (in the tests target)`
import Testing
@testable import SwiftQuiz
struct QuizTests {
private let two = [
Question(text: "One?", options: ["a", "b"], answerIndex: 0, explanation: ""),
Question(text: "Two?", options: ["a", "b"], answerIndex: 1, explanation: "")
]
@Test func correctAnswerScores() {
let engine = QuizEngine(questions: two)
engine.choose(0)
#expect(engine.score == 1)
}
@Test func secondTapIsIgnored() {
let engine = QuizEngine(questions: two)
engine.choose(1) // wrong
engine.choose(0) // would be right, but too late
#expect(engine.score == 0)
}
@Test func mustAnswerBeforeNext() {
let engine = QuizEngine(questions: two)
engine.next()
#expect(engine.index == 0)
}
@Test func finishesAfterLastQuestion() {
let engine = QuizEngine(questions: two)
engine.choose(0)
engine.next()
engine.choose(1)
engine.next()
#expect(engine.isFinished)
#expect(engine.score == 2)
}
}
Walkthrough
Question holds the text, the options, the index of the right option and a short explanation. Storing the answer as an index keeps the data small. The sample questions are plain Swift code, so you can see the shape of the data and replace it with your own or load it from JSON later.
QuizEngine marks its properties private(set). That is a useful habit: the view can show the score but cannot change it, so every change goes through choose, next or restart. In choose, the first guard returns if there is no current question or if an answer is already selected. That single line is what prevents double scoring.
next also begins with a guard. Without a selected answer it does nothing, so the Next button cannot skip a question even if the view has a bug. This is defensive design: the engine protects its own rules instead of trusting the screen.
The view uses an optional: if let question = engine.current. When the quiz is over, current is nil and the finished screen appears. This is a clean way to model two screens from one piece of state. The option buttons are disabled after an answer, and their tint comes from one small function that looks at the selected and correct indexes.
The four tests describe the rules as sentences: a correct answer scores, a second tap is ignored, Next needs an answer, and the quiz finishes after the last question with the right score. If you ever change the engine, these tests tell you at once whether a rule broke.
How it works
- The view asks the engine for
current. If there is a question it draws it, otherwise it draws the result. - A tap calls
choose. The engine records the answer and adds to the score if it is right. - The view sees
hasAnswered, colours the buttons, shows the explanation and offers Next. - After the last question,
isFinishedbecomes true and the score screen appears. Play again shuffles and resets.
Expected output
The first screen shows a progress bar, "Question 1 of 5" and three buttons. Tap the right one: it turns green with a check mark, the others turn grey, an explanation appears and a Next button shows. Tap a wrong answer on another question: it turns red and the right one turns green. After five questions you see "You scored 4 out of 5" (your number will vary) and a Play again button. All four tests pass.
Your task
- Build the app and answer all five questions.
- Add five questions of your own about a topic you know.
- Load the questions from a JSON file in the app bundle with Codable.
- Add a timer for each question and treat running out of time as a wrong answer.
How to check it worked
- A second tap on an answer does not change the score.
- Next does nothing before an answer is chosen.
- The final score matches the number of correct answers.
Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.