Building a Foreground-Safe Stopwatch with Reliable UI Updates
System DesignModel answerLast updated
Design a small iOS stopwatch/SwiftUI app with a clear state machine, clock-derived elapsed time, main-thread updates, and sensible lifecycle handling.
You are asked to sketch the architecture of a tiny timer app for iOS. The product type is deliberately underspecified — say clearly whether you are building a stopwatch, a countdown, or an interval timer, and then design for that one.
Use Swift with either SwiftUI or UIKit (pick one and stay consistent). The exercise is a discussion and whiteboard-style implementation, not a runnable judge.
Your design must address, in concrete terms:
- State — what the discrete states are, which single object holds the truth, and how user actions (start, pause, resume, reset) move between states.
- Time representation — how elapsed or remaining time is computed, why you do not trust the firing cadence of a repeating timer, and how you keep the display accurate when callbacks arrive late or are skipped.
- UI updates — how the view learns about changes and why updates must land on the main thread.
- Callback ownership — who retains the repeating timer / task, how it is invalidated, and how you avoid duplicate tickers or retain cycles.
- Lifecycle — behavior when the app is backgrounded, when the device sleeps, when the view is recreated, and whether state should survive process termination.
State the trade-offs you make. Ambiguities you should resolve before coding: which actions are required, whether backgrounded time counts, whether state must be persisted across launches, and the required display precision (tenths vs. whole seconds) and what to show when ticks are delayed.
Hints
Hint 1
Compute elapsed time from a monotonic clock reading (start date vs. now) rather than accumulating tick deltas — scheduled timers drift and can coalesce.
Hint 2
Treat the ticker purely as a repaint trigger, not as the source of truth; invalidate it whenever you leave the running state so you never have two tickers alive.
Hint 3
Derive everything from one state enum plus start/pause timestamps, so a background→foreground transition needs only a single repaint.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
I'll build a stopwatch in SwiftUI with Swift, since that combination keeps the state and view code compact and makes threading explicit.
Clarified scope. Actions: start, pause (freeze), resume, and reset. Elapsed time keeps counting while the app is backgrounded or the device sleeps, because users expect a stopwatch to measure wall-clock work time. Display precision: tenths of a second. No persistence across process termination — a relaunch starts at zero; if that were required I'd snapshot the running state and timestamps to UserDefaults. No notifications for now.
State machine. One observable model is the single source of truth. Two stored fields define it:
elapsedBeforeStart: TimeInterval— time accumulated in prior run segments.segmentStart: Date?— non-nil iff running.state: enum { idle, running, paused }— derived, but stored explicitly for readability.
Transitions:
startfrom idle orresumefrom paused:segmentStart = now, state = running, start the ticker.pausefrom running:elapsedBeforeStart += now - segmentStart!,segmentStart = nil, state = paused, stop the ticker.reset: zero both fields, state = idle, stop the ticker.
Guarding each transition so that a duplicate tap (e.g., two start calls) is a no-op avoids the classic double-ticker bug.
Time representation. The key decision: never accumulate tickInterval per callback. A repeating timer coalesces, drifts, and can be delayed by a long main-thread frame; accumulating deltas would slowly lose or gain time. Instead, elapsed is always computed:
var elapsed: TimeInterval {
elapsedBeforeStart + (segmentStart.map { Date().timeIntervalSince($0) } ?? 0)
}
The ticker exists only to repaint. For monotonicity I'd prefer a clock that does not jump on wall-clock adjustments — ContinuousClock / SuspendingClock or CACurrentMediaTime() — so a user changing the system time mid-run cannot move the display backwards. For a discussion answer, Date is acceptable provided I note the wall-clock caveat.
UI updates. In SwiftUI the model is @MainActor @Observable (or ObservableObject), so both the state mutation and the ticker's repaint run on the main actor; a Timer.publish/AsyncStream or a Task loop hops back via the main queue before touching elapsed. The publisher in the timer callback is where an unstructured background thread would corrupt the display, so I keep the invalidation of timer and state on the same actor — that also makes pause/reset race-free. For UIKit the equivalent is a view controller that owns the model and calls label.text = ... on DispatchQueue.main.
Tick rate. A stopwatch showing tenths needs repaints at roughly 10 Hz, but a display refresh at 60 Hz would be wasteful. A 0.1 s repeating timer is fine; since accuracy lives in the clock computation, a late tick costs a slightly stale frame, not accumulated error, and the next tick self-corrects. I can also tick at a higher rate for no visual benefit — there's no reason to.
Callback ownership. The model owns the ticker. On entering running it creates it; on every exit path (pause, reset) it invalidates or cancels it. I keep the ticker reference optional and idempotent: stopTicker() sets it to nil and cancellation happens first. The ticker closure captures the model weakly (or, with a Task, the Task is stored and cancelled) — capturing self strongly in a repeating timer would keep the model alive forever.
Lifecycle. Backgrounding does not stop the model; the ticker simply stops firing (iOS suspends timers), which is harmless because elapsed is derived. On .active (scene phase change) or viewWillAppear, I stop and restart the ticker if running, and repaint once — the display jumps to the correct value rather than showing the value at suspension. View recreation in SwiftUI (onAppear/onDisappear) is handled the same way: the model lives outside the transient view (@StateObject / an injected object), so no state is lost. If backgrounding must instead behave like an automatic pause, the .inactive/.background transition does exactly the same work as the pause path.
Mistakes I'd call out. Accumulating tick deltas (drift), mutating observable state off the main thread (crashes or ignored updates), letting start idempotency slip (two tickers, doubled speed), forgetting to invalidate on pause (battery drain, stale repaints), and assuming appDidEnterBackground fires when the device simply locks — which argues again for deriving time rather than counting it.
Complexity is constant per tick and O(1) per transition; the correctness win comes from one authoritative clock-derived value and one owning actor.