One card at a time. Say your answer out loud, reveal, then rate yourself. Shaky cards come back first next time, in this browser.
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.
MVC costs almost nothing to write, which is why I use it only where there's no logic to move: About, legal or debug screens.
For a substantial app I default to MVVM with a Router, because the risk is business logic with no home outside the controller.
A screen that stays thin is what would keep me on MVC.
MVCSwiftAsked directly
What is "Massive View Controller" actually a symptom of?
A missing model layer.
In MVC the model is meant to hold the business logic and data access, not just plain structs.
When it holds only structs, networking, caching, validation and state all land in the view controller, the only class left. The size is just the symptom.
The fix is giving the model real objects, like a NotesStore that owns loading, saving and the current state.
The view controller goes back to being glue, and the logic becomes 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 holds its own copy of the notes, so there's no single source of truth and every edit has to be pushed by hand.
I'd first check who writes the notes today, because two copies also mean two writes that can diverge.
Then I'd make one store object own the notes and have both screens observe it through @Observable, a delegate or a notification.
View controllers render state they don't own and never push data into each other.
I'd fix ownership before touching file size.
MVCiOS codingAsked indirectly
You inherit a 1,500-line view controller. What do you extract first, and why in that order?
I wouldn't start by converting it to MVVM.
First I cover the critical user journeys with tests and map async work, lifecycle dependencies and shared state.
Then I extract by risk: pure validation and transformation logic, networking and persistence behind boundaries, self-contained subviews, presentation state into a ViewModel, and navigation last, only if it's complex.
That order is a default: if database work stalls the main thread, isolate persistence first. 1,500 lines is a signal to investigate, not proof you need a new architecture.
MVCSystem designAsked indirectly
When would you move a team off plain MVC, and how?
When keeping it consistent costs more than adding structure, and before view controllers get massive.
The signals: business logic tied to UIKit or the lifecycle, complex state transitions, tests that must load view controllers, navigation coupled across screens, and repeated regressions.
Team size multiplies these; it doesn't decide.
Then I name the real pain points, set principles like state ownership and dependency direction before picking a pattern, pilot one representative feature, and migrate incrementally while MVC coexists, with templates and test utilities as a paved road. I standardize boundaries more than patterns.
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 without importing UIKit, the Router owns navigation and builds the next screen, and the view only renders and forwards intent.
That makes presentation logic testable without a view and lets flows change without touching screens.
It's my production default once a screen has collections or several async sources.
The risk is a ViewModel that only forwards calls to a service, which adds indirection without separation.
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?
Network updates arrive off the main actor, so the view model applies them on @MainActor and the view never renders a half-updated state.
In SwiftUI, an @Observable view model invalidates only the views that read the changed properties.
In UIKit I'd use the same @Observable model: iOS 26 tracks reads in updateProperties() and layout methods automatically, and on earlier targets I'd use withObservationTracking or a closure.
I wouldn't let the network layer mutate view state directly, because then ordering bugs have no single owner.
MVVM (+ Router)System designAsked indirectly
Your team is debating MVC versus MVVM for a new app. What questions settle it?
My production default is MVVM with a Router because it isolates presentation state (testable without UIKit) and navigation (reusable screens) from view lifecycle without VIPER's ceremony, and @Observable avoids RxSwift/Combine binding overhead.
MVC is the exception, for static screens like Settings. What settles it: long-lived or prototype? Collections or complex stateful elements? Async updates from several sources?
Multiple teams or AI agents editing it?
Complexity and expected evolution matter far more than team size: optimize for changing code safely tomorrow, not writing it fast today.
MVVM (+ Router)System designAsked indirectly
Your team wants MVVM but refuses to adopt a reactive framework. Is that viable?
Yes, because observation ships with the platform.
On iOS 17 and later an @Observable view model needs no third-party framework, and a plain onChange closure works on any target.
Immutable models passed through init need no binding at all.
The real decision is how state reaches the view on our minimum OS version.
A reactive library is a long-term dependency the whole team must learn, so I'd only adopt one for stream-shaped work like debounced search.
MVVM (+ Router)System designAsked indirectly
A year after moving to MVVM, view models are 800 lines. What went wrong?
The line count alone doesn't tell me much, so I'd look at what keeps changing the file.
If networking, persistence or business rules moved in, the view model became the new massive view controller.
I'd keep it to presentation state and user intents on the main actor, and move rules and resource access into services behind protocols, so each concern has one owner.
I wouldn't split it into smaller view models mechanically.
In review, a view model touching URLSession or the database directly is my signal to act.
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: extra pass-through layers fragment context and cause partial edits.
So I favor MVVM + Router and unit tests even for small production apps.
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 rules with no UIKit import.
The Presenter formats results, handles input and decides when to navigate.
The Router performs the transition because it owns the view controllers.
The View is passive behind a protocol, and Entities are plain data only the Interactor touches.
Separating the decision from the transition makes navigation testable without UIKit.
The cost is five types per screen, so I'd use it only where a feature has several independent reasons to change.
VIPERSystem designAsked indirectly
The team might replace Core Data next year. How do you keep business logic from depending on the persistence technology?
I'd put a seam exactly here, because storage is a likely change and wrapping everything isn't worth it.
The Interactor talks to a protocol like protocol OrderStore { func fetch() async throws -> [Order] }, and Core Data stays behind it.
I'd never hand managed objects up to the Presenter, since they're tied to their context and aren't Sendable.
I'd map them into plain structs at the boundary, so the compiler stops persistence types from leaking.
The cost is mapping code, which I accept only at seams like this.
VIPERSystem designAsked indirectly
Adopting VIPER produced many tiny files per screen and the team is frustrated. How do you adopt it pragmatically?
First I'd check whether every screen needed VIPER at all.
I use it for features with several independent reasons to change, so simple screens go back to MVVM with a Router.
Where VIPER stays, I'd let a trivial Presenter merge into its View, as long as each piece keeps one responsibility.
New features adopt it, but I wouldn't rewrite old ones.
What must stay consistent is where business logic lives and who owns state, not the file count per screen.
VIPERSystem designAsked indirectly
Your VIPER app has grown deeply nested business flows like login, onboarding and checkout, and many teams build on it. What starts to hurt next?
VIPER is screen-scoped, so three things start to hurt: cross-screen workflow state (auth, onboarding, checkout) leaks into presenters, five-file boilerplate taxes simple screens, and one composition root plus shared interfaces become build and merge bottlenecks.
You don't need RIBs to fix this: pull flow state into session-scoped state machines and coordinators, split teams into feature interface and implementation modules, and use compile-time DI.
Reach for RIBs only when many hierarchical business subtrees share one canvas, because its framework ceremony costs a steep ramp-up.
VIPERSystem designAsked directly
Why would a flow or business-logic node have no view controller at all, and what's the cleanup gotcha?
Some states are pure session logic with no screen of their own, like LoggedIn deciding between Onboarding, Home or Force-Update while owning user-scoped services.
Borrowing the parent's view controller avoids piling up empty container VCs.
The gotcha is teardown: UIKit automatically removes child views when a view controller pops, but detaching a viewless node (or session coordinator on logout) does not.
Its teardown hook must explicitly dismiss any screens it presented, or stale logged-in screens stay stuck on the stack.
VIPERiOS codingAsked indirectly
A child feature module needs the signed-in user's name. A teammate wants an optional property 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
About 40 teams ship into one iOS app, and a broken optional feature must never block the core flow. How do you isolate it?
Three options.
Core plus plugin protocols behind feature flags enforces one-way dependencies so switching off a broken feature can't break core, at the cost of plugin boilerplate and shared process crashes.
Server-driven UI enables instant rollback without a release, but struggles with offline or rich native flows.
Separate extensions give true crash isolation, with UX and IPC friction.
Assuming one native app, I'd pick core-plus-plugins with crash-loop kill switches and strict core review, reserving server-driven UI for high-churn promo surfaces.
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.
Because screens never know what follows them, one screen can serve two flows and a deep link becomes building a stack.
I add one when a screen is reused across flows or navigation depends on state.
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 each one to a single flow.
A coordinator is a plain object that owns the flow instead.
Parents keep children in var childCoordinators: [Coordinator] so they stay alive, and remove them when the child reports it's done.
Forget that removal and you leak whole flows.
I'd add coordinators when navigation is reused or conditional; for a linear two-screen flow, a closure from the parent is cheaper.
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.
An edit-profile screen needs to save via an API call. Does the POST belong in the view controller?
No, and not in the coordinator either.
The view controller reports “save tapped” with the edited values.
The view model or an interactor performs the save through an injected API client.
The coordinator only decides what happens next: dismiss, or show login if the session expired.
I keep “who changes data” apart from “who navigates”, because a coordinator that also saves can't be tested without a network and grows with every feature.
Unidirectional (TCA / Redux)30-second answer
Explain Unidirectional (TCA / Redux) in 30 seconds.
Unidirectional flow keeps a screen's state in one value that only a reducer can change.
The view sends actions, the reducer computes the next state, and side effects come back as new actions.
Every change is traceable and replayable, and tests assert the exact state after each action.
The cost is ceremony per event, so I use it for screens with many events and async flows, not simple forms.
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 that feed actions back in, while the Store runs the loop.
Because state only changes inside the reducer, every change is an action you can log, replay and test.
The cost is more setup than plain SwiftUI and a dependency the whole team must learn.
I'd adopt it for event-heavy async features, not as an app-wide default.
Do you need a Redux-style framework to get one-way data flow in UIKit?
No.
One-way flow means state changes in one place and the view only renders it.
In UIKit I'd keep a ViewState struct owned by the view model, send user input in as intents, and have the controller render the whole struct on each change.
That gives traceable updates without a dependency.
The cost is that nothing enforces it, so I'd back it with review rules and tests.
I'd only bring in TCA when many features need composition, effect cancellation and exhaustive tests.
Dependency Injection30-second answer
Explain Dependency Injection in 30 seconds.
I use dependency injection to make change cheap.
An object receives what it needs through its initializer instead of reaching for .shared, so its real dependencies are visible and tests can pass fakes.
Concrete types are chosen once, in a composition root.
I add protocols only at seams likely to change, like storage, networking and vendor SDKs, because a protocol per class is indirection with nothing behind it.
The hard part, and the main risk, is scoping lifetimes: 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?
My concern is the cost of change.
A locator hides each class's real needs behind lookup calls, so reading init no longer tells you what a type touches.
A missing registration fails at runtime instead of at build, and every test shares one global registry.
So I'd say no to the global locator and inject through init.
If the team wants a container like Swinject, I'd allow it only at the composition root, which keeps the convenience in one file and the dependencies visible everywhere else.
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, so structs and enums gain behavior without a base class.
The value I care about is the seam: a feature depends on a small protocol, which lets storage or a vendor SDK change behind it and lets tests pass fakes.
The cost is indirection, since readers jump through more files to find what runs.
I add a protocol only where something actually varies, and never one per class by reflex.
Protocol-Oriented ProgrammingSwiftAsked directly
some versus any: what's the real difference, and which should be your default?
I default to some P or generics, and use any P when the concrete type really varies at runtime.
An any P is an existential box, which may heap-allocate and keeps calls from being specialized.
The explicit any keyword exists to make that cost visible.
some P keeps the concrete type known to the compiler, so it can specialize and inline.
For an injected service doing I/O, I'd still accept any, because the box costs little next to the work behind it.
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 subsystem for every caller, and whoever owns that subsystem usually writes it.
A gateway is written by the consumer for its own needs: protocol PaymentsGateway speaks my app's terms and translates to the vendor's.
I'd write gateways for volatile vendor SDKs, like payments or analytics, where swapping later is plausible.
For a stable system API like FileManager, the translation layer is cost with no change to absorb.
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?
I'd wrap it behind a protocol in my app's terms, like protocol Analytics { func track(_ event: Event) }, so only one file imports the SDK.
Then I'd migrate the forty call sites incrementally while the old and new paths coexist, and swap vendors once nothing imports the SDK directly.
To prevent a repeat, I'd watch how many files import each third-party module.
I wouldn't wrap every library, only volatile vendor code, because each wrapper is API you maintain.
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?
I'd mark them package, which Swift 5.9 added.
Modules in the same package can call them, but code importing the package can't, so app code never builds a dependency on internals you meant to change.
Before package, sharing across modules meant public, which turned helpers into API.
I'd still keep the package surface small, because sibling modules can couple to it just as tightly as clients would.
Repository30-second answer
Explain Repository in 30 seconds.
A repository, which iOS code usually calls a store or client, gives features a small API like notes() and save(_:) and hides whether data comes from memory, disk or the network.
Its real job is policy: which source is the truth, when cached data goes stale, and how conflicts resolve.
For offline-first, local is the truth and the network is sync.
The cost is one more layer, so I skip it for a single endpoint with no caching.
RepositorySystem designAsked directly
What is the Repository pattern, and what does it centralize?
In iOS code it's usually a store or client: one type that owns access to a kind of data, like NoteStore.notes(matching:), so features ask for what they want and never see Core Data, files or endpoints.
It centralizes query construction and data policy, meaning caching, source of truth and mapping into plain structs.
I'd add one once several features read the same data or storage may change.
For one endpoint with no caching, I'd skip it, because it's a layer with nothing to hide.
RepositoryiOS codingAsked indirectly
You must ship a feature before the storage choice is decided. How do you avoid rewriting the view model later?
I'd define the protocol in the feature's terms, like protocol UserStore { func user(id: User.ID) async throws -> User? }, and inject it into the view model's init.
Making it async throws from day one matters, because an in-memory version that can't fail would let callers skip error handling the real store needs.
I'd ship with an in-memory actor, which doubles as the test fake, then swap in SwiftData or Core Data without touching the view model.
RepositorySystem designAsked indirectly
Similar query logic for the same entities is duplicated across many view models. Where should it live, and why?
I'd diff the copies first, because duplicated queries usually drift, and settle which behavior is correct before moving anything.
Then I'd give each entity one store, like OrderStore.orders(status:), so view models pass criteria and the store owns fetching and mapping.
I'd migrate one view model at a time behind tests.
If the copies are trivial one-line fetches, I'd leave them, because the layer would cost more than the duplication.
RepositorySystem designAsked indirectly
Five view models each call the network singleton directly. How do you restructure access to remote and disk data?
I'd move network and disk access behind injected stores, like ProfileStore, and stop view models reaching NetworkManager.shared.
The coordinator or composition root passes the store in, so each view model's dependencies show in its init and tests pass fakes.
I'd migrate one view model at a time, keeping the singleton behind the store until nothing else calls it.
It's still one shared object, but now it has one owner and a lifetime I can replace.
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?
In app code I default to a struct with default values, because memberwise init plus defaults already lets callers set only what they care about.
A builder still pays off when construction has steps or validation, when wrapping Objective-C APIs built on mutable objects, and in public frameworks that allow customization without exposing mutable properties.
Chained calls collect settings privately and build() returns an immutable result.
The cost is a second 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?
The root cause is a reference type crossing a boundary while someone still mutates it.
On iOS 15 and later I'd prefer Swift's AttributedString, a value type, so the database gets its own copy.
Where APIs still need NSAttributedString, I'd build into a private NSMutableAttributedString and have build() return an immutable copy.
Either way the caller can't change what it already handed off.
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.
Having one instance is fine; the damage comes from global access: 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, like logging, 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?
UserManager.shared hides who depends on it, carries state between tests, and lives for the whole run, so logout has to reset it by hand.
I'd first list its callers and what each uses, because that shows the small protocols to extract.
Then I'd make the singleton conform unchanged, inject it with init(users: UserManaging = UserManager.shared), and migrate one flow at a time, starting where tests hurt most.
The singleton becomes an implementation detail I can retire later.
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?
I'd share through injection rather than global access.
A factory or session object owns the shared pieces, like the image cache and URLSession, and creates fresh objects for anything per consumer, like request queues.
Every screen shares the cache, yet its dependencies stay visible in init and replaceable in tests.
The cost is that someone must own each lifetime.
For anything holding user data, I'd make that owner the user session, so logout drops it.
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?
I'd scope session state to the user, because the real bug is giving it app lifetime.
I'd introduce a UserSession that owns the session, caches and user services, then migrate one flow at a time, starting where SessionManager.shared is read most.
During migration the singleton can forward to the active session, so old and new code coexist.
Truly app-wide pieces, like a cache of public assets, can stay global.
Signing one account out then drops exactly its graph.
Services vs SingletonsSystem designAsked directly
The AppDelegate holds the API client, the cache and the current user. What test decides what may stay global?
I'd ask three questions of each object: does something else naturally own it, must there be exactly one, and is it mutable state rather than a constant?
My call here is that the current user and the API client move into a session object, because the session owns them and auth changes with the user.
Only the cache could stay app-wide, reached through an injected protocol.
If the cache holds user data, it moves into the session too.
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 inward only, so inner layers never name outer types, including UIKit or Core Data.
When a use case must push results out, it calls a protocol it owns, like protocol OrderOutput { func present(_ orders: [Order]) }, and the presenter conforms.
Control flows out while the import still points in.
In an MVVM feature I'd usually skip the output protocol, because the use case can return values and the view model publishes the state.
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?
I'd keep business rules in plain Swift types with no UIKit or AppKit import, in a shared module, so all three apps compile the same logic and test it once.
View models can often be shared too, since SwiftUI runs on all three.
I'd split views where layout and input differ, like sidebars and menu commands on Mac, and keep persistence behind a store protocol.
The risk is forcing one view hierarchy onto every platform, which makes the Mac app feel like a port.
Decoupled LayersSystem designAsked indirectly
Rules like whether a user can comment are copied across view controllers and a global helper. Where should they live?
I'd give the rule one home: a small viewless type that owns the model and exposes purpose-built answers, like var canComment: Bool.
View controllers ask it instead of recomputing, and the global helper goes away, so the rule has one tested code path.
I wouldn't put it on the plain model struct if it needs services or the session.
I'd avoid a global too, because that drags in shared mutable state.
The cost is an 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?
What I gain is cheaper change.
A feature builds and previews without compiling the whole app, the compiler enforces which features can see each other, and ownership maps to modules.
App Clips and extensions can link only what they need.
The cost is Package.swift wiring, cross-module refactors and access control everywhere.
I wouldn't start with dozens; I'd split when build times hurt, teams collide in the same code, or boundaries keep getting bypassed.
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?
Before restructuring, I'd add a debug launch argument that resets first-launch state, because that fixes QA's loop today at almost no cost.
If onboarding changes often, I'd move it into its own module and build a small preview app from only the modules it needs, so the flow runs standalone with injected fake state.
That only works if the module doesn't depend on the app target, which is exactly the discipline it enforces.
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?
I'd weigh it by what changes and who collides, with headcount only as a multiplier.
A plugin architecture adds interface modules, registration and upfront contract design, and a central group approving core changes becomes a queue.
Those costs pay off when features have independent lifecycles, ship in parallel, or the domain needs hard boundaries.
I'd start with logical boundaries, add physical modules where builds or ownership hurt, and use plugins only where runtime swapping is real.
Delegate30-second answer
Explain Delegate in 30 seconds.
A delegate is one owner answering a component's questions and events through a protocol, the way a table view asks its data source.
The component holds it weak, which breaks the ownership cycle.
I'd use it when there are several related callbacks and exactly one listener.
A single callback gets a closure, and broadcasts get pub/sub.
The risk is silence, because an optional delegate nobody set just does nothing.
So when an answer is required, I take a closure in init.
DelegateSwiftAsked directly
Delegate protocol or closures: how do you choose for a component's callbacks in Swift?
I choose by the shape of the conversation.
One event, or one required answer, gets a closure in init, so the dependency can't be forgotten.
Several related events for one owner get a delegate protocol, because it groups them in one documented type and default extensions let conformers implement only what they need.
Closures cost a deliberate capture list each, while a delegate is a single weak reference.
I'd standardize the convention per layer, so reviewers and AI agents don't have to guess.
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 screen owns the component strongly, and the component holds the screen as a strong delegate, so neither reference count reaches zero.
I'd declare weak var delegate: PickerDelegate? and constrain the protocol to AnyObject, because weak only applies to class references.
Then I'd confirm it in Xcode's Memory Graph Debugger, rather than trusting a deinit print.
To stop the next one, I'd add a test that releases the owner and asserts the component deallocated too.
DelegateiOS codingAsked indirectly
A tap inside a deeply nested child view controller must trigger navigation owned several levels up. How do you route it?
I'd have the child report intent, like didSelect(item), and leave the navigating to someone else.
Each parent forwards it up until it reaches whoever owns navigation.
In my default that's a router, so the relay chain stays short and screens never import each other.
Children never walk the parent hierarchy, which keeps them reusable and testable in isolation.
The cost is forwarding boilerplate at every level.
If intent hops through several layers that don't care about it, the navigation owner is in the wrong place.
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?
I'd keep the screen as the single delegate and have it forward what each component needs, because ownership stays obvious and nothing has to multiplex.
What would change my mind is components that must work on any screen without wiring.
Then I'd install a proxy that forwards each call to every target and answers responds(to:) for any of them, because UIKit only calls methods the delegate says it implements.
Value-returning methods, like scrollViewShouldScrollToTop(_:), need an explicit winner.
Pub/Sub30-second answer
Explain Pub/Sub in 30 seconds.
Pub/sub lets one publisher reach any number of subscribers without knowing them.
On iOS that's NotificationCenter, Combine subjects, or state observed through @Observable.
I use it for broadcasts, like sign-out or a settings change, and never for something that needs an answer.
The cost is invisible coupling, because you can't find the listeners by reading the sender.
Delivery happens on whatever thread posted, and every subscription has a lifetime someone must own.
For one owner, I'd use a delegate or a closure.
Pub/SubSwiftAsked directly
Compare delegation, NotificationCenter and KVO by coupling and fan-out. When does each fit?
I'd sort them by who needs to know.
A delegate is one listener behind a typed protocol, so the sender can ask questions and get answers.
NotificationCenter reaches any number of listeners the poster can't see, which suits app-wide events but hides who reacts.
KVO watches one property on one object, and it only works on NSObject subclasses with @objc dynamic.
In Swift models I'd reach for @Observable instead.
The cost rises with fan-out, because every extra listener makes a change harder to trace.
Pub/SubiOS codingAsked indirectly
A notification handler updates a label and sometimes misbehaves or crashes. What do you check?
I'd check the thread first.
Observers run synchronously on the posting thread, so a post from a background queue updates UIKit off the main thread, which the Main Thread Checker flags.
Passing queue: .main moves delivery to the main queue.
Next I'd check lifetime, because the center keeps the block alive until its token is removed.
A block capturing self strongly keeps the screen alive and still reacting.
I'd capture [weak self] and remove the token in deinit.
In Swift 6 code I'd iterate notifications(named:) in a task the screen owns instead.
Pub/SubSystem designAsked indirectly
NotificationCenter is used everywhere and nobody knows who reacts to what. How do you make observation safer and clearer?
I'd start with an inventory of every notification name, who posts it and who observes it.
Some turn out to be one-to-one calls in disguise, and those become a delegate, a closure or a direct call.
The real broadcasts get typed channels, either observer protocols or, on iOS 26, NotificationCenter message types with a typed payload.
Old and new coexist while I migrate one name at a time.
The cost is more declared types, and that's deliberate.
A reader, or an AI agent, can find every listener by searching for one type.
Pub/SubiOS codingAsked indirectly
Your custom observer list keeps observers alive long after their screens close. How do you fix the storage?
The list holds observers strongly, so it keeps alive screens it should only notify.
I'd store a box with weak var observer: AnyObject? and prune empty boxes on every notify.
Keying by ObjectIdentifier makes removal cheap, but an identifier can be reused once its object deallocates, so stale entries must go before a new object registers.
I'd also make the list @MainActor or an actor, since adds and notifies come from different places.
On Apple platforms NSHashTable.weakObjects() gives you the weak storage.
Pub/SubiOS codingAsked indirectly
A shared player takes observation closures, and old screens keep reacting after they're gone. What's the design flaw?
The player stores closures with no removal path, so each one keeps its captures alive and keeps running after its screen is gone.
A cancel token helps, but people forget to cancel, which is the bug you already have.
I'd make the token cancel in its own deinit, the way Combine's AnyCancellable does.
Then storing it on the screen ties observation to the screen's lifetime automatically.
I'd only take the observer weakly instead when callers can't hold a token, like fire-and-forget registrations from Objective-C.
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?
Short term, I'd make each function single-exit.
It computes one Result and calls completion from a defer, so every path calls it exactly once.
Then I'd remove the bug class with async throws, where the compiler requires a return or a throw on every path.
In a large codebase I'd add an async wrapper with a checked continuation, migrate callers, then invert it so the async version is the real implementation.
I wouldn't convert everything in one pass, because each caller's threading assumptions need checking.
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.
Promises turned a callback into a value you could chain. async/await moved that into the language: an async function suspends, then returns or throws exactly once, and the compiler checks every path.
I bridge each legacy callback API once, at the boundary, with withCheckedThrowingContinuation.
A double resume then traps in any build, instead of silently doing the work twice.
The risks that remain are cancellation, which is cooperative, 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?
I'd start a Task in the handler.
Because the handler is on the main actor, the task inherits it, so after each await I can update UI directly and catch errors in a normal do/catch.
The task captures self until it finishes, which is fine for a quick save.
For longer work I'd store the handle and cancel it when the screen goes away or the work is superseded.
I'd also disable the button, so a double tap can't start two saves.
When several handlers need this, the task belongs in the view model.
Swift 6 Concurrency30-second answer
Explain Swift 6 Concurrency in 30 seconds.
Swift 6 turns data races into compile errors.
Every piece of mutable state belongs to one isolation domain, an actor or the main actor, and only Sendable values cross between domains.
What it can't catch are logic races.
An actor is reentrant, so its state can change across any await.
Cancellation is cooperative, so superseded work still finishes unless it checks.
I keep UI state on the main actor, re-check invariants after every await, and cancel work when its input changes.
Swift 6 ConcurrencySwiftAsked directly
Swift 6 makes data races compile errors. What concurrency bugs can you still ship?
Logic races are still possible, because the compiler checks isolation rather than intent.
Actor reentrancy breaks read-await-write sequences, since state can change at any suspension point.
Missing cancellation lets superseded work finish and publish stale results.
Heavy synchronous work can land on the main actor, because a Task {} inherits its caller's actor, and with approachable concurrency so do nonisolated async functions.
Blocking a cooperative-pool thread on a semaphore can stall unrelated tasks.
I'd look for all four in code review.
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?
I'd run it as shippable steps.
First I turn on complete concurrency checking as warnings, module by module, leaves first, and track the count per module.
That map shows where shared mutable state really lives.
Then UI types get @MainActor, or default main-actor isolation in app targets, and singletons become actors or main-actor types.
Callback SDKs get wrapped once at the boundary.
@preconcurrency and @unchecked Sendable need a written invariant and an owner.
A module flips to Swift 6 mode once it's clean.
Declarative UI (React lineage)30-second answer
Explain Declarative UI (React lineage) in 30 seconds.
Declarative UI describes the screen 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 change state and let SwiftUI diff the result.
The bugs move to identity and dependencies.
Identity decides whether state survives, so swapping branches in an if resets it.
Dependencies decide what re-evaluates, because anything body reads can trigger it.
That's why I keep body 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 and lifetime.
@State storage belongs to the view's identity, which is why it survives body re-running.
@Binding borrows a parent's value, @Environment passes dependencies down the tree, and an @Observable model tracks which properties each view reads.
My default is one @Observable view model per screen, owned with @State, with navigation in a router.
The common bugs are duplicated state that drifts, and @State seeded from a parameter, which ignores later updates.
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() in the owning view only, and pass a plain property or @Bindable to receivers.
Keep Model.init cheap and side-effect-free: unlike @StateObject, @State evaluates the initializer on every parent redraw and discards extra instances.
State ManagementSystem designAsked indirectly
Two architecture proposals both handle model data fine. How do you compare them fairly?
I'd compare them on four boundaries: where business logic lives, who owns non-model state like selection, loading and navigation, how dependencies are injected, and how behavior is tested without the UI.
Then both sides build the same representative feature, one with async loading and navigation, and I compare the diffs and the tests.
I'd pick whichever makes the next change easier to get right, even if it's more code today.
Without contrary evidence, I'd expect MVVM with a router to win, because state ownership and navigation each get one home.
That's the deck. Shaky ones will lead next time. 🎃