One card at a time. Say your answer out loud, reveal, then rate yourself. Shaky cards come back first next time.
Keys: Space reveal · 1 shaky · 2 nailed it · → skip
MVC30-second answer
Explain MVC in 30 seconds.
In UIKit MVC the controller mediates between model and view, and UIViewController also owns the lifecycle, so responsibilities pile up there.
A massive view controller means the model layer is missing.
I keep MVC for simple screens with little state; once a screen has real logic, I move state and rules into model objects that screens observe and pull navigation into a router.
At scale, that's MVVM with a router.
MVCSwiftAsked directly
What is "Massive View Controller" actually a symptom of?
A missing model layer.
Teams treat the model as plain structs, so networking, caching, validation and state all land in the only class left, the view controller.
Size is the symptom.
The fix is to give the model layer real objects: a NotesStore that owns loading, saving and the current state.
Then the view controller goes back to being glue, and the logic becomes unit-testable without UIKit.
MVCSystem designAsked indirectly
Two tabs show the same notes. You edit in one and the other shows stale data. What's wrong with the design?
Each screen got its own copy of the data, so there's no single source of truth.
In MVC this is the real scaling problem, more than file size.
Make one model object own the notes and have both screens observe it, through a delegate, a notification or @Observable.
One writer, many readers.
View controllers render state they don't own and never push data into each other.
MVCiOS codingAsked indirectly
You inherit a 1,500-line view controller. What do you extract first, and why in that order?
Extract by value, not by line count.
First, business logic and networking go into model-layer objects, because that's what you most need to test.
Second, UITableViewDataSource goes into its own type.
Third, independent regions of the screen become child view controllers via addChild(_:).
Do it one slice per PR, with characterization tests first, so behavior never changes during the move.
MVCSystem designAsked indirectly
When would you move a team off plain MVC, and how?
When the pain is structural, not cosmetic.
Signals: navigation decisions scattered across view controllers, business rules duplicated between screens, several engineers colliding in the same files.
Address each signal directly.
Use coordinators for flow, shared model objects for rules, and feature modules for ownership.
Migrate screen by screen behind the same interfaces.
A big-bang rewrite to a new architecture rarely pays back.
MVVM (+ Router)30-second answer
Explain MVVM (+ Router) in 30 seconds.
MVVM with a Router splits a screen three ways.
The ViewModel holds presentation state and decisions and never imports UIKit.
The Router owns navigation and building the next screen.
The view controller only binds and forwards.
That makes presentation logic unit-testable and lets flows change without touching screens.
The cost is a ViewModel even on simple screens, and when one ViewModel gets a second reason to change, I pull out an interactor.
MVVM (+ Router)iOS codingAsked directly
MVVM vs MVC in UIKit: what exactly moves into the view model, and what does that buy you?
Move presentation logic into the view model, like joining a name with an optional salutation or formatting a date.
It exposes ready-to-show strings, so viewDidLoad just does nameLabel.text = viewModel.name.
Tests assert those strings without building a view controller, and view hierarchy changes don't break them.
Think of MVVM as refined MVC.
The view controller still exists, it just stops formatting.
MVVM (+ Router)iOS codingAsked indirectly
The model changes from network updates while the screen is visible. How does your view model keep the view in sync?
Observe it, and update on the main actor.
Network updates arrive off-main, so the view model hops to @MainActor before mutating state.
In SwiftUI, an @Observable view model re-renders exactly the views that read the changed properties.
In UIKit, use withObservationTracking to re-run your render function, or Combine @Published on older targets.
MVVM itself doesn't require any binding framework.
MVVM (+ Router)System designAsked indirectly
Your team is debating MVC versus MVVM for a new app. What questions settle it?
My default for a production app is MVVM with a Router; with @Observable it needs no binding framework, so it stays light.
MVC is the exception, for simple static screens like Settings.
What settles it: long-lived or a prototype?
Collections or complex, stateful elements?
Async updates from several sources?
Other teams or AI agents editing it?
Complexity and expected evolution matter far more than team size.
Optimize for how easy the code is to change correctly tomorrow, not to write today.
MVVM (+ Router)System designAsked indirectly
Your team wants MVVM but refuses to adopt a reactive framework. Is that viable?
Yes.
Observation ships with Swift: @Observable needs no third-party framework, and a plain onChange closure works on any deployment target.
Immutable models handed in through init need no binding at all.
The real decision is how state reaches the view on your minimum OS version, not whether to adopt a reactive library you'll carry for years.
MVVM (+ Router)System designAsked indirectly
A year after moving to MVVM, view models are 800 lines. What went wrong?
The view model became the new massive view controller: networking, persistence and business rules moved in.
Keep it to presentation state and user intents on the main actor.
Move resource access, business rules and state machines into domain services or interactors behind protocols, so each concern has one owner.
In review, a view model that touches URLSession or the database directly is the red flag.
MVVM (+ Router)System designAsked indirectly
Does AI-assisted development change how you'd architect an iOS app?
Yes, it strengthens the case for structure.
I now also optimize for safe, localized changes by AI agents.
Two questions: can an agent change one responsibility without understanding unrelated ones, and can we verify it without running the whole app?
With MVVM + Router, a selection change lands in the ViewModel and its tests, not navigation or rendering.
AI makes boilerplate cheaper, not coupling or regressions.
The limit: needless indirection confuses AI too.
So I favor MVVM + Router and unit tests even for small production apps.
MVP (Passive View)30-second answer
Explain MVP (Passive View) in 30 seconds.
MVP makes the view passive: it forwards events and executes commands like setSaveEnabled, while a Presenter holds all presentation logic behind a view protocol.
You test the presenter with a fake view, no UIKit.
The difference from MVVM: MVP pushes commands, MVVM exposes state the view binds to.
I'd pick it for UIKit without a binding layer; the cost is a view protocol that grows with every label.
MVP (Passive View)iOS codingAsked directly
What is Passive View, and how does it differ from Supervising Controller?
In Passive View the view has zero logic.
It forwards input, and the presenter updates the model and sets every widget, like view.setTitle(_:).
Supervising Controller lets the view do simple declarative bindings itself, which leaves that code untested.
Passive View is more explicit and easier to debug because nothing happens through observers.
The cost is a chattier presenter and a fake view in every test.
MVP (Passive View)iOS codingAsked indirectly
You need to unit-test form validation and error display without instantiating UIKit. How do you structure the screen?
Use a Humble View.
Put validation and display decisions in a presenter and hide the view behind a protocol, like protocol SignUpView: AnyObject { func showError(_ message: String) }.
In tests a fake view records what the presenter set, so you test the logic with no UIKit.
The rule is that anything hard to test gets minimal behavior.
The cost is a protocol and a fake per screen.
MVP (Passive View)System designAsked indirectly
Two screens show the same model and must both update when it changes. Observer synchronization or explicit flow synchronization?
Use observer synchronization when several screens show the same model.
Each one just reacts to the model and ignores the others, so adding a third screen costs nothing.
The catch is that implicit observer chains are hard to trace and debug.
Flow synchronization updates controls explicitly and reads top to bottom, but the code has to know every dependent widget, which breaks down as screens multiply.
VIPER30-second answer
Explain VIPER in 30 seconds.
VIPER splits a screen into five roles behind protocols: View renders, Presenter formats, Interactor runs business rules, Entity is data, Router navigates.
It formalizes what MVVM blurs: presentation versus business orchestration.
That pays off on long-lived components with several independent reasons to change, like a contact picker.
The cost is five types per screen, so I default to MVVM with a router and use VIPER selectively.
VIPERSystem designAsked directly
Walk through VIPER's roles. Who owns business logic, who decides to navigate, and who performs the transition?
The Interactor holds one use case's business logic as a plain object with no UIKit import.
The Presenter formats results, handles input and decides when to navigate.
The Wireframe, or Router, owns the view controllers and performs the transition.
The View is a passive, protocol-backed screen.
Entities are plain data that only the Interactor touches.
Splitting decide from perform makes navigation logic testable.
VIPERSystem designAsked indirectly
The team might replace Core Data next year. How do you keep business logic from depending on the persistence technology?
Put a data manager between the Interactor and the store.
The Interactor talks to a protocol, like protocol OrderStore { func fetch() async throws -> [Order] }, and Core Data stays behind it, so you can swap the store.
Never hand managed objects up to the Presenter.
Map them into plain structs and let the type system stop persistence types from leaking across boundaries.
VIPERSystem designAsked indirectly
Adopting VIPER produced many tiny files per screen and the team is frustrated. How do you adopt it pragmatically?
Adopt it incrementally and bend it where it hurts.
VIPER does create many small objects, and deviating is fine as long as each piece keeps a single responsibility.
Use it for new features instead of rewriting old ones.
Build the Interactor first, then the Presenter, then the View, so tested logic exists before any UI.
Merging a trivial Presenter into a static screen's View is fine.
VIPERSystem designAsked indirectly
You moved a 3,000-line view controller to VIPER, and a few hundred engineers now build on it. What starts to hurt next?
App state still follows the view tree.
VIPER fixes separation and testing, but business logic leaks into presenters, and there's no way to have a node with logic and no screen.
At that scale, route on business state instead of screens.
A deep logic tree can then sit over a shallow view hierarchy, which keeps transitions simple and lets teams own whole subtrees.
VIPERSystem designAsked directly
In RIBs, the architecture very large apps grew out of VIPER, why would a node have no view at all?
Some states are pure business logic, like logged in versus logged out, and only decide which child to show.
A viewless node owns that decision and presents its children through the parent's view controller.
The gotcha is cleanup.
Nothing removes those views for you, so its detach hook, like willResignActive(), must dismiss its children's screens or stale screens stay on the stack.
VIPERiOS codingAsked indirectly
In a RIBs-style tree, a child node needs the signed-in player's name. A teammate wants an optional on a shared object. What do you do instead?
Pass it into the child's builder at build time, like build(withListener: self, playerName: name).
The value is fixed for the module's lifetime, and the child never handles nil for a problem it doesn't own.
Resolve values as early as you can.
The child declares a dependency protocol and the parent's component satisfies it, so the compiler checks the wiring instead of a runtime lookup.
VIPERSystem designAsked indirectly
Beyond VIPER (RIBs-style): about 40 teams ship into one app, and one feature's failure must not block the core flow. How do you structure the modules?
Split core from optional.
Keep a small core, like login, session and the main job flow, under strict review.
Everything else is a plugin.
Core exposes a plugin-point protocol and each feature implements it behind a feature flag.
In an incident you switch off one feature, say the map, and the core flow still works.
The cost is more boilerplate and slower core reviews.
It works because features reach the core only through the plugin protocol, so switching one off can't break core code.
Clean Swift (VIP)30-second answer
Explain Clean Swift (VIP) in 30 seconds.
Clean Swift's VIP runs one direction: the View sends a Request to the Interactor, which sends a Response to the Presenter, which displays a ViewModel back on the View.
Each hop is a plain struct, so every stage is a pure input-to-output test.
I'd use it when a team wants VIPER's boundaries with a flow that's easier to trace; the cost is three structs per use case.
Clean Swift (VIP)System designAsked directly
Trace one user action through the VIP cycle. What types cross each boundary?
The view controller calls the Interactor through a BusinessLogic protocol, passing a Request.
The Interactor gets data from a worker, keeps it in its DataStore, and sends a Response to the Presenter through PresentationLogic.
The Presenter turns that into a ViewModel and calls the view's DisplayLogic.
Data only flows forward, so each layer is testable with a spy on the next.
Clean Swift (VIP)iOS codingAsked indirectly
A selected order must reach the detail scene without the detail screen reaching back into the list. How?
Let the Router pass the data.
It adopts a DataPassing protocol that exposes the scene's DataStore.
On navigation it reads the source store and writes into the destination's, like destination.order = source.orders?[selectedRow].
The detail scene never reaches back to the list.
The same code path works whether you navigate by segue or by instantiating the destination and calling show.
Clean Swift (VIP)iOS codingAsked indirectly
Your presenter calls back into the view controller. How do you avoid a retain cycle and keep formatting testable?
Hold the view weakly through a protocol, like weak var viewController: DisplayLogic?.
The presenter never retains the controller, and calls become no-ops once it's gone.
Do date and currency formatting in the presenter as it maps a Response to a ViewModel.
Then a test passes any spy conforming to DisplayLogic and asserts the formatted strings, with no UIKit involved.
Coordinator / Routing30-second answer
Explain Coordinator / Routing in 30 seconds.
A coordinator owns navigation for a flow.
Screens report intent, like “user picked a pumpkin”, and the coordinator decides what's next, builds it and pushes it.
Screens never know what comes after them, so one screen works in two flows and deep links become “build this stack”.
The cost is lifetime management: parents retain child coordinators and must release them, including on back-swipe.
Coordinator / RoutingiOS codingAsked directly
What problem does the Coordinator pattern solve, and how do child coordinators stay alive and get cleaned up?
It stops view controllers from building and presenting the next screen, which welds them to one flow.
A coordinator is a plain object that owns the flow instead.
Parents keep children in var childCoordinators: [Coordinator] so they stay alive.
When a child finishes, it tells its parent through a delegate, and the parent removes it.
Forget that removal and you leak whole flows.
Coordinator / RoutingiOS codingAsked indirectly
This detail screen must open from two different flows. How do you avoid it knowing where it came from?
Have the screen report intent instead of navigating.
A view controller should manage either the sequence of screens or its own UI, never both.
The list turns the row into a model and calls delegate?.didSelect(item).
A parent flow controller that owns the navigation stack decides what comes next.
Either flow can then host the same detail screen unchanged.
Explain TCA's State, Action, Reducer, Store and Effects. What do you gain, and what does it cost?
State is a value type, Action is an enum of everything that can happen, and the Reducer mutates state and returns Effects, like network calls, that feed actions back in.
The Store runs the loop.
You get one consistent way to change state, exhaustive tests and features that compose.
The cost is more setup than plain SwiftUI and a framework the whole team must learn.
It works because state changes only inside the reducer, so every change is an action you can log, replay and test.
Do you need a Redux-style framework to get one-way data flow in UIKit?
No.
You can enforce one-way flow with a library like TCA, get it through discipline, or let bindings produce it.
Discipline, such as MVC plus a ViewState struct the controller renders, costs extra observation code.
Bindings route input into the model and state back out automatically.
Pick by how much enforcement your team needs.
The Elm and Redux ideas are the same either way.
Dependency Injection30-second answer
Explain Dependency Injection in 30 seconds.
Dependency injection means an object receives what it needs, usually through its initializer, instead of creating or looking it up.
Concrete types are chosen in one composition root, so tests pass fakes and features swap implementations.
I prefer static injection, where a missing dependency is a build error, over runtime containers that fail while the app runs.
The real design work is scoping: app, user session and screen.
Dependency InjectionSwiftAsked directly
Initializer, property and parameter injection in Swift: when do you choose each?
Default to initializer injection, like init(store: any NoteStoring), so an object is complete the moment it exists.
Use property injection only for system-created classes, like storyboard view controllers, and accept the property may be unset or changed later.
Use parameter injection for legacy code, static APIs, or a dependency that only one call needs.
Dependency InjectionSystem designAsked indirectly
A teammate proposes a global service locator so any class can fetch its dependencies. What's your concern?
A locator hides dependencies.
Every class depends on the locator itself, and its real needs are scattered across lookup calls instead of visible in init.
A missing registration only shows up at runtime.
It's acceptable for app code you fully control.
For shared components other teams reuse, prefer injection.
Separating configuration from use matters more than which one you pick.
Dependency InjectioniOS codingAsked indirectly
A view controller loaded from a storyboard needs an API client, but you don't control its initializer. How do you inject it?
Use property injection, like var apiClient: APIClient = .live, set right after instantiating from the storyboard.
It's the standard workaround for system-created classes.
The gotcha is that a mutable property can be left unset or swapped unexpectedly.
On iOS 13 and later, instantiateViewController(identifier:creator:) lets you use a real initializer, so prefer that where you can.
Protocol-Oriented Programming30-second answer
Explain Protocol-Oriented Programming in 30 seconds.
Protocol-oriented programming puts shared behavior in protocols with default implementations in extensions, so value types gain behavior without a base class.
Both sides depend on the abstraction, which creates seams for testing and swapping.
The nuances: some P is one concrete type and fast, any P boxes it and dispatches dynamically, and a method only in an extension dispatches statically.
I add protocols only where something actually varies.
Protocol-Oriented ProgrammingSwiftAsked directly
some versus any: what's the real difference, and which should be your default?
Default to generics or some P, and use any P only when you need to mix concrete types at runtime.
An any P is an existential box.
It may heap-allocate, its calls can't be specialized, and protocols with associated types get awkward.
The explicit any keyword exists to make that cost visible.
Use some when one concrete type is fixed at compile time.
some is fast because the compiler knows the concrete type, so it can specialize and inline calls.
A type implements a method that also lives in a protocol extension, yet the extension's version runs. Why?
Only protocol requirements are dynamically dispatched.
A method that exists only in a protocol extension is statically dispatched, so calling through the protocol type runs the extension's version and skips the type's own.
Fix it by declaring the method in the protocol, like protocol Greeter { func greet() }, and keeping the extension as the default implementation.
Facade & Modules30-second answer
Explain Facade & Modules in 30 seconds.
A facade is one small public API in front of a messy subsystem like networking or storage.
Putting the subsystem in its own Swift package makes everything else internal, so the compiler enforces the boundary instead of code review.
Callers stay stable while the internals change, say from JSON to protobuf.
The risk is the facade growing into a god object, so I split facades by capability.
Facade & ModulesSystem designAsked directly
Facade versus Gateway: what's the difference, and who writes each?
A Facade simplifies a complex API, and the provider usually writes it for every consumer.
A Gateway is written by the client for its own needs.
It wraps an external system behind an interface in your app's terms, like protocol PaymentsGateway, and translates calls both ways.
Wrapping any foreign API this way pays off, because swapping vendors then touches one type.
Use a gateway for any API you don't control; the cost is a translation layer you keep in sync with the vendor.
Facade & ModulesSystem designAsked indirectly
A third-party analytics SDK is imported in forty files and now must be replaced. How do you prevent that next time?
Wrap it behind a protocol, like protocol Analytics { func track(_ event: Event) }, so only one file imports the SDK, and keep the concrete type private behind a factory.
Count how many files import each dependency to find where encapsulation is weak.
The gotcha is over-wrapping every library, which makes the design rigid.
Wrap volatile third-party code first.
Facade & ModulesSystem designAsked indirectly
Sibling modules in your Swift package need shared helper APIs, but app clients shouldn't use them. How do you expose them?
Mark them package.
It shares the API across modules in the same package without making it public.
Before it, cross-module use meant public, so app clients could build unwanted dependencies on internals.
Public symbols are also exported from the binary, which adds code size.
With package, the external surface stays small and you can refactor internals freely.
Repository30-second answer
Explain Repository in 30 seconds.
A repository gives features a collection-like API, such as notes() and save(_:), and hides whether data comes from memory, disk or network.
Its real job is policy: which source is the truth, when caches go stale, and how conflicts resolve.
For offline-first, local is the truth and the network is sync.
I'd skip it for a single endpoint with no caching.
RepositorySystem designAsked directly
What is the Repository pattern, and what does it centralize?
A Repository sits between the domain and the data-mapping layer and makes stored objects look like an in-memory collection, like repo.users(matching: criteria).
Callers describe what they want declaratively, and the repository's mapping code does the real fetch.
Query construction lives in one place, and dependencies point one way.
It earns its keep with many entities or heavy querying.
Skip it for a single endpoint with no caching, since it's one more layer to maintain.
RepositoryiOS codingAsked indirectly
You must ship a feature before the storage choice is decided. How do you avoid rewriting the view model later?
Start with a protocol, like protocol UserRepository { func find(id: User.ID) async throws -> User? }, plus create and delete.
Inject it into the view model's init.
Ship with an in-memory actor, then swap in UserDefaults or Core Data later without touching the view model.
The in-memory version doubles as your test fake.
RepositorySystem designAsked indirectly
Similar query logic for the same entities is duplicated across many view models. Where should it live, and why?
Move it into a Repository.
Concentrating query construction in one place stops duplicates from drifting apart, and it pays off most with many entities or heavy querying.
Callers pass declarative criteria and never touch data mapping, so storage details stay behind a one-way dependency.
For a small app with three simple fetches, it's overkill.
RepositorySystem designAsked indirectly
Five view models each call the network singleton directly. How do you restructure access to remote and disk data?
Give each resource, like network, disk or sensors, one model controller and inject it.
Don't let view models reach NetworkManager.shared.
View controllers or coordinators hand the controller down, so access paths are visible and mockable.
The honest trade-off is that it's still one shared object.
You've traded global reachability for one injected owner you can replace in tests.
Factory & Builder30-second answer
Explain Factory & Builder in 30 seconds.
A factory centralizes construction: callers ask for a kind of screen or object and never name the concrete type or its dependencies, so adding a dependency touches one place.
Returning a fresh instance avoids state shared by accident.
The risk is one giant switch that every feature edits, so I keep a factory per feature.
Builders I keep for multi-step input, since default arguments cover the rest.
Factory & BuilderSwiftAsked directly
When is the Builder pattern still worth it in Swift, given structs and value types?
Rarely in app code, because structs with default values cover most cases.
It still pays off with Objective-C APIs where a value type isn't practical, and in public frameworks where you want customization without exposing mutable properties.
Chained calls collect settings privately and build() returns an immutable result.
The cost is an extra type to keep in sync.
Factory & BuilderiOS codingAsked indirectly
Fast browsing builds a queue of stale requests on one shared movie loader. How do you fix the design?
Stop sharing the loader.
Inject a MovieLoaderFactory that holds the truly shared pieces, the cache and the URLSession, and give each screen its own loader.
Have the loader's deinit cancel pending requests, so stale work dies with its screen.
View controllers pass the factory along instead of a loader.
Share the cache, and keep request queues per screen.
Factory & BuilderSwiftAsked indirectly
A mutable attributed string is handed to the database while still being modified, causing crashes. What design prevents this?
Accumulate into a builder that keeps the NSMutableAttributedString private, and have build() return an immutable NSAttributedString copy.
Callers never hold the mutable object, so nothing can change after handoff.
The principle is to never let mutable state cross a boundary.
For a public API, builders also let you close off a lot of mutable surface.
Factory & BuilderSystem designAsked indirectly
You're shipping a persistence framework. How do callers write rich queries without seeing your internal operation types?
Give callers a builder, like db.query(User.self).where(\.age, >, 18).sorted(by: \.name).
They chain declarative filters while your internal operation types stay private, so you can change them without breaking clients.
Public frameworks are where builders really earn their place.
The cost is another type to keep in sync with the internals.
Factory & BuilderiOS codingAsked indirectly
The codebase has TitleLabel, SubtitleLabel and SpinnerViewController subclasses that only set properties. What do you change?
Replace them with static factory methods, like static func makeTitle() -> UILabel.
Setup isn't behavior, so it doesn't need a new type.
Put the helper in a private extension to scope it to one file, and keep subclasses for real behavior.
The gotcha is that a static computed property can't take arguments, so it becomes a method once it needs one.
Factory & BuilderiOS codingAsked indirectly
Every test builds a User with ten arguments, and a new field breaks 200 tests. What's the fix?
Add a test-only factory, like static func stub(permissions: [Permission] = []) -> User, with defaults for every field.
Each test passes only what it cares about, so a new field changes one stub instead of 200 call sites.
Keep it in the test target so production can't call it.
The name makes it obvious it's test data.
Services vs Singletons30-second answer
Explain Services vs Singletons in 30 seconds.
A singleton is one instance reachable everywhere through .shared.
A service is a capability behind a protocol that gets passed in.
One instance is fine; global access is the problem: hidden dependencies, state leaking between tests, and a lifetime that never ends, so logout can leak one user's data to the next.
I keep singletons at the edges and inject anything holding logic or user data.
Services vs SingletonsSystem designAsked directly
Singletons versus injected services: what goes wrong with UserManager.shared, and how do you migrate?
Turn UserManager.shared into an injected dependency.
Singletons are global mutable state, they hide dependencies, and they live for the whole run, which often forces optionals.
Define a protocol, make the singleton conform with no changes, and inject it, like init(users: UserManaging = UserManager.shared).
Then migrate one view controller at a time with no big-bang rewrite.
Services vs SingletonsiOS codingAsked indirectly
Tests pass individually but fail together because one test logs a user in. What's the root cause, and the fix?
Shared global state is leaking between tests.
The singleton survives the whole run and is hard to reset, so test order changes results.
Inject protocol-typed services, like init(userService: UserService, logoutService: LogoutService), and build fresh instances in each test.
The tests become isolated, and you can safely run them in parallel.
Services vs SingletonsSystem designAsked indirectly
Some resources should be shared, like an image cache. How do you share them without a singleton's downsides?
Inject a factory that owns the shared pieces, like the image cache and URLSession, and have it create fresh objects for per-consumer state.
Every screen then shares the cache but gets its own request queue.
You keep the benefit of sharing without global access.
The cost is more types, and someone has to own each instance's lifetime.
That works because the factory is injected, so each consumer's dependencies stay visible and replaceable in tests.
Services vs SingletonsiOS codingAsked indirectly
On logout you clear the image-cache singleton, but user A's thumbnails still show up for user B. What happened?
An in-flight save wrote A's image into the freshly cleared cache.
A singleton has no owner and no end of life, so teardown always races with background work.
Scope user state to a user object that owns the cache and is passed down explicitly.
Logout drops the whole object graph, work in flight still holds its own user's context, and user B starts clean.
Services vs SingletonsSystem designAsked indirectly
Product now wants two accounts signed in at once, and SessionManager.shared is used everywhere. How do you plan the migration?
Scope it to the user.
The real bug is giving session state app lifetime.
Introduce a UserSession object that owns the session, caches and services, and inject it one flow at a time, starting where SessionManager.shared is read.
When you're done, each signed-in account has its own object graph.
Truly app-wide things, like a shared memory cache, can stay global.
Because each account's services hang off its own session object, signing one out drops exactly its state.
Services vs SingletonsSystem designAsked directly
The AppDelegate holds the API client, the cache and the current user. What test decides what may stay global?
Apply a three-part test.
Nothing else owns it, there's exactly one, and it isn't a constant.
Most data fails, because it has a natural parent like the screen or flow that manages it.
The API client and current user usually belong to a session object.
Anything that passes should be self-contained.
Hide it behind an accessor anyway, so you can swap the implementation later.
Decoupled Layers30-second answer
Explain Decoupled Layers in 30 seconds.
Decoupled layers point every dependency inward: the UI and data layers depend on the domain, and the domain (models, rules and protocols) depends on nothing.
Adapters convert DTOs and database objects into domain types at the boundary.
My test: could I swap disk storage for CloudKit without touching a view?
The cost is mapping code at every boundary, so I don't formalize layers for a two-screen app.
Decoupled LayersSystem designAsked directly
State the dependency rule. How does a use case call out to a presenter without breaking it?
Source dependencies point only inward.
Inner layers never name anything in outer ones, including framework types.
When control must flow outward, the use case calls a protocol it defines, like protocol OrderOutput { func present(_ orders: [Order]) }, and the outer presenter implements it.
Control flows out while the source dependency still points in.
That's dependency inversion.
Decoupled LayersSystem designAsked indirectly
The domain layer passes Core Data managed objects straight up to views. What's the risk, and the fix?
Map them to plain structs at the boundary.
Passing NSManagedObject upward couples every layer to Core Data, so views inherit its threading rules, faults and schema changes.
Data crossing a boundary should be simple values shaped for the inner layer.
The mapping code is boring, but it's what lets you change persistence later without touching views.
Decoupled LayersSystem designAsked indirectly
The same business rules must power iPhone, iPad and Mac apps. How do you layer the code?
Keep business logic in plain objects with no UIKit or AppKit import, like VIPER Interactors or use-case types, and share them in a module.
Give each platform its own presenters and views, since layouts differ.
Put persistence behind a data manager, so the store can change too.
Reuse across iPhone, iPad and Mac is exactly what this layering buys you.
Decoupled LayersSystem designAsked indirectly
Rules like whether a user can comment are copied across view controllers and a global helper. Where should they live?
Put it in a model controller.
Models should stay plain data, and a singleton brings shared mutable state.
A model controller is a viewless object that keeps one model private and exposes purpose-built APIs, like var canComment: Bool.
Each rule gets one testable code path, and views observe the controller instead of the raw model.
The cost is a new API per use case.
Feature Modules30-second answer
Explain Feature Modules in 30 seconds.
Feature modules split an app into an interface module and an implementation module per feature.
Features depend only on each other's interfaces, and implementations meet at one composition root.
That buys faster incremental builds, preview apps per feature and clear team ownership.
The costs are Package.swift plumbing and cross-module refactors, so I start with logical boundaries and split physically when build times or ownership demand it.
Feature ModulesSystem designAsked directly
Why split an app into dozens of SPM feature modules? What do you actually gain?
Faster builds and isolation.
With fine-grained modules you build one feature without compiling the whole app, so iteration speeds up and SwiftUI previews stay stable.
Picking only the modules you need also keeps size-constrained targets like App Clips and extensions small.
The costs are real: more Package.swift wiring and dependency hygiene, so weigh them for your team.
Feature ModulesSystem designAsked indirectly
Onboarding only appears on first launch, so QA keeps reinstalling the app to test it. How would you restructure the code?
Move onboarding into its own module and build a small preview app from just the modules it needs.
Then the flow launches on its own, with no reinstalling to reset first-launch state.
QA and developers get a one-tap loop.
It only works if the feature module has no dependency on the app target, so it rewards modularization discipline.
Feature ModulesSystem designAsked indirectly
Feature A must navigate to Feature B, but feature modules shouldn't import each other. How do you wire it?
Don't import B's implementation.
Either A depends on B's interface module, a small protocol like ProfileRouting, or A exposes a closure like onSelect: (Item.ID) -> Void and the composition root wires it to B.
Only the root sees both implementations.
Because features stay independent, each can also ship as a standalone preview app for QA.
Feature ModulesSystem designAsked indirectly
Leadership wants a strict modular, plugin-based architecture for a 10-person team. What does it actually cost?
Name the costs.
A plugin architecture has more pieces than MVC or MVP and needs more upfront planning.
A small reviewer group must approve every core change, which slows everyone.
That process makes sense with dozens of parallel teams and weekly releases.
For 10 engineers it's mostly overhead.
Match the ceremony to your team count and adopt only the parts that solve real pain.
Delegate30-second answer
Explain Delegate in 30 seconds.
Delegation hands decisions or events from one object to exactly one owner through a protocol, like a table view asking its data source.
The delegate is held weakly to avoid a retain cycle.
It fits a component with several related callbacks and one listener.
For a single callback I use a closure, for many listeners pub/sub, and if an answer is required I take it in init instead.
DelegateSwiftAsked directly
Delegate protocol or closures: how do you choose for a component's callbacks in Swift?
Use a closure for a single callback, ideally passed in init, so there's no ambiguous nil delegate when a decision is needed.
Use a delegate for many related events, since it groups them in one type.
The gotcha with closures is retain cycles when they capture the owner, so use [weak self].
For several closures, group them in a configuration struct.
DelegateiOS codingAsked indirectly
After adding a delegate to your custom component, neither the component nor its owning screen ever deallocates. What happened?
It's a retain cycle.
The owner holds the component, and the component holds the owner as its delegate.
Declare weak var delegate: ComponentDelegate? and constrain the protocol to AnyObject.
Also follow the conventions.
Methods start with the delegating type's name and pass the delegating object first, like func picker(_ picker: Picker, didSelect item: Item).
DelegateiOS codingAsked indirectly
A tap inside a deeply nested child view controller must trigger navigation owned several levels up. How do you route it?
Relay it up the delegate chain.
The child calls its delegate, each parent forwards the intent until it reaches the controller that owns the navigation controller, and that one navigates.
Children never reach sideways or walk up the hierarchy, so each stays reusable anywhere.
The cost is relay boilerplate at each level, and coordinators exist partly to shorten that chain.
DelegateiOS codingAsked indirectly
Two reusable components on one screen both need to be the scroll view's delegate. UIKit allows only one. What do you do?
Put a multiplexing proxy in the delegate slot that forwards each call to several targets.
The gotcha is responds(to:).
If the proxy only checks the first target, UIKit may skip callbacks that another target implements, so check every target.
Also decide who wins for callbacks that return values, like scrollViewShouldScrollToTop(_:).
Pub/Sub30-second answer
Explain Pub/Sub in 30 seconds.
Pub/sub lets a publisher emit events that any number of subscribers receive without knowing who they are: NotificationCenter, Combine subjects or AsyncStream.
It's right for broadcasts like sign-out or a settings change.
The cost is invisible coupling, since you can't see listeners in the code, plus threading and subscription lifetimes to manage.
For one-to-one conversations I use a delegate or a closure.
Pub/SubSwiftAsked directly
Compare delegation, NotificationCenter and KVO by coupling and fan-out. When does each fit?
Delegates and callbacks are one-to-one and loosely coupled, so use them when one owner needs to respond.
NotificationCenter broadcasts to any number of observers and the poster doesn't know who's listening, so use it for app-wide events.
KVO is one-to-many but tightly coupled to key paths on a specific object.
Choose by who needs to know and how many.
Pub/SubiOS codingAsked indirectly
A notification handler updates a label and sometimes misbehaves or crashes. What do you check?
Check the thread first.
Notifications arrive on the posting thread, so UI updates need to hop to the main queue.
Then check lifetime.
With the block API, keep the token from addObserver(forName:object:queue:using:), remove it when you're done, and capture [weak self] in the block.
Passing queue: .main handles the threading for you.
Pub/SubSystem designAsked indirectly
NotificationCenter is used everywhere and nobody knows who reacts to what. How do you make observation safer and clearer?
Replace stringly-typed broadcasts with typed observer protocols, one method per event, with empty default implementations.
Store observers as weak wrappers keyed by ObjectIdentifier, so there are no retain cycles and insert and remove are constant time.
You regain type safety and can see who listens to what.
The trade-off is more code and more protocols.
Pub/SubiOS codingAsked indirectly
Your custom observer list keeps observers alive long after their screens close. How do you fix the storage?
Store observers weakly.
Wrap each in a struct holding weak var observer: AnyObject?, key it by ObjectIdentifier for easy removal, and prune entries whose observer is nil whenever you notify.
Typed observer protocols with empty defaults let each observer pick events, and the compiler checks arguments.
The cost is more internal code in an observation-heavy codebase.
Pub/SubiOS codingAsked indirectly
A shared player takes observation closures, and old screens keep reacting after they're gone. What's the design flaw?
Closures with no removal path outlive their screens.
Tokens help.
Store closures in a [UUID: Handler] dictionary and return a token whose cancel() removes the entry.
But people forget to cancel.
The sturdier fix is capturing the observer weakly and passing it into the closure, so observation ends when it deallocates.
Match the technique to the observer's lifetime.
Completion Handlers30-second answer
Explain Completion Handlers in 30 seconds.
A completion handler is an escaping closure an async API calls when it finishes, usually with a Result.
The contract is exactly once on every path, and nothing enforces it: a missing return fires it twice, an early return never calls it.
The callback thread must be documented, and self is captured strongly by default.
In new code I use async/await, where exactly-once is a language guarantee.
Completion HandlersSwiftAsked directly
What's wrong with a completion handler taking Data? and Error?, and how does Result fix it?
With (Data?, Error?), both can be nil or both set, so callers face states that make no sense, and the compiler can't prove the data exists.
Result<Data, Error> has exactly two cases, success with a value or failure with an error, and the compiler forces callers to switch over both.
Today async throws gives the same guarantee with less ceremony.
Completion HandlersSwiftAsked indirectly
Code review finds a function with several early returns that sometimes never calls its completion. How do you prevent this bug class?
Move to async/await.
Forgetting to call the completion on an early return, or forgetting to return after calling it, is a whole bug class the compiler can't catch with callbacks.
An async throws function must return a value or throw on every path, so the compiler enforces it.
Nesting and verbose error paths go away too.
Completion HandlersiOS codingAsked indirectly
A view model stores a completion closure that references the view controller, and the screen never deallocates. Fix it.
Escaping closures are stored, so they retain whatever they capture.
A view model holding a closure that captures the controller is a cycle.
[weak self] fixes it, but the compiler won't warn when you forget.
A safer habit is capturing only what you need, like [label = self.label], so the controller never enters the closure.
Completion HandlersSwiftAsked directly
Swift has throws. Why would you still pass a Result value?
Throws only propagates an error up the current call stack.
It can't be stored, moved between threads, or handed to another function later.
Result is a plain value, so it can do all of that, which is why callback APIs used it.
The gotcha is that the compiler forces you to handle a throw, but a Result can be silently ignored.
Promises → async/await30-second answer
Explain Promises → async/await in 30 seconds.
Futures turned a callback into a value, and async/await made it part of the language: an async function suspends, then returns or throws exactly once.
I bridge legacy callback APIs once with withCheckedThrowingContinuation, so a double resume traps in development instead of silently duplicating work.
The things to watch are cooperative cancellation and unstructured Task {} work that outlives its screen.
Promises → async/awaitSwiftAsked directly
How do you wrap a completion-handler API with async/await, and which rule must never be broken?
Use withCheckedThrowingContinuation, call the old API inside, and resume from its callback.
The rule is that every path resumes exactly once.
A checked continuation traps on a double resume in every build and logs a warning if it's dropped.
The unsafe version turns a double resume into undefined behavior and a dropped one into a silently leaked task.
Promises → async/awaitSwiftAsked indirectly
Profiling shows checked continuations in a hot path. Can you switch to unsafe ones, and what do you give up?
Yes, the APIs are identical, so it's a one-word swap.
Only do it after the wrapper is verified and profiling proves it matters.
You lose the safety net.
A double resume becomes undefined behavior instead of a trap, and a dropped continuation silently leaks the task.
Make sure tests cover every callback path before you swap.
Promises → async/awaitiOS codingAsked indirectly
A UIKit button handler must call an async method and show errors. How do you bridge sync and async?
Start a Task in the handler: Task { do { try await save() } catch { show(error) } }.
Inside, you get normal do/try/catch and main-actor UI updates.
The catch: the Task keeps self alive until it finishes.
That's fine for a short save, but for long work keep a handle and cancel it when the screen goes away.
Wrap old callback APIs once with withCheckedThrowingContinuation.
Swift 6 Concurrency30-second answer
Explain Swift 6 Concurrency in 30 seconds.
Swift 6 turns data races into compile errors: state lives in one isolation domain, and only Sendable values cross.
The bugs that remain are logical: reentrancy across awaits and forgotten cancellation.
So I keep UI state on the main actor, cancel superseded work, and re-check invariants after every await.
Swift 6 ConcurrencySwiftAsked directly
Swift 6 makes data races compile errors. What concurrency bugs can you still ship?
Logic races.
Actor reentrancy: state changes across an await, so read-await-write sequences break.
Missing cancellation: superseded work still finishes and publishes stale results.
Work on the wrong executor: a Task {} from the main actor inherits it.
And deadlock-like stalls from blocking calls inside the cooperative pool.
The compiler checks isolation, not intent.
Swift 6 ConcurrencyiOS codingAsked indirectly
Search results flicker and sometimes show results for an older query. Walk through the fix.
Each keystroke starts a search, and a slow early one finishes last.
Keep a Task handle on the main-actor model, cancel it when the query changes, and check Task.isCancelled after the await before assigning results.
Debounce with Task.sleep inside the task, so cancellation also cancels the wait.
Tag results with their query if the API can't be cancelled.
Swift 6 ConcurrencySystem designAsked indirectly
You're migrating a large UIKit app to Swift 6 strict concurrency. How do you plan it?
Module by module, leaves first, with the Swift 6 language mode on per module.
Make UI types @MainActor explicitly, or adopt default main-actor isolation for app targets.
Convert shared mutable singletons into actors or main-actor types.
Allow @preconcurrency and @unchecked Sendable only with a written invariant and an owner, tracked so they get removed.
Keep each step shippable.
Declarative UI (React lineage)30-second answer
Explain Declarative UI (React lineage) in 30 seconds.
Declarative UI describes what the screen looks like for a given state, and the framework works out the updates.
In SwiftUI a view is a cheap value whose body is a function of state, so I update state, never views.
The nuances are identity, which decides whether state survives, and dependencies: a view re-renders when anything it reads changes, so body must stay pure and cheap.
Declarative UI (React lineage)SwiftAsked directly
Imperative UIKit vs declarative SwiftUI: what fundamentally changes in how you update the screen?
UIKit views are long-lived objects you mutate with commands, like label.text = name.
SwiftUI views are cheap structs whose body describes the UI as a function of state.
When state changes, body runs again and produces a new description, and SwiftUI diffs it against the screen, including list insertions and deletions.
Your job shifts from sequencing updates to modeling state.
That's why the bugs move from forgotten updates to identity and state ownership.
A search field and a results list are siblings. Where does the query live, and how does the field change it?
Lift the query into the closest common parent as @State private var query = "" and pass it down.
The field gets $query as a Binding, and the list gets the value.
Results are derived, so compute them instead of storing them.
Data flows down and changes flow up through the binding, which is SwiftUI's version of passing a setter.
State Management30-second answer
Explain State Management in 30 seconds.
SwiftUI state is about ownership.
@State is owned by the view, @Binding borrows a parent's value, @Environment hands dependencies down the tree, and @Observable models hold shared data with per-property tracking.
My first question is who owns this state: one source of truth, everyone else borrows it.
The common bugs are duplicated state that drifts and initializing @State from a parameter.
State ManagementSwiftAsked directly
With an @Observable model, how do you choose between @State, @Environment, @Bindable, or a plain property?
Ask three questions.
Does this view own the model?
Use @State.
Does it come from far up the tree?
Use @Environment.
Does the view only need bindings to edit it?
Use @Bindable.
Otherwise use a plain let.
With Observation, views re-render only when properties they actually read in body change, so the wrapper only decides ownership and lifetime.
State ManagementiOS codingAsked indirectly
A child Play button must toggle the parent's isPlaying, but passing a copy loses sync. What's the correct wiring?
The parent owns @State private var isPlaying = false.
The child declares @Binding var isPlaying: Bool with no default, and the parent passes $isPlaying.
Now there's one source of truth, and the child reads and writes it without owning it.
Reading it in body creates the dependency, so SwiftUI updates both views with no manual syncing.
State ManagementSwiftAsked indirectly
After migrating to @Observable, a screen's model resets whenever its parent redraws. What's wrong?
The view holds its @Observable model as a plain property, so every parent redraw creates a fresh instance and resets it.
Wrap it in @State private var model = Model() so it lives as long as the view's identity.
Only the view that creates the instance should use @State.
Views that receive it take a plain property or @Bindable.
State ManagementSystem designAsked indirectly
Two architecture proposals both handle model data fine. How do you compare them fairly?
Compare them on the three problems every architecture must solve.
How are components constructed and connected?
How do view and model communicate?
Where does non-model state, like selection and navigation, live?
Model data is the easy part, so proposals rarely differ there.
Ask each side to sketch the same feature and compare how they handle non-model state.
That's the deck. Shaky ones will lead next time. 🎃