SwiftPumpkin

Interview prep

Architecture questions, by priority

Open a question only after you've answered it in your head.

What every answer should cover

  1. What's the essential complexity here, and what would be accidental?
  2. What does each choice cost, and what won't you build yet?
  3. Who owns the state?
  4. What is the source of truth?
  5. Which dependencies are abstracted?
  6. How do changes propagate to the UI?
  7. What survives process termination?
  8. What happens when operations fail halfway through?
  9. How do you test and evolve this system?

How answers sound at each level

WeakNames a pattern and a slogan: "MVVM, because separation of concerns."
SeniorAsks about the team and lifespan, picks a structure, names its cost.
StaffSeparates domain, runtime, team and evolution scale; contains the essential complexity even with a small team; adds seams only where change is likely; says what it won't build yet.

P0 · Architecture, prepare first

Why does UIKit MVC struggle at scale?They want: Massive ViewControllers, lifecycle coupling, testability
  • UIViewController already owns lifecycle, the view hierarchy, layout and interaction handling.
  • MVC adds presentation logic, business orchestration and navigation to the same class, so it becomes the bottleneck everything flows through.
  • The symptoms are 1,500-line controllers, logic tied to viewDidLoad and viewWillAppear timing, code you can't test without UIKit, merge conflicts and navigation wired through prepare(for:).
  • Still, a 1,500-line controller is a signal to investigate rather than proof that a specific architecture is needed.
  • Before converting to MVVM, isolate pure logic, side effects and cohesive UI components, then add a ViewModel or router where churn and risk justify the extra indirection.

Study: MVC

Compare MVC, MVVM and VIPER. When would you choose each?They want: Responsibility boundaries, data flow, complexity
  • In MVC the controller mediates between model and view and tends to own everything.
  • In MVVM the view binds to state a ViewModel exposes, so presentation logic is testable without UIKit.
  • VIPER adds explicit view contracts and splits business orchestration (Interactor) from presentation (Presenter), with a Router for navigation.
  • MVVM with a router is my production default; MVC is the exception, for thin static screens like Settings.
  • Reach for VIPER when business rules and UI change on independent axes (pricing, eligibility, privacy rules), multiple data sources need orchestration, or a complex UIKit flow like a contact picker or checkout needs strict independent testing.
  • On a CRUD or display screen, VIPER is pure ceremony, so skip it.

Study: MVC MVVM (+ Router) VIPER

How do you prevent Massive ViewModels?They want: Interactors, use cases, service abstractions
  • Diagnose why the ViewModel bloated before splitting it, because different causes need different cuts.
  • Domain orchestration and business rules belong in interactors or use cases, data access in repositories behind protocols, navigation in a router, and derived formatting in small pure types.
  • Large multi-region screens need child ViewModels per region rather than one giant model.
  • Slapping VIPER onto a ViewModel bloated by UI formatting just scatters the same mess across five files.
  • The real warning sign is multiple independent reasons to change, or a test requiring database, network and analytics stubs.
  • Each split adds a type and indirection, so extract only along a real axis of change.

Study: MVVM (+ Router) VIPER

How do you implement navigation independently of screens?They want: Router, Coordinator, deep linking
  • Screens report intent through a closure or delegate ("user picked a contact") and never construct or push the next screen.
  • A router or coordinator owns construction and transitions, modeling destinations as a Route enum so deep links build the right stack.
  • In SwiftUI the router owns a NavigationStack path.
  • Back-swipe and interactive dismissal bypass finish callbacks unless you observe the navigation controller delegate.
  • In production, also handle deferred deep links across login, modal collisions where UIKit drops a present over an active sheet, and async route lookups before pushing.
  • Inject the router protocol so tests verify routes without UIKit.
  • The cost is another object per flow and lifecycle bookkeeping, so skip coordinators on a simple list-to-detail screen.

Study: Coordinator / Routing

How would you architect a large iOS application from scratch?They want: Feature modules, layering, dependency graph
  • Separate domain complexity, runtime scale, team structure and evolution first; MVVM versus VIPER only settles presentation.
  • Size the graph to the team: a pair can ship SwiftUI with @Observable models; a single team wants MVVM with injected dependencies and routers; several teams need feature packages split into interface and implementation modules wired at a composition root.
  • Enforce boundaries with the module graph rather than wiki pages.
  • Watch the year-two failure modes: a shared CoreInterfaces module can bloat into a monolith that triggers full rebuilds on every PR, and one giant composition root becomes a merge bottleneck.
  • Split interfaces by domain, decentralize screen creation through feature factories, and skip physical modules until ownership or build pain earns the setup cost.

Study: Feature Modules Decoupled Layers Dependency Injection

Three engineers are building a chat app. What architecture do you choose?They want: Essential vs accidental complexity, team size vs domain
  • Team size isn't the whole story: chat has real domain complexity (offline sends, ordering, persistence, delivery guarantees, live updates) no matter how small the team.
  • I'd use MVVM for presentation, keep messaging and sync logic out of the UI, and put protocols around storage, networking and any vendor SDK.
  • What I wouldn't add without a concrete reason: VIPER everywhere, dozens of packages, a use-case type per operation.
  • Start with logical boundaries and promote them to physical modules when ownership, build times or enforcement demand it.
  • A small team is a reason to cut accidental complexity, not to ignore essential complexity.
  • The cost is a few protocols and some up-front wiring, which is cheap next to a message-ordering bug in production.

Study: MVVM (+ Router) Repository Decoupled Layers

How would you migrate a legacy MVC application to MVVM?They want: Incremental migration, regression prevention
  • Don't mechanically convert view controllers into MVVM.
  • First add characterization tests around critical journeys and map churn, async races and shared mutable state.
  • Extract in lowest-risk order: pure computation and validation, then networking and persistence side effects, then cohesive UI components, then presentation state into a ViewModel, and finally navigation into a coordinator if justified.
  • Treat that sequence as a default: if database queries stall the main thread, isolate persistence first; if five engineers collide on one controller, split feature boundaries first; if async callbacks race, fix state ownership first.
  • Leave stable screens alone and ship risky cuts behind feature flags.
  • The cost is mixed patterns mid-migration, which beats a risky rewrite.

Study: MVC MVVM (+ Router)

How do you manage shared state across multiple screens?They want: Source of truth, observation, consistency
  • Separate persisted domain truth from ephemeral cross-screen UI state such as drafts, selection or optimistic writes in flight.
  • Give each piece one owner at the right scope: a database or session store, never mutable copies passed between view controllers.
  • Writes go through one API so invariants stay in one place, and screens observe value snapshots via @Observable, Combine or database change notifications.
  • Watch observation fan-out at scale: five screens observing raw tables can trigger main-thread query storms unless you scope queries and debounce or project reads.
  • The cost is an observation layer and write discipline; the alternative is tabs that quietly disagree.

Study: State Management Repository

How do you decouple features from databases and networking?They want: Protocols, repositories, dependency inversion
  • Features depend on domain protocols rather than Core Data, SQLite or URLSession.
  • Repositories in a data module implement those ports and map DTOs and storage records into plain domain structs at the boundary, while the composition root injects real implementations and tests use in-memory fakes.
  • Separate repositories break atomicity when one action must write domain state and an outbox entry together, so share a transaction boundary or Unit of Work.
  • On large result sets, paginate or window queries instead of eagerly mapping thousands of rows into value structs.
  • Skip the protocol for a dependency that will never change, since boundary mapping has a real maintenance cost.

Study: Repository Decoupled Layers Protocol-Oriented Programming

P1 · Architecture, prepare next

Compare MVVM, Redux, MVI and TCA.They want: Unidirectional data flow, reducers, observable state
  • I'd compare them by how state changes.
  • In MVVM, ViewModel methods mutate state the view observes, which is cheap and familiar.
  • Redux routes every change through actions and reducers on one store, and MVI applies the same idea per screen.
  • TCA is the Swift version, adding effects as values, store scoping, dependency control and exhaustive tests.
  • Unidirectional flow buys traceability and reproducible bugs, at the cost of ceremony, onboarding time and a third-party dependency at the core of the app.
  • My default stays MVVM with a router.
  • I'd reach for a reducer, usually as a state machine inside one ViewModel, when a feature has complex transitions or ordering bugs.
  • I'd adopt TCA app-wide only if the team already knows it and wants its testing model.
  • What should stay consistent is who owns state and where side effects run.

Study: Unidirectional (TCA / Redux) MVVM (+ Router)

How do you structure SwiftUI versus UIKit applications?They want: State ownership, lifecycle, observation
  • In SwiftUI, views are values and the core question is state ownership: @State for local state, @Observable models owned once (or ObservableObject when supporting iOS 16), @Environment for dependencies, and a router owning NavigationStack path.
  • In UIKit, MVVM with a router keeps view controllers thin.
  • Share domain and data layers between both.
  • In hybrid apps, keep UINavigationController hosting UIHostingController as the root navigation shell when you need deterministic transitions and deep-link control, and test UIHostingController self-sizing carefully inside collection cells. Skip ViewModels on tiny SwiftUI views.
  • Mixing both costs two binding and navigation models, so keep the bridge thin and owned by one team.

Study: Declarative UI (React lineage) State Management

How would you prevent circular dependencies between feature modules?They want: Dependency graph, interface modules, DI
  • I'd prevent cycles structurally, because a rule on a wiki erodes as people rotate.
  • Features depend only on each other's interface modules, and only the composition root imports implementations.
  • SwiftPM already refuses to build a target cycle, but that doesn't stop layering drift, like a feature importing another feature's implementation.
  • So I'd add a dependency check in CI that fails the build when the graph breaks those rules.
  • When A and B genuinely need each other, I'd extract the shared contract into an interface module, or invert one direction with an injected protocol or event.
  • The cost is an extra module per feature and more setup, so I'd only split once a real two-way dependency appears.
  • Contracts enforced by the build outlast conventions.

Study: Feature Modules

How would you design a reusable component across multiple product surfaces?They want: Composition, customization, API contracts
  • Small, stable API: a configuration value type plus callbacks for intent.
  • Prefer composition and slots over boolean flags, because ten flags means a thousand untested combinations.
  • Style through design tokens, not per-caller overrides. No dependencies on feature modules.
  • Build accessibility and Dynamic Type in, give it an owner, and cover each supported configuration with snapshot tests.
  • Every configuration option is a maintenance cost, so I say no to flags until a second surface needs them.

Study: Facade & Modules Protocol-Oriented Programming

How would you test navigation and presentation logic independently?They want: Mocks, spies, injected routers
  • Inject the router as a protocol.
  • In ViewModel or Presenter tests, a spy router records the routes requested while you assert state, with no UIKit involved.
  • Test coordinators by feeding them routes and asserting the resulting stack, using a fake navigation controller or a route array.
  • Keep UI tests for a few smoke flows.
  • The cost is a protocol and a spy per router, worth it because navigation bugs are slow to find through UI tests alone.

Study: Coordinator / Routing MVVM (+ Router)

When does architectural abstraction become overengineering?They want: Cost of abstraction, actual change patterns
  • I'd call an abstraction overengineering when it costs more than the change it was meant to absorb.
  • To judge that, I'd look at history: which seams ever got a second implementation, which layers every PR has to touch, and where tests are still hard to write.
  • Typical signs are a protocol with one implementation and no test seam, a ViewModel that only forwards calls, or VIPER on a static settings screen.
  • My default is to add a seam where change is likely, like storage, networking and vendor SDKs, or at the second real use.
  • A team or test boundary that needs one also counts.
  • I'd also delete abstractions that never varied in practice.
  • What I wouldn't do is strip essential structure, like sync ordering, because it looks heavy.
  • I optimize for changing it correctly tomorrow.

Study: Protocol-Oriented Programming Services vs Singletons

Design patterns in practice

Delegates vs closures vs observers: when would you use each?They want: UIKit event handling
  • A delegate for a component with several related callbacks and one owner, UIKit style.
  • A closure for a single callback, such as a completion or a one-off action.
  • An observer (NotificationCenter, Combine, @Observable) when many unrelated parts react and the sender shouldn't know them.
  • The lifetime rules differ: delegates are weak, long-lived closures need [weak self], and observers need their token or cancellable kept alive.
  • The classic bug is a retain cycle from a strong delegate or a stored closure capturing self.

Study: Delegate Pub/Sub

How would you propagate state changes across screens?They want: Combine, Observation, NotificationCenter
  • Put the shared state in one observable source of truth at the right scope, such as a session store or repository.
  • Screens subscribe: @Observable in SwiftUI (tracked per property), Combine publishers or async sequences in UIKit, NotificationCenter for system and app-wide events.
  • Deliver on the main actor, publish value snapshots, and never let each screen cache its own copy.
  • In database-backed apps, observe the database's change notifications so every screen converges on the same data.
  • The cost is invisible coupling: I keep event types few and typed, and don't use broadcasts for one-to-one flows.

Study: Pub/Sub State Management

How would you hide a complex subsystem behind a stable API?They want: Contacts, privacy, networking
  • I'd put the subsystem behind one small facade, because consumers should depend only on what they need, like search, resolve and request permission.
  • SQL, caches, permission prompts and privacy rules stay internal to its module.
  • It returns domain errors instead of framework errors, so a Contacts or networking change doesn't leak into features.
  • If the API grows past one capability, I'd split facades by capability before it becomes a god object.
  • The payoff is that I can migrate the implementation without touching consumers.
  • The cost is mapping code and a facade that can hide expensive work, so I'd expose async APIs and document what's slow.
  • I'd skip the facade for a subsystem with one caller and no planned change.

Study: Facade & Modules

How would you replace a legacy dependency without changing its consumers?They want: Database and API migrations
  • Keep, or extract, the interface consumers already use, then write an adapter that implements it on top of the new dependency.
  • Swap at the composition root behind a flag, and for risky migrations run old and new side by side (dual-read or shadow compare) before cutting over.
  • The adapter maps new schemas and DTOs onto the existing domain types, so consumers never change.
  • The cost is running two implementations for a while, so set a date to delete the old one.

Study: Facade & Modules Decoupled Layers

How would you support interchangeable algorithms without branching everywhere?They want: Search, sorting, retry policies
  • Model the varying behavior as a protocol (SearchRanking, SortOrder, RetryPolicy) with concrete strategies, and inject the one to use.
  • Branching moves to one place, where things are built, instead of every call site.
  • In Swift a struct of closures or an enum with associated values is often lighter than a protocol: RetryPolicy.exponential(base:max:) versus .none, chosen per request type.
  • The cost is indirection, so I don't introduce it for a branch that appears once.

Study: Protocol-Oriented Programming Dependency Injection

How would you abstract local and remote data sources?They want: Offline-first data access
  • Expose a domain-level protocol (notes(), save(_:)) and implement it over a local store and a remote API.
  • State the source-of-truth policy: offline-first writes locally and syncs through a queue, online-first fetches and caches.
  • Map DTOs into domain types, serialize access with an actor, and define staleness and conflict rules explicitly.
  • I'd skip a repository for a single endpoint with no caching; it earns its place with a second source of truth.
  • The cost is owning conflict resolution, which is where sync gets hard.

Study: Repository

How would you construct feature modules with complex dependencies?They want: Screen construction, DI
  • Give each feature a factory that takes its dependencies, as protocols, once and builds screens: makeContactPicker(entryPoint:).
  • The composition root creates it with real services; tests create it with fakes.
  • Callers never see the dependency list, a new dependency touches one place, and every call returns a fresh instance.
  • With feature modules, the factory lives in the implementation and is exposed through the interface module.
  • The risk is a factory that grows into a service locator, so it builds screens and nothing else.

Study: Factory & Builder Feature Modules

How would you decouple navigation from ViewControllers?They want: Multi-screen workflows
  • Screens emit intent and a coordinator decides what's next, creating and pushing screens itself.
  • Parents retain child coordinators and release them on finish, including back-swipe and interactive dismissal, which you detect through the navigation controller's delegate.
  • Routes as values make deep links "build this stack" instead of a chain of pushes.
  • The cost is lifecycle bookkeeping; I wouldn't add one for a single list and detail.

Study: Coordinator / Routing

How would you add caching or logging without modifying existing implementations?They want: Networking middleware
  • Wrap the implementation in another type that conforms to the same protocol: CachingClient(wrapping: client), LoggingClient, RetryingClient.
  • Compose them at the composition root, for example Logging(Caching(Retrying(network))).
  • Order matters: logging outermost so it sees everything, and the cache outside the retry so a cache hit skips retries entirely.
  • The original type and its consumers don't change, and each decorator is testable on its own.
  • The cost is layers that are harder to debug, so I keep the chain short and log at the outer edge.

Study: Protocol-Oriented Programming Dependency Injection

What problems do singletons introduce?They want: Shared services, hidden dependencies
  • Hidden dependencies that aren't in any signature.
  • Global mutable state shared between tests, which makes them order-dependent and breaks parallel runs.
  • Process-long lifetime: logout can race a background save and leak data across accounts, and multiple accounts become impossible.
  • One instance is fine; global access is the problem.
  • Migrate with a protocol and default-argument injection, call site by call site, and scope user data to a session.
  • Pair default arguments with a CI ratchet—a SwiftLint rule, allowlist, or deprecation warning on .shared—otherwise new callers quietly reintroduce the singleton and the migration stalls forever.

Study: Services vs Singletons

How would you represent a complex asynchronous workflow?They want: Message delivery, uploads, authentication
  • An enum of states with associated data and one transition function: idle → uploading(progress) → retrying(attempt) → sent, or failed(error).
  • Invalid transitions become impossible or explicit errors.
  • The UI renders from the current state, and side effects fire on transitions.
  • For delivery and uploads, persist the state so it survives termination, and make transitions idempotent so retries and duplicate events are safe.
  • The cost is spelling out every state up front, which is exactly the point for delivery and auth flows.
  • I reach for one when a flow has more than a few states or must survive relaunch; a simple loading flag doesn't need it.

Study: Unidirectional (TCA / Redux) Coordinator / Routing

How would you model operations that can be queued, retried or undone?They want: Offline operations, message sending
  • I'd model each operation as a value, like SendMessage(id, payload) or DeleteNote(id), because values can be persisted, retried and inspected.
  • For offline sending, the app writes the command to a durable outbox first, so it survives termination.
  • A worker processes the outbox in order per conversation, retries with backoff and attaches an idempotency key, which lets the server drop duplicate retries.
  • Undo then becomes an inverse command the app enqueues.
  • The real risk is correctness: commands must be safe to replay, and undoing a change the server already applied needs a server-side inverse.
  • I'd skip the outbox for actions that only matter while the screen is open.
  • Anything the user expects to survive a relaunch belongs in it.

Study: Unidirectional (TCA / Redux) Repository

How would you represent nested UI components or hierarchical data?They want: View trees, threads, folders
  • Give leaves and containers one interface so code walks the tree uniformly.
  • UIKit's view hierarchy and child view controllers are composites, and every SwiftUI view composes views.
  • For hierarchical data (folders, threaded replies, settings sections) use a recursive struct or an indirect enum, rendered with recursive views or OutlineGroup.
  • Mind stable identity and lazy loading for deep trees.
  • The risk is unstable identity: give every node a stable id, so expanding or editing one node doesn't reset state or animations elsewhere in the tree.

Study: Declarative UI (React lineage)