KatInterview

Building a Foreground-Safe Stopwatch with Reliable UI Updates

System DesignModel answer
EasyModel answerSystem Designiosswiftuistate-management

Last 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:

  1. State — what the discrete states are, which single object holds the truth, and how user actions (start, pause, resume, reset) move between states.
  2. 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.
  3. UI updates — how the view learns about changes and why updates must land on the main thread.
  4. Callback ownership — who retains the repeating timer / task, how it is invalidated, and how you avoid duplicate tickers or retain cycles.
  5. 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.