⌁CodeQuestSwiftUI · Term 2
0/8
SECONDARY 2 · INTERACTIVE EDITION

Make your SwiftUI apps
move, connect & recover.

Explore the ideas behind modern apps through live simulations, editable code, predictions, quick checks, and a computational app studio.

YOUR TERM 2 MAP

Four powerful ideas. One connected journey.

01✦

Animation

Implicit and explicit motion, curves, state and game feel.

02◎

Capabilities

Camera, microphone, location, privacy and purpose strings.

03↭

REST APIs

Requests, JSON, Codable, URLSession and live data.

04⌁

Error Handling

throw, try, do-catch and thoughtful debugging.

MISSION OBJECTIVES

By the end, you can…

  • Explain how state changes power SwiftUI animation.
  • Connect app capabilities to privacy and responsible permission requests.
  • Trace how an app requests, decodes and displays API data.
  • Predict, catch and communicate errors without crashing the experience.
  • Sketch a computational app that combines these ideas.
LEARNING PASSPORT

Who is exploring?

Progress is dated and saved only in this browser on this device.

First opened —Latest visit —App sessions 1
How to use this explorer
1 · READ

Study the idea and instructions.

2 · TRY

Change every highlighted control.

3 · OBSERVE

Watch the code and preview update.

4 · EXPLAIN

Answer checks in your own words.

WORLD 1

Animation Playground

Animation is a smooth transition between values. Change the controls, then connect what you see to the SwiftUI code.

✦
LEARN FIRST · WHAT IS ANIMATION?

Animation smoothly changes a view property—such as scale, position, rotation or opacity—from one value to another. The changing value is usually stored in @State.

AUTOMATIC

Implicit animation

Attach .animation(..., value:) to a view. SwiftUI watches the chosen value and animates whenever it changes.

Best for:

continuous or automatic effects such as pulsing stars, spinning coins and loading indicators.

EVENT-DRIVEN

Explicit animation

Wrap a state change inside withAnimation { }. Only the changes in that action are animated.

Best for:

button taps and gestures such as launching a rocket, moving a target or flipping a card.

linearSame speed from start to finish
easeInOutStarts slowly, speeds up, then slows down
springOvershoots and bounces like a physical object
Explore beside Swift PlaygroundsUse Split View. First test the Pulsing Star here. Then tap Copy complete code, paste it into ContentView.swift, press Run, and compare the real SwiftUI animation with this simulation.
MOTION CONTROLS

Design the collectible

APP PREVIEW
★

Implicit animation watches isPulsing

Complete ContentView.swift● LIVE CODE
Observe it

Because this is implicit, the modifier watches a value and animates automatically whenever that value changes.

QUICK CHECK · ANIMATION

A character should jump only when the player taps a button. Which approach gives precise control over when it moves?

MASTER VOCABULARY
AnimationA smooth visual change between view values.
Implicit animationA view modifier that automatically watches a value.
Explicit animationA state change deliberately placed inside withAnimation.
Animation curveThe timing or physics of motion.
onAppearRuns code when a view appears.
@StateStores changing data owned by a view.
WORLD 2

Capabilities & Purpose Strings

Software must ask before it reaches beyond its sandbox. Build the two-part permission handshake.

◎
THEORY · CAPABILITIES AND PURPOSE STRINGS

Writing code is not enough

To use hardware in Swift Playgrounds, an app completes a two-step handshake:

  1. Configuration step — Capabilities & Info.plist: Declare the hardware feature in App Settings and provide a purpose string explaining why it is needed.
  2. Code step — Authorization request: Write Swift code that shows the system permission popup so the user can choose Allow or Deny.

Privacy rule: Request access only when the feature is needed. A user’s denial must be respected.

CapabilityFrameworkPurpose String KeyExample Purpose String
CameraAVFoundationNSCameraUsageDescription“We need the camera so you can take a profile picture.”
MicrophoneAVFoundationNSMicrophoneUsageDescription“We need the microphone to record your voice notes.”
LocationCoreLocationNSLocationWhenInUseUsageDescription“We need your location to show nearby restaurants.”
Photo LibraryPhotosUINSPhotoLibraryUsageDescription“We need access to save your edited artwork.”
1

Configure

Add the capability and a clear purpose string in App Settings.

→
2

Request

Use the correct framework and authorization code.

→
3

Respond

Show a helpful UI for allowed, denied or undetermined states.

PERMISSION BUILDER

Choose a capability

SYSTEM PERMISSION SIMULATION
📷

Camera Demo

Waiting to ask…

“CodeQuest” Would Like to Access the Camera

We need your camera so you can scan a code.

App Settings + complete ContentView.swift
QUICK CHECK · PRIVACY

The code requests camera access, but the developer forgot the purpose description. What is the serious problem?

MASTER VOCABULARY
CapabilityA hardware or software feature an app is allowed to use.
Info.plistThe configuration file that stores privacy descriptions and settings.
Purpose StringA clear explanation of why permission is needed.
AVFoundationApple’s framework for camera, microphone, audio and video.
CoreLocationApple’s framework for GPS and location services.
SandboxSecurity isolation that prevents unapproved access.
WORLD 3

REST API Mission Control

Follow the journey from a user request to live data on the screen—without freezing the interface.

↭
LEARN FIRST · WHAT IS AN API?

API means Application Programming Interface

An API (Application Programming Interface) is a software messenger that allows two different computer systems to communicate. A REST API follows web-based rules: your app sends a request to an endpoint, and a server returns a response, often as JSON. Swift uses Codable and JSONDecoder to translate that JSON into Swift data.

Restaurant analogyClient: customer placing the orderAPI: waiter carrying the requestServer: kitchen preparing the dataResponse: completed order returned to the client

Before coding: In App Settings, enable Outgoing Network Connections so the app can act as a client.

→ Request →→ Response →→ JSON →
Client

Your SwiftUI app is the customer. It asks for information through an endpoint.

API PLAYGROUND

Choose the data

LIVE-DATA SIMULATION

Ready to connect

Send a request and observe each stage.

Complete Swift Playgrounds example · model, request, decoding and preview
JSON → CODABLE

Match the translator

Tap one of the purple JSON key buttons below. Its matching Swift property will light up on the right.

Swift model

Choose a key to see how JSONDecoder matches the spelling and data type.

QUICK CHECK · ASYNC

Why should a slow network request not run as blocking work on the main thread?

MASTER VOCABULARY
APIA software intermediary that lets applications communicate.
EndpointThe URL where an API receives requests.
JSONA lightweight text format for exchanging data.
URLSessionSwift’s tool for sending network requests.
CodableA protocol that helps translate JSON and Swift types.
AsynchronousWork that runs without freezing the interface.
WORLD 4

Crash-Proof Debug Lab

Good code anticipates failure, explains the problem and gives the user a safe next step.

⌁
LEARN FIRST · THE ANATOMY OF AN ERROR
BEFORE RUNNING

Compile-time error

A syntax or spelling mistake detected by Swift before the app can run—for example, a missing brace or typing Buton.

WHILE RUNNING

Runtime error

An unexpected problem during use—for example, lost Wi-Fi, a missing file or invalid input. Without handling, it may crash the app.

Swift’s safety net is do-catch: a function marked throws can throw an error; the caller uses try; and catch provides a safe response.

ErrorDefines what can go wrong
throwTriggers a specific error
throwsWarns that a function may fail
tryCalls throwing code
do-catchAttempts and safely handles
KITCHEN ORDER SIMULATOR

Test every condition

Debug Console●
  1. Ready. Change a condition, then submit.
🍲

Ready to order

The safety net is waiting.

Safe pattern
do {
    try submitOrder()
    message = "Order sent!"
} catch OrderError.kitchenClosed {
    message = "Kitchen is closed."
} catch {
    message = "Something went wrong."
}
Complete Kitchen Order example
import SwiftUI

enum OrderError: Error {
    case outOfStock
    case kitchenClosed
}

struct ContentView: View {
    @State private var message = "Ready to Order"
    @State private var itemsInStock = 1
    @State private var isKitchenOpen = true

    func submitOrder() throws {
        if !isKitchenOpen {
            throw OrderError.kitchenClosed
        }
        if itemsInStock == 0 {
            throw OrderError.outOfStock
        }
        itemsInStock -= 1
    }

    var body: some View {
        VStack(spacing: 30) {
            Text("Soto Order System")
                .font(.largeTitle)
                .bold()
            Text(message)
                .multilineTextAlignment(.center)

            Toggle("Kitchen is open", isOn: $isKitchenOpen)

            Button("Submit Order to Kitchen") {
                do {
                    try submitOrder()
                    message = "Success! Order sent to the kitchen."
                } catch OrderError.kitchenClosed {
                    message = "The kitchen is currently closed."
                } catch OrderError.outOfStock {
                    message = "This item is sold out."
                } catch {
                    message = "An unknown error occurred."
                }
            }
            .buttonStyle(.borderedProminent)
        }
        .padding()
    }
}
QUICK CHECK · ERROR HANDLING

Why is an empty catch block harmful?

MASTER VOCABULARY
ExceptionAn unexpected event while a program runs.
do-catchA safety structure for code that may throw.
try?Returns nil instead of crashing when an error occurs.
try!Forces success and crashes if the promise is wrong.
BreakpointPauses execution so values can be inspected.
print()Writes checkpoints to the debug console.
BUILD BRIDGE

Computational App Studio

Combine one input, one computation and one useful output. This is a small taste of planning a complete app.

▦
InstructionsEdit every field. Observe the app card and pseudocode change. Test at least two different user situations, including one failure or boundary case.
NEW IDEA · PSEUDOCODE

Plan the logic before writing Swift

Pseudocode is a plain-language plan for an algorithm. It is not real Swift code, so it does not need exact punctuation. It should show the order of the input, decision/process and output.

START
GET the weather temperature
IF temperature is above the safety limit
    SHOW “Choose an indoor activity”
ELSE
    SHOW “Conditions are suitable”
END IF
END

Use clear action words such as GET, SET, CALCULATE, IF, ELSE, SHOW and REPEAT.

APP BLUEPRINT

Shape your idea

PROTOTYPE PREVIEW
◉SMART COMPANION

SafeTrip

Help a traveller decide whether conditions are safe.

YOUR RESULTSafety recommendationBased on live weather data
Live pseudocode blueprint● LIVE PLAN
TEST YOUR APP IDEA

Predict how your app should respond

Imagine that the app has already been created. Test it with two sample situations. Record the input, the expected output and what the app should do if something goes wrong.

CHALLENGE ARCADE

Serious thinking. Playful missions.

Complete a mix of prediction, matching, debugging and design decisions.

◆
CURRENT ATTEMPTAttempt 1

Your first answer is final. Read carefully before selecting.

CHALLENGE SCORE0 / 20

Twenty varied missions are waiting.

SCORE PROGRESS

From first attempt to mastery

A score of 16/20 or higher is marked as Mastered.

MISSION REPORT

Your CodeQuest Summary

Your report records what you actually tried—not only what you marked complete.

Student —Class —First opened —Latest visit —App sessions 0
0%exploration
EXPLORATION EVIDENCE

Journey in progress

Complete the worlds and interact with their controls to build evidence.

DATED CHALLENGE RECORD

Score progress

RECORDED RESPONSES

Quick Checks and Written Thinking

Answers completed before this reporting update may need to be selected once more. Existing scores and completion remain saved.

CHALLENGE ANSWERS

Latest submitted attempt

FINAL REFLECTION

Look ahead to Term 2

1

Save or print your summary as PDF.
Save it first inside your ComputerScience folder. On iPad: Share/Print → pinch out the preview → Share → Save to Files.

2

Rename the file:
Name_sec2FaithCodeQuest.pdf
Replace Name with your complete name.

3

Submit using your school email.
Open your class’s CodeQuest folder. Create a folder using your complete name, set General access to Restricted, share it only with your teacher’s school email, and make your teacher an Editor. Upload your PDF inside your folder.