Interview Preparation

Follow role- and difficulty-specific interview questions that point back to shared canonical engineering answers.

~2 hr 7 min reading~3 min practice estimate
Suggest content

Interview Paths: Senior, Lead, Staff, and Architect

Use these maps to practice by role and seniority. Answer one main question, then read its short teaching answer and detailed explanation. Related concept links provide further background, and optional follow-up questions let you explore a topic more deeply.

All applied examples below are illustrative, uncompiled Swift 6+ snippets or explicitly labeled planning artifacts. Some are member/body excerpts whose named application dependencies come from the surrounding feature; SwiftUI Observation examples assume iOS 17+ and newer APIs require their own deployment checks. They demonstrate the local answer while the linked concept remains the full reference.

Senior iOS Developer

Intermediate

When should a dependency use a concrete type, a protocol, or a generic?

Short answer: Use a concrete type for one known implementation. A protocol-typed value, called an existential, can hold different implementations while hiding their concrete type; a generic keeps the caller’s concrete type and its relationships visible to the compiler. Choose the form that preserves the relationships the feature needs.

Detailed explanation:

Answer focus: Preserve useful type relationships, introduce an abstraction at a real boundary, and avoid protocolizing every type. Compare tradeoffs using the protocol and generic guide.

Optional follow-up questions

When does an associated type make an existential awkward?

Applied example — illustrative:

SWIFT
protocol TitleProviding { var title: String { get } }
struct PaymentTitle: TitleProviding {
    let title = "Payment"
}
func concreteTitle(_ source: PaymentTitle) -> String { source.title }
func preserveType<T: TitleProviding>(_ source: T) -> T { source }
func displayedTitle(_ source: any TitleProviding) -> String { source.title }
let concrete = PaymentTitle()
let sameType: PaymentTitle = preserveType(concrete)
let erased: any TitleProviding = concrete
print(concreteTitle(sameType), displayedTitle(erased))

The concrete parameter intentionally accepts only PaymentTitle; the generic preserves its caller-selected T; the existential stores any conformer behind the small display contract. Choose the boundary for its needed type relationships and substitution, rather than assuming any form is universally faster.

How do you give a SwiftUI child view editable state?

Short answer: Keep the editable value in the view or model that owns it. Give the child a binding, which lets it read and update that same value. A binding connects the child to existing state; it does not create a second copy of the state.

Detailed explanation:

Answer focus: The owner stores the source of truth; a child receives a Binding when it needs read/write access. See SwiftUI state ownership.

Optional follow-up questions

How is @Bindable different when using Observation?

Applied example — illustrative:

SWIFT
import SwiftUI
struct NameField: View {
    @Binding var name: String
    var body: some View { TextField("Name", text: $name) }
}
struct ProfileForm: View {
    @State private var name = ""
    var body: some View { NameField(name: $name) }
}

The parent owns persistent state and passes a writable projection to the editor. An Observation-based reference model instead uses @Bindable to create bindings; neither binding wrapper creates a second authoritative name.

How do you prevent an older search response from replacing newer results?

Short answer: Only the newest search request should be allowed to update the screen. Cancel older work when possible, and check a request identifier before displaying its result. Cancellation saves work, while the identifier check prevents an older response from replacing newer results.

Detailed explanation:

Answer focus: Own and cancel prior work, check cancellation after suspension points, and enforce the latest-query invariant before publishing state. Review the stale-result example.

Applied example — illustrative:

SWIFT
@MainActor
func search(_ query: String) async throws {
    generation += 1
    let request = generation
    let loaded = try await service.search(query)
    try Task.checkCancellation()
    guard request == generation else { return }
    results = loaded
}

This screen-model method assumes MainActor-owned generation/results and a Sendable search service. Cancellation reduces wasted work; the generation guard separately prevents an earlier completion from publishing, including an A → B → A query sequence.

How does copying a value differ from sharing an object?

Short answer: Copying a value gives you logically independent data, while two object references can point to the same instance. Copy-on-write is an optimization that lets value copies share storage until a change requires separate storage. It preserves independent values without copying every buffer immediately.

Detailed explanation:

Answer focus: Value semantics describe independent logical values; reference identity means two references can point to the same instance. Copy-on-write can defer a value's physical buffer copy until mutation, so it preserves value semantics without eagerly copying all storage. See struct versus class.

Applied example — illustrative:

SWIFT
struct Preferences { var tags: [String] }
var first = Preferences(tags: ["swift"])
var second = first
second.tags.append("ios")
print(first.tags, second.tags)
final class Session { var signedIn = false }
let original = Session()
let alias = original
alias.signedIn = true
print(original === alias, original.signedIn)

Array copy-on-write may share storage before mutation while preserving the independent values of first and second. The class aliases share one instance, so a let reference does not freeze that instance’s mutable state.

When would you choose an enum with associated values instead of a protocol hierarchy?

Short answer: Choose an enum when you own a known set of cases and want every case handled explicitly. Choose a protocol when different implementations should provide the same behavior and new implementations may be added independently. The choice depends on whether the set of possibilities is closed or open.

Detailed explanation:

Answer focus: Choose a finite, centrally owned set with exhaustive handling as an enum; choose an open set of implementations behind behavior as a protocol. Compare enum and protocol tradeoffs.

Applied example — illustrative:

SWIFT
enum PaymentState {
    case idle
    case authorizing(operationID: String)
    case failed(message: String)
}
func message(for state: PaymentState) -> String {
    switch state {
    case .idle: return "Ready"
    case .authorizing: return "Authorizing"
    case .failed(let message): return message
    }
}

The finite screen state makes every rendering case explicit, and adding a case forces handling to be reviewed. A protocol is more suitable for independently added payment-provider implementations; it does not enforce a closed list of UI states.

What is the difference between Sendable and Codable?

Short answer: Sendable describes values that can safely cross concurrency boundaries. Codable describes values that can be encoded and decoded, such as when saving data or reading JSON. A type may support both, but neither capability automatically provides the other.

Detailed explanation:

Answer focus: Sendable is about safe concurrency transfer; Codable is about serialization. A type can need both, but neither implies the other. See the concurrency contract.

Applied example — illustrative:

SWIFT
import Foundation
struct AccountSnapshot: Sendable, Codable {
    let id: String
    let balanceCents: Int
}
actor AccountCache {
    private var current: AccountSnapshot?
    func store(_ snapshot: AccountSnapshot) { current = snapshot }
}
let bytes = try JSONEncoder().encode(
    AccountSnapshot(id: "account-1", balanceCents: 200)
)

Codable supports the encoding operation; Sendable permits this immutable snapshot to cross isolation boundaries safely. Neither conformance validates financial meaning, authorization, or whether the snapshot is current.

What do primary associated types let an API express?

Short answer: They let an API specify an important related type without choosing a particular implementation. For example, an API can require a loader that returns a list of names while allowing several ways to load those names. This makes the required relationship clearer at the point where the API is used.

Detailed explanation:

Answer focus: They let an API name important associated types at a use site and apply same-type constraints, while the conformer still chooses the associated type. Review associated types and primary associated types.

Applied example — illustrative:

SWIFT
protocol Loading<Value> {
    associatedtype Value
    func load() async throws -> Value
}
struct NameLoader: Loading {
    func load() async throws -> [String] { ["Ada", "Lin"] }
}
func names(from loader: any Loading<[String]>) async throws -> [String] {
    try await loader.load()
}

The primary associated type lets the existential constrain its output to [String], while each conformer still selects Value. A generic remains useful when the API needs to preserve the concrete loader type or relationships beyond that output constraint.

Advanced

How do you apply dependency inversion without adding needless layers?

Short answer: A feature should depend on the behavior it needs rather than on a particular database or network implementation. Define a small contract at a useful boundary and supply the implementation when constructing the feature. Add that boundary where replacement, ownership, or testing benefits justify it.

Detailed explanation:

Answer focus: Put an abstraction at a meaningful change, ownership, or test boundary; inject it at the composition root; keep the contract small. The dependency inversion explanation is authoritative.

Optional follow-up questions

Where should the live implementation be constructed, and how would you test the consumer?

Applied example — illustrative:

SWIFT
protocol PriceLoading { func priceCents() throws -> Int }
struct PriceLabel {
    let loader: any PriceLoading
    func text() throws -> String { "\(try loader.priceCents()) cents" }
}
struct StoredPrice: PriceLoading {
    let read: () throws -> Int
    func priceCents() throws -> Int { try read() }
}
func makePriceLabel(readDatabase: @escaping () throws -> Int) -> PriceLabel {
    PriceLabel(loader: StoredPrice(read: readDatabase))
}

PriceLabel owns a narrow capability and has no database import; makePriceLabel is the composition root where the live database read is supplied. The adapter is worthwhile at this replaceable data boundary; a pure formatter with no changing dependency could stay concrete.

Consumer test — same contract, controlled response:

SWIFT
import Testing
struct FixedPrice: PriceLoading {
    let cents: Int
    func priceCents() throws -> Int { cents }
}
@Test func formatsLoadedPrice() throws {
    let label = PriceLabel(loader: FixedPrice(cents: 250))
    #expect(try label.text() == "250 cents")
}

The stub supplies data while the test checks the real consumer’s result; it does not merely assert that an initializer stored the dependency. Compare the worked mobile DIP scenario for a concrete change trigger, dependency direction, assembly, and tradeoff.

How do you decide what belongs in a unit, integration, or UI test?

Short answer: Unit tests check small rules in isolation, integration tests check collaborating parts, and UI tests check a user journey through the app. Put each risk at the lowest level that can reliably expose it. Keep a smaller set of UI tests for important journeys that need the real interface.

Detailed explanation:

Answer focus: Test behavior at the narrowest reliable boundary, reserve UI tests for user-visible flows, and inject nondeterministic inputs. See testing boundaries.

Optional follow-up questions

How do you make cancellation and time deterministic in tests?

Applied example — illustrative:

SWIFT
import Testing
func canWithdraw(balance: Int, amount: Int) -> Bool {
    amount > 0 && amount <= balance
}
@Test func rejectsInvalidWithdrawalWithoutNetworking() {
    #expect(!canWithdraw(balance: 100, amount: -1))
    #expect(!canWithdraw(balance: 100, amount: 101))
    #expect(canWithdraw(balance: 100, amount: 100))
}

This pure rule belongs in a unit test; a repository plus real temporary store belongs in an integration test. Reserve a UI test for the user-visible withdrawal/error journey, so failures reveal which boundary broke.

How do you diagnose a production regression without guessing?

Short answer: First establish which users and actions are affected, and compare the failing release with a known baseline. Reduce exposure if users are at risk, then use measurements and a reproduction to test a specific explanation. Verify the repair against the same failing journey rather than treating a passing unrelated test as proof.

Detailed explanation:

Answer focus: Establish impact and a baseline, correlate release/version and device cohorts, use privacy-safe telemetry, mitigate first, then verify a targeted fix. See reliability and incident response.

Applied example — illustrative:

YAML
incident: launch_failure_after_release
first_checks:
  - compare_same_device_os_cohorts_by_app_version
  - inspect_symbolicated_crash_signatures
  - verify_release_and_feature_exposure_timeline
mitigation:
  owner: mobile_on_call
  action: pause_exposure_and_disable_optional_startup_refresh
verification: reproduce_signature_then_compare_matched_cohorts

This is an incident-plan artifact, not a measured incident or an executable runbook. It separates evidence and mitigation from the later root-cause fix and avoids logging account payloads to explain a version-correlated crash.

What lifetime and isolation risks come with an escaping closure?

Short answer: An escaping closure can run after the function that received it has returned, so captured objects may stay alive longer than expected. Check both who owns the closure and where it is allowed to access shared state. A weak capture can help with lifetime, but it does not make concurrent access safe.

Detailed explanation:

Answer focus: An escaping closure can outlive its call, so inspect captured references for retain cycles and make actor isolation explicit at the call boundary. [weak self] is appropriate when the callback should not keep its owner alive, but it is not a universal fix. Review ARC and actor isolation.

Applied example — illustrative:

SWIFT
@MainActor
final class DraftEditor {
    var text = ""
    var onSave: (@MainActor () -> Void)?
    func configure() {
        onSave = { [weak self] in
            guard let self else { return }
            print("Saving \(self.text.count) characters")
        }
    }
    func finish() { onSave = nil }
}

The stored escaping callback would otherwise complete an owner → closure → owner cycle. Its MainActor function type also makes invocation isolation explicit; weak ownership alone does not make callbacks safe to call from arbitrary threads.

When is it safe to use unchecked Sendable?

Short answer: Use unchecked Sendable only when a documented synchronization design already makes the type safe and the compiler cannot prove that safety. The annotation asks the compiler to trust your promise; it does not add locks or protect mutable data. Every access to the protected state must follow that design.

Detailed explanation:

Answer focus: Only when a real, documented synchronization invariant makes cross-task access safe and the compiler cannot prove it. It suppresses checking; it does not synchronize. See the unchecked conformance guidance.

Applied example — illustrative:

SWIFT
import Foundation
final class LockedCounter: @unchecked Sendable {
    private let lock = NSLock()
    private var value = 0
    func increment() {
        lock.lock(); defer { lock.unlock() }
        value += 1
    }
    func snapshot() -> Int {
        lock.lock(); defer { lock.unlock() }
        return value
    }
}

Every read and write is private and protected by the same lock, with no suspension or reference escape from the critical section. This is the synchronization invariant being asserted, not safety created by @unchecked; prefer a checked synchronization abstraction when supported and re-audit every new accessor. Swift Sendable responsibilities

How do you bridge a callback API to async/await safely?

Short answer: A continuation lets an asynchronous function wait for a callback-based operation. Complete it exactly once on every success or failure path, and coordinate cancellation with the underlying operation when possible. A checked continuation helps detect misuse, but it does not decide the operation’s lifetime for you.

Detailed explanation:

Answer focus: Use a checked continuation for one completion, guarantee exactly one resume, cover errors and every terminal path, and propagate cancellation when supported. See continuation bridging.

Applied example — illustrative:

SWIFT
import Foundation
protocol LegacyReading {
    func read(_ completion: @escaping (Result<Data, Error>) -> Void)
}
func readAsync(_ source: any LegacyReading) async throws -> Data {
    try await withCheckedThrowingContinuation { continuation in
        source.read { result in
            continuation.resume(with: result)
        }
    }
}

This adapter assumes the legacy API invokes completion exactly once on every terminal path. It does not magically cancel the underlying read: a cancellable API needs a synchronized cancellation/completion state machine, with exactly one continuation resume even when the two race.

What is priority inversion, and how do you respond to it?

Short answer: Priority inversion happens when urgent work waits for a resource held by less urgent work. Keep the protected work short, avoid blocking waits, and investigate the actual dependency before changing priorities. Raising a priority alone does not remove the dependency that caused the delay.

Detailed explanation:

Answer focus: A high-priority task can be blocked behind a lower-priority lock/resource holder while other work delays the holder. Keep critical sections short and measure before tuning priorities; see priority inversion.

Applied example — illustrative:

SWIFT
import Foundation
final class CachedNames {
    private let lock = NSLock()
    private var names: [String] = []
    func snapshot() -> [String] {
        lock.lock(); defer { lock.unlock() }
        return names
    }
    func replace(with loaded: [String]) {
        lock.lock(); defer { lock.unlock() }
        names = loaded
    }
}

Fetch and decode before replace, so the lock protects only the small state transition rather than slow I/O. A high-priority reader can still wait for the current holder; short critical sections reduce the dependency bottleneck without treating priority changes as a correctness fix.

Can an actor’s state change while its method is waiting?

Short answer: Other work can run on an actor while its method is waiting for an asynchronous operation. When the method continues, values checked earlier may have changed. Recheck the required conditions or record a deliberate reservation before waiting.

Detailed explanation:

Answer focus: The actor can run other work at a suspension point, so state may no longer satisfy assumptions made before await. Revalidate invariants or reserve a deliberate state transition; see actor reentrancy.

Applied example — illustrative:

SWIFT
actor Inventory {
    private var available = 1
    func reserve(check: @Sendable () async throws -> Void) async throws -> Bool {
        guard available > 0 else { return false }
        try await check()
        guard available > 0 else { return false }
        available -= 1
        return true
    }
}

Another reservation can complete during check(), so the second guard revalidates local state before an uninterrupted mutation. If check performs an external charge, this local repair is insufficient: authorization, reservation rollback, and idempotency need a separate transaction policy.

How do structured child tasks, Task, and Task.detached differ?

Short answer: Structured child tasks belong to a parent scope, which waits for them and propagates cancellation. Task creates unstructured work that normally inherits the surrounding actor context, priority, and task-local values. Task.detached creates independent work without that inheritance, so its lifetime and context need explicit management.

Detailed explanation:

Answer focus: Structured child tasks are scoped to a parent; Task is unstructured but inherits context; detached work deliberately drops actor, task-local, and priority inheritance. See task lifetime choices.

Applied example — illustrative:

SWIFT
func combinedTitle() async -> String {
    async let first = loadTitle(id: "first")
    async let second = loadTitle(id: "second")
    return await first + " / " + second
}
@MainActor
func beginOwnedRefresh() {
    refreshTask?.cancel()
    refreshTask = Task { await model.refresh() }
}

The first function’s children cannot outlive its scope; loadTitle is an injected async operation. The screen excerpt owns an unstructured handle and its cancellation; detached work would also drop inherited context and still need an owner, rather than becoming structured when awaited.

Which kind of test should verify a particular behavior?

Short answer: Use a unit test for a rule such as discount calculation, an integration test for a repository working with storage, and a UI test for a checkout journey. Choose the smallest test that can reveal the relevant failure. This gives faster, clearer feedback while retaining coverage of important user flows.

Detailed explanation:

Answer focus: Test at the narrowest stable boundary that proves the behavior; use UI tests for important user-visible journeys, not every branch. See testing boundaries.

Applied example — illustrative:

SWIFT
import XCTest
final class LoginJourneyTests: XCTestCase {
    func testInvalidCredentialsShowRecovery() {
        let app = XCUIApplication()
        app.launchArguments = ["--fixture=invalid-credentials"]
        app.launch()
        app.textFields["login.email"].tap()
        app.textFields["login.email"].typeText("reader@example.test")
        app.buttons["login.submit"].tap()
        XCTAssertTrue(app.staticTexts["login.invalidCredentials"].waitForExistence(timeout: 3))
    }
}

This UI-test excerpt assumes the app explicitly implements that deterministic launch fixture and accessibility IDs. It checks the visible recovery outcome; pure credential validation and HTTP mapping should have narrower tests, and the timeout is a test bound rather than a performance claim.

How do you make time, randomness, UUIDs, and networking deterministic in tests?

Short answer: Supply controllable clocks, ID generators, random values, and network clients to the code under test. The test can then choose exactly when work completes and which values it receives. Repeating those inputs should produce the same result without live services or guessed delays.

Detailed explanation:

Answer focus: Inject controllable capabilities such as a clock, ID generator, and network client; tests advance or resolve them explicitly instead of relying on sleeps or live services. See testing boundaries.

Applied example — illustrative:

SWIFT
import Foundation
struct DraftFactory {
    let now: () -> Date
    let newID: () -> UUID
    func make() -> (id: UUID, createdAt: Date) { (newID(), now()) }
}
let fixedID = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!
let factory = DraftFactory(
    now: { Date(timeIntervalSince1970: 0) },
    newID: { fixedID }
)
assert(factory.make().id == fixedID)

The fixed literal is a known-valid fixture, and the injected clock/ID capabilities make the output repeatable without sleeping. A network fake should similarly let the test resolve a named request explicitly, not depend on a live server’s timing.

How do you test cancellation and actor-isolated state without timing sleeps?

Short answer: Bring the operation to a known waiting point using a controllable dependency, then cancel it explicitly. Wait for a defined completion or state change and read actor-owned state through its actor. Sleeping for an arbitrary interval cannot prove that cancellation or cleanup has finished.

Detailed explanation:

Answer focus: Use a controllable async dependency or test clock, trigger cancellation explicitly, and await a known state/result instead of guessing with a delay. See testing boundaries and cancellation patterns.

Applied example — illustrative:

SWIFT
import Testing
@Test func cancellationUnblocksStreamConsumption() async {
    let ready = AsyncStream<Void>.makeStream()
    let input = AsyncStream<Int>.makeStream()
    let worker = Task {
        ready.continuation.yield(())
        for await _ in input.stream { }
        try Task.checkCancellation()
    }
    var handshake = ready.stream.makeAsyncIterator()
    _ = await handshake.next()
    worker.cancel()
    do { try await worker.value; Issue.record("Expected cancellation") }
    catch { #expect(error is CancellationError) }
}

The handshake proves the task started; cancelling AsyncStream iteration unblocks it, and awaiting the result establishes completion without a timing sleep. In a model test, inspect an actor’s snapshot only after that completion boundary; use a controlled repository to hold a particular suspension when testing stale publication.

How do feature flags support rollout and rollback?

Short answer: A feature flag lets you control who sees a feature separately from shipping the app version. Use it to start with a small group, observe outcomes, and disable risky behavior when necessary. Define safe defaults and a removal owner, because disabling a flag does not undo completed transactions or incompatible data changes.

Detailed explanation:

Answer focus: They decouple release from exposure and can limit blast radius, but require default behavior, owner, expiry, both-branch tests, and a rollback plan that accounts for old clients. See CI/CD and release design.

Applied example — illustrative:

SWIFT
struct CheckoutFlags {
    var useNewSummary = false
}
enum SummaryLayout { case classic, revised }
func summaryLayout(flags: CheckoutFlags) -> SummaryLayout {
    flags.useNewSummary ? .revised : .classic
}
let disabled = summaryLayout(flags: CheckoutFlags())
let enabled = summaryLayout(flags: CheckoutFlags(useNewSummary: true))
assert(disabled == .classic && enabled == .revised)

The safe default and both paths are explicit and testable independently of a remote flag service. The rollout still needs an owner, expiry, and backward-compatible server behavior; turning the flag off cannot undo a data migration already performed.

How would you evolve a public Swift API without breaking clients?

Short answer: Prefer adding a compatible capability while keeping existing callers working. Deprecate old behavior gradually, provide migration guidance, and test both source compatibility and observable behavior. An API can still break clients even when their code continues to compile.

Detailed explanation:

Answer focus: Prefer additive changes, stage deprecation, avoid unsatisfied protocol requirements, and provide migration guidance for unavoidable breaks. See public API evolution.

Applied example — illustrative:

SWIFT
public struct SearchOptions {
    public var includeArchived: Bool
    public init(includeArchived: Bool = false) {
        self.includeArchived = includeArchived
    }
}
public func search(_ query: String, options: SearchOptions) -> [String] { [] }
@available(*, deprecated, message: "Use search(_:options:)")
public func search(_ query: String) -> [String] {
    search(query, options: SearchOptions())
}

This API-shape example forwards old callers to the new entry point while providing migration guidance; the empty result stands in for the existing implementation. Source compatibility and binary/library-evolution compatibility are separate concerns, so review deployment and distribution requirements before promising either.

How do you propagate cancellation through networking, parsing, and UI state?

Short answer: The owner of an operation should be able to cancel the work it started. Pass that cancellation through child tasks and supported APIs, and check it before expensive work or publishing a result. Cancellation is cooperative, so every layer needs a clear way to stop or ignore an obsolete result.

Detailed explanation:

Answer focus: Let the owner cancel the task, pass cancellation through child work and supported APIs, check at expensive boundaries, and avoid publishing stale state after cancellation. See cancellation patterns.

Applied example — illustrative:

SWIFT
import Foundation
func loadNames(from url: URL, session: URLSession) async throws -> [String] {
    let (data, response) = try await session.data(from: url)
    guard (response as? HTTPURLResponse)?.statusCode == 200 else {
        throw URLError(.badServerResponse)
    }
    try Task.checkCancellation()
    let names = try JSONDecoder().decode([String].self, from: data)
    try Task.checkCancellation()
    return names
}

The owning task’s cancellation reaches URLSession, and explicit checks prevent continuing at the decode/publication boundary. Synchronous JSONDecoder work is not forcibly interrupted mid-call; bound response size or change parsing strategy when cancellation latency or CPU cost matters.

How do you prevent duplicate token refresh requests?

Short answer: Use one refresh coordinator so requests that fail together wait for the same refresh operation. Publish the new credentials as one consistent update and retry only requests allowed by the authentication policy. Track the operation’s identity so an older completion cannot clear a newer refresh.

Detailed explanation:

Answer focus: Use one refresh coordinator so concurrent failures await the same in-flight operation, update credentials atomically, retry eligible calls once, and clear the session if refresh fails. See authentication and token refresh.

Applied example — illustrative:

SWIFT
actor RefreshCoordinator {
    private var running: Task<String, Error>?
    func token(using refresh: @escaping @Sendable () async throws -> String) async throws -> String {
        if let running { return try await running.value }
        let task = Task { try await refresh() }
        running = task
        defer { running = nil }
        return try await task.value
    }
}

For this coordinator’s single session with no concurrent invalidation API, overlapping callers share one refresh. A production coordinator also needs session/generation checks for logout or account switches, protected credential persistence, and an explicit shared-task cancellation policy before retrying an eligible request once.

How do you define dependency direction for UI, domain, and data?

Short answer: The UI uses application behavior, the domain expresses business rules, and data implementations handle networking or storage. Keep high-level rules independent of those technical details by defining the contracts they need. Connect the real implementations where the application is assembled.

Detailed explanation:

Answer focus: High-level policy should not import transport or persistence details; depend on consumer-facing capabilities and compose implementations at the boundary. See dependency direction and the canonical DIP answer.

Applied example — illustrative:

SWIFT
// Domain module:
protocol OrderReading { func totalCents(orderID: String) async throws -> Int }
struct TotalForReceipt {
    let orders: any OrderReading
    func callAsFunction(_ id: String) async throws -> Int {
        try await orders.totalCents(orderID: id)
    }
}
// Data module depends on Domain, not the reverse:
struct RemoteOrders: OrderReading {
    let load: (String) async throws -> Int
    func totalCents(orderID: String) async throws -> Int { try await load(orderID) }
}

The domain consumer defines its required capability without URLSession or JSON types. The outer data adapter implements that capability and is assembled by the app root, so replacing HTTP storage does not change the receipt policy.

How do DTOs, domain models, and view state differ?

Short answer: A DTO matches the shape of data exchanged with an external system. A domain model expresses the application’s business meaning, while view state describes what a screen can display. Mapping between them prevents transport details from controlling business rules or leaking directly into the interface.

Detailed explanation:

Answer focus: DTOs reflect transport shape, domain models express stable app meaning, and view state represents what a screen can render. Map at the data boundary and do not leak HTTP or JSON details into UI state. See domain model and DTO.

Applied example — illustrative:

SWIFT
struct ProductDTO: Decodable { let id: String; let price_cents: Int }
struct Product: Sendable { let id: String; let priceCents: Int }
enum ProductState { case loading, content(title: String), failed }
func map(_ dto: ProductDTO) throws -> Product {
    guard dto.price_cents >= 0 else { throw MappingError.invalidPrice }
    return Product(id: dto.id, priceCents: dto.price_cents)
}
enum MappingError: Error { case invalidPrice }
func renderState(_ product: Product) -> ProductState {
    .content(title: "\(product.priceCents) cents")
}

The transport’s snake_case stays in the DTO, validation occurs before producing the domain model, and the view state carries renderable information. Real currency formatting belongs to an injected/localized presentation capability rather than this teaching string.

Short answer: Validate an external link at the application boundary and turn it into a known destination with validated identifiers. The owning feature or navigation coordinator should then check prerequisites and construct the route. A URL supplied from outside the app must not grant access or directly dictate internal screen state.

Detailed explanation:

Answer focus: Parse and validate the external URL at the app boundary, convert it into a typed destination, then let the owning feature/coordinator construct the route and required dependencies. Keep raw URL strings out of view state; see state-driven navigation.

Applied example — illustrative:

SWIFT
import Foundation
enum Destination { case product(id: String) }
func destination(from url: URL) -> Destination? {
    guard url.scheme == "https", url.host == "shop.example.test" else { return nil }
    let parts = url.path.split(separator: "/")
    guard parts.count == 2, parts[0] == "products", !parts[1].isEmpty else { return nil }
    return .product(id: String(parts[1]))
}

This boundary parser accepts one explicit route shape and rejects other hosts/routes. The navigation owner must still resolve existence and authorization; successfully parsing an external identifier does not grant permission to open its data.

How do Auto Layout priorities decide which layout preference can yield?

Short answer: Priorities tell Auto Layout which preferences may yield when they cannot all be satisfied. Content hugging resists a view becoming larger than its natural size, while compression resistance resists it becoming smaller. Resolve the actual conflicting constraints instead of increasing every priority.

Detailed explanation:

Answer focus: Hugging resists growth and compression resistance resists shrinking; distinguish an ambiguous system from unsatisfiable required constraints, then inspect the actual constraint graph. See Auto Layout priorities.

Applied example — illustrative:

SWIFT
import UIKit
let title = UILabel()
let amount = UILabel()
title.setContentHuggingPriority(.defaultLow, for: .horizontal)
amount.setContentHuggingPriority(.defaultHigh, for: .horizontal)
amount.setContentCompressionResistancePriority(.required, for: .horizontal)
let row = UIStackView(arrangedSubviews: [title, amount])
row.axis = .horizontal
row.spacing = 8

Hugging lets the title absorb available space, while the amount strongly resists compression. This is only a policy choice inside a complete constraint system: test large text/localization and resolve contradictory required constraints rather than adjusting priorities blindly.

How do you preserve a multi-step flow across app relaunch?

Short answer: Save the small pieces of durable intent needed to rebuild the flow, such as its current step and record identifiers. On relaunch, validate that intent and reconstruct the screens through their owner. Handle expired accounts and missing records instead of trying to restore old view objects.

Detailed explanation:

Answer focus: Persist the minimal validated route state needed to restore the user's intent, not transient view objects; reconstruct the flow through its owner and handle removed or expired destinations. See state-driven navigation.

Applied example — illustrative:

SWIFT
import Foundation
struct CheckoutRestore: Codable {
    let schemaVersion: Int
    let cartID: String
    let step: Step
    enum Step: String, Codable { case address, delivery }
}
func restore(_ saved: CheckoutRestore, activeCartID: String) -> CheckoutRestore.Step? {
    guard saved.schemaVersion == 1, saved.cartID == activeCartID else { return nil }
    return saved.step
}

Persist minimal nonsensitive intent, then validate schema and current cart before reconstructing the flow. Payment confirmation, expired sessions, and missing data need explicit recovery; restoring a route must not replay a charge or claim old authorization is still valid.

How do you choose the right layer and freshness rules for a cache?

Short answer: Cache where doing so removes measured work and where temporarily stale data is acceptable. Give the cache explicit keys, size limits, freshness rules, and invalidation events. Separate account data and remember that an HTTP response cache, decoded-data cache, and image cache solve different problems.

Detailed explanation:

Answer focus: Cache at the layer that removes measured work, with explicit freshness, invalidation, memory limits, and privacy policy. Distinguish HTTP revalidation, decoded data, and rendered-image caches; see persistence choices and performance investigation.

Applied example — illustrative:

SWIFT
import Foundation
actor ProductCache {
    struct Entry { let value: String; let expiresAt: Date }
    private var entries: [String: Entry] = [:]
    func read(_ id: String, now: Date) -> String? {
        guard let entry = entries[id], entry.expiresAt > now else {
            entries[id] = nil
            return nil
        }
        return entry.value
    }
    func invalidate(_ id: String) { entries[id] = nil }
}

This excerpt isolates expiry and explicit invalidation while injecting time for deterministic boundary tests. A usable cache also needs insertion and a bounded capacity/eviction policy; TTL alone does not bound memory or invalidate account-scoped data on logout.

How can a client use caching and retries without repeating an unsafe operation?

Short answer: Use cache validators such as ETags to check whether a saved response is still current. Retry transient failures with a bounded policy, but repeat a write only when its contract makes repetition safe. An idempotency key helps only when the server uses it to recognize the same logical operation.

Detailed explanation:

Answer focus: Use validators to revalidate cached reads, retry only transient errors with bounded backoff, and retry writes only when idempotent or protected by an idempotency key. See HTTP caching and retry policy.

Applied example — illustrative:

SWIFT
import Foundation
var read = URLRequest(url: URL(string: "https://api.example.test/orders/42")!)
read.setValue("\"revision-7\"", forHTTPHeaderField: "If-None-Match")
var write = URLRequest(url: URL(string: "https://api.example.test/orders")!)
write.httpMethod = "POST"
let operationID = UUID().uuidString
write.setValue(operationID, forHTTPHeaderField: "Idempotency-Key")

A 304 response reuses the validated cached representation; the write key must stay the same for retries of this one logical operation. The server must implement the idempotency contract, and retries need bounded transient-error/backoff rules rather than treating either header as automatic reliability.

How do you choose an integration point for SwiftUI inside a UIKit app?

Short answer: Introduce SwiftUI at a bounded screen or component boundary while keeping navigation and state ownership explicit. A hosting controller can present a SwiftUI surface inside a UIKit application. Start with a small migration and verify behavior before expanding it.

Detailed explanation:

Answer focus: Keep navigation and state ownership explicit, migrate a bounded surface, and use hosting/representable interoperability only where it reduces risk. See the UIKit-to-SwiftUI migration plan.

Applied example — illustrative:

SWIFT
import UIKit
import SwiftUI
@MainActor
func mount<Content: View>(_ content: Content, in parent: UIViewController) {
    let host = UIHostingController(rootView: content)
    parent.addChild(host)
    host.view.frame = parent.view.bounds
    host.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    parent.view.addSubview(host.view)
    host.didMove(toParent: parent)
}

UIKit keeps controller/navigation ownership while one bounded surface uses SwiftUI. This full-container example uses autoresizing deliberately; a constrained subregion needs its own Auto Layout constraints and a removal/lifecycle policy. The child receives the parent's bounds because its frame belongs in that parent's local coordinates; compare the worked frame/bounds examples.

Which performance question can each Instruments tool answer?

Short answer: A memory graph shows which objects keep other objects alive. Allocations shows when objects are created and how their memory use changes, while Time Profiler samples where CPU time is spent. Choose the tool that can test your explanation for the observed symptom.

Detailed explanation:

Answer focus: Use memory graphs to inspect ownership paths, Allocations to see object creation and lifetime, and Time Profiler to find CPU hot spots; choose based on the symptom and compare to a baseline. See performance investigation.

Applied example — illustrative:

SWIFT
import Foundation
import os
let signposter = OSSignposter(subsystem: "com.example.catalog", category: "loading")
func measureDecode(_ data: Data) throws -> [String] {
    let interval = signposter.beginInterval("Decode names")
    defer { signposter.endInterval("Decode names", interval) }
    return try JSONDecoder().decode([String].self, from: data)
}

This interval correlates a specific operation with CPU/allocation traces; it does not itself explain a retained owner. Inspect Memory Graph for ownership, Allocations for lifetime/churn, and a supported CPU profiler for execution cost, using comparable device/build conditions.

How do you distinguish a stub, fake, spy, and mock?

Short answer: A stub supplies chosen responses, while a fake provides a lightweight working implementation. A spy records interactions, and a mock checks expected interactions. Prefer checking results unless the interaction itself is part of the behavior being promised.

Detailed explanation:

Answer focus: A stub returns controlled responses, a fake has a lightweight working implementation, a spy records calls, and a mock verifies expectations. Prefer result/state assertions unless interaction order is itself contractual. See testing boundaries and doubles.

Applied example — illustrative:

SWIFT
protocol GreetingReading { func greeting() -> String }
struct GreetingStub: GreetingReading {
    func greeting() -> String { "Hello" }
}
final class GreetingSpy: GreetingReading {
    private(set) var calls = 0
    func greeting() -> String { calls += 1; return "Hello" }
}
let spy = GreetingSpy()
_ = spy.greeting()
assert(spy.calls == 1)

The stub only supplies a response; the spy additionally records use. A fake would implement working lightweight behavior such as an in-memory store, while a mock encodes expected interactions; prefer asserting the displayed greeting unless call count is contractual.

What release signals prove a rollout is healthy without exposing user data?

Short answer: Measure outcomes for the affected journey and release group, including success rate, crashes, latency, and responsiveness. Compare those signals with a baseline and define when to pause expansion. Collect only the information needed for that decision, excluding credentials and sensitive payloads.

Detailed explanation:

Answer focus: Track privacy-safe, appropriately aggregated crash, latency, launch, hitch, and key-journey signals by version/cohort; minimize payloads and exclude credentials or sensitive response data. See mobile scale and observability.

Applied example — illustrative:

SWIFT
struct LaunchObservation: Encodable {
    let appVersion: String
    let osMajor: Int
    let scenario: String
    let durationBucket: String
}
let event = LaunchObservation(
    appVersion: "candidate", osMajor: 27,
    scenario: "signed_out_launch", durationBucket: "within_budget"
)

This typed event intentionally excludes tokens, raw URLs, payloads, and user IDs; it is a schema illustration, not collected telemetry or an invented measurement. Apply consent/retention/aggregation rules and compare crash, latency, and journey health across comparable release cohorts.

How do you review an architectural proposal constructively?

Short answer: Start by agreeing on the problem, constraints, and evidence that would make a design successful. Compare options on failure behavior, ownership, migration cost, and likely future changes. Record who decides and what new evidence would justify revisiting the decision.

Detailed explanation:

Answer focus: Restate the problem and constraints, test options against agreed criteria, surface failure modes and migration cost, then record a decision owner and revisit trigger. See architecture decision-making.

Applied example — illustrative:

YAML
decision: keep_checkout_navigation_in_feature_coordinator
constraints:
  - restore_deep_links_without_replaying_payment
  - test_routes_without_launching_the_app
alternatives: [view_owned_routes, feature_coordinator, global_router]
selected: feature_coordinator
owner: checkout_team
revisit_when: another_feature_requires_cross_flow_checkout_resume

This abbreviated ADR makes options, constraints, ownership, and a revisit trigger reviewable. It is a decision example rather than proof that one pattern wins everywhere; invite concrete counterexamples against the constraints instead of arguing from preferred labels.

Why should side effects not run in SwiftUI body?

Short answer: SwiftUI may evaluate a view’s body many times to describe the interface. Starting requests or changing business state there can therefore repeat work unexpectedly. Put that work in an explicit user action, a lifecycle-bound task, or an appropriately owned model.

Detailed explanation:

Answer focus: body is a repeatable description that SwiftUI may recompute; start lifecycle-bound work in .task or a model/service and make it cancellable. See lifecycle work and cancellation.

Applied example — illustrative:

SWIFT
import SwiftUI
struct InboxScreen: View {
    @State private var names: [String] = []
    let load: @Sendable () async throws -> [String]
    var body: some View {
        List(names, id: \.self) { Text($0) }
            .task {
                do {
                    let loaded = try await load()
                    try Task.checkCancellation()
                    names = loaded
                }
                catch is CancellationError { }
                catch { if !Task.isCancelled { names = [] } }
            }
    }
}

The render description stays free of a task-creation side effect; lifecycle work belongs to .task and its dependency must cooperate with cancellation. This focused sample assumes unique names and intentionally minimal error rendering; production UI should represent failures and stale-publication rules explicitly.

How do view identity and list identifiers affect SwiftUI state?

Short answer: SwiftUI connects stored view state to view identity. Stable identifiers help a row keep the state that belongs to its data, while changing identity can reset that state. Use a new identity deliberately, rather than generating a fresh identifier every time the view is evaluated.

Detailed explanation:

Answer focus: SwiftUI associates state with identity; unstable IDs can move/reset row state and break animations. Use stable domain identity and change .id only when resetting state is intended. See view identity and rendering.

Applied example — illustrative:

SWIFT
import SwiftUI
struct Note: Identifiable {
    let id: UUID
    var title: String
}
struct NotesList: View {
    let notes: [Note]
    var body: some View {
        List(notes) { note in Text(note.title) }
    }
}

The ID is stored once with the domain item and survives insertion, sorting, and title edits. A newly generated computed UUID or array index would give different identity semantics and can reset or misassociate local row state.

How do you cancel image loading when a reusable view disappears?

Short answer: Tie image-loading work to the lifetime of the view or request that needs it. Cancel work when that destination disappears or is reused, and check the request identity before applying a late result. Cancellation alone is insufficient when a loader can still complete after the view has changed.

Detailed explanation:

Answer focus: Tie the request to the view/task lifetime, propagate cancellation into the loader, and prevent late results from updating a reused destination. See SwiftUI task lifetime and cancellation patterns.

Applied example — illustrative:

SWIFT
// Inside a MainActor-owned reusable image view/model:
.task(id: imageURL) {
    let requestedURL = imageURL
    do {
        let loaded = try await imageLoader.load(requestedURL)
        try Task.checkCancellation()
        guard requestedURL == imageURL else { return }
        image = loaded
    } catch is CancellationError {
    } catch {
        if !Task.isCancelled { image = nil }
    }
}

The view-owned task is cancelled when its identity changes or disappears; the loader must propagate cancellation to its underlying work. A model shared by multiple callers should also guard a request generation, including its failure/cleanup paths, so an old completion cannot update a reused destination.

What accessibility behavior should a custom control provide?

Short answer: Expose the control’s purpose, current value, state, and available actions to accessibility services. Support readable text, usable touch targets, and cues that do not depend only on color. Verify the complete interaction with VoiceOver and other relevant accessibility settings.

Detailed explanation:

Answer focus: Expose a meaningful label, value, traits, and actions; support Dynamic Type, adequate hit targets, and non-color cues; then verify with VoiceOver and accessibility tests. See layout, accessibility, and platform fit.

Applied example — illustrative:

SWIFT
import SwiftUI
struct FavoriteButton: View {
    @Binding var isFavorite: Bool
    var body: some View {
        Button { isFavorite.toggle() } label: {
            Image(systemName: isFavorite ? "star.fill" : "star")
                .frame(minWidth: 44, minHeight: 44)
        }
        .accessibilityLabel("Favorite")
        .accessibilityValue(isFavorite ? "On" : "Off")
        .accessibilityHint("Changes whether this item is a favorite")
    }
}

A semantic Button supplies an actionable control, while label/value explain the icon and current state without color alone. Localize strings and verify VoiceOver, keyboard, hit testing, contrast, and Dynamic Type in the surrounding layout; modifiers alone do not prove accessibility.

What causes scrolling hitches, and what work should leave the main actor?

Short answer: A scrolling hitch means the app failed to prepare a frame within the available time. Measure the affected interval and look for expensive layout, image decoding, repeated computation, or blocked UI work. Move suitable expensive work away from the UI actor while keeping UI updates and shared state correctly isolated.

Detailed explanation:

Answer focus: Measure frame-time, then inspect main-thread work, layout, image decode, and repeated computation. Move safe expensive work off the UI actor without losing cancellation or synchronization; see performance investigation.

Applied example — illustrative:

SWIFT
@concurrent
func sortedNames(_ names: [String]) async throws -> [String] {
    try Task.checkCancellation()
    let sorted = names.sorted()
    try Task.checkCancellation()
    return sorted
}
@MainActor
func publishNames(_ snapshot: [String], request: Int) async throws {
    let sorted = try await sortedNames(snapshot)
    guard !Task.isCancelled, request == generation else { return }
    visibleNames = sorted
}

This Swift 6.2+ member/helper excerpt moves measured sorting work away from the calling UI actor and rejects stale results before publication. Sorting itself is synchronous and not interrupted mid-call; bound the input or redesign the algorithm if cancellation latency matters, and confirm the actual hitching stage before applying this change.

How do you migrate a local store while preserving user data?

Short answer: Define a versioned transformation from each supported old data format to the new one. Test realistic existing stores and interrupted upgrades, and keep a recovery plan that protects user data. A migration is complete only when the updated application can safely use the resulting data.

Detailed explanation:

Answer focus: Use versioned migrations, test realistic prior stores and interrupted upgrades, retain a safe recovery path, and monitor failure rates. See persistent-store migration.

Applied example — illustrative:

SQL
BEGIN IMMEDIATE;
ALTER TABLE drafts ADD COLUMN sync_state TEXT NOT NULL DEFAULT 'pending';
UPDATE drafts SET sync_state = 'synced' WHERE server_version IS NOT NULL;
PRAGMA user_version = 2;
COMMIT;

This SQLite migration artifact assumes the version-1 schema contains server_version and the migration runner executes it only for version 1. Keep the schema change and version bump transactional, test real prior-store fixtures and interruption recovery, and handle errors without replacing the user’s store with an empty one.

How do you resolve offline data conflicts?

Short answer: Compare the record’s version with the version the user edited, then apply a rule appropriate to that data. Independent changes may merge, while conflicting or safety-sensitive changes may need explicit resolution. Do not assume the latest device timestamp identifies the correct business result.

Detailed explanation:

Answer focus: Choose a domain-specific policy—merge independent fields, use version checks, or ask the user—and make retries idempotent. Do not assume last-write-wins is safe for every record. See offline-first design.

Applied example — illustrative:

SWIFT
struct DraftSnapshot {
    let text: String
    let serverVersion: Int
}
enum SaveDecision { case accept, conflict(current: DraftSnapshot) }
func decideSave(expectedVersion: Int, current: DraftSnapshot) -> SaveDecision {
    expectedVersion == current.serverVersion ? .accept : .conflict(current: current)
}

Version comparison exposes a conflict instead of silently overwriting a newer edit. The authoritative comparison and write must occur atomically on the server; this pure decision function explains the contract but cannot prevent a check-then-write race by itself.

How do you avoid excess copies when decoding a very large response?

Short answer: Measure peak memory and avoid keeping raw bytes, decoded objects, and mapped copies longer than necessary. Use pagination or streaming when the server and parser support it, and avoid decoding the same data repeatedly. Move suitable processing away from the UI actor without ignoring cancellation.

Detailed explanation:

Answer focus: Measure peak memory, paginate or stream when the API supports it, decode once, and avoid retaining raw, decoded, and mapped copies together longer than needed. See memory and performance investigation.

Applied example — illustrative:

SWIFT
struct Page<Row: Sendable>: Sendable {
    let rows: [Row]
    let nextCursor: String?
}
func importPages<Row: Sendable>(
    fetch: (String?) async throws -> Page<Row>,
    save: ([Row]) async throws -> Void
) async throws {
    var cursor: String?
    repeat {
        try Task.checkCancellation()
        let page = try await fetch(cursor)
        try await save(page.rows)
        cursor = page.nextCursor
    } while cursor != nil
}

With a bounded page contract, each iteration can release its decoded page after saving rather than retaining the whole result set plus raw copies. The service must guarantee cursor progress and limits; the importer also needs resumability/idempotency if a later page fails after earlier pages have committed.

Who should own state shared by a SwiftUI parent and its children?

Short answer: Keep one authoritative owner for each mutable value. Pass read-only values to children that only display them, and a binding to a child that edits the owner’s value. Passing the same connection through another child should not create a second independent state store.

Detailed explanation:

Answer focus: Keep one owner for mutable state, pass read-only values where enough, and pass a Binding only to the child that edits it. See SwiftUI state ownership.

Applied example — illustrative:

SWIFT
import SwiftUI
struct NamePreview: View {
    let name: String
    var body: some View { Text(name) }
}
struct NameEditor: View {
    @Binding var name: String
    var body: some View { TextField("Name", text: $name) }
}
struct NameFlow: View {
    @State private var name = ""
    var body: some View {
        VStack { NamePreview(name: name); NameEditor(name: $name) }
    }
}

NameFlow is the sole source of truth, the preview reads a value, and only the editing child receives mutation access. Both children therefore reflect one update without synchronizing duplicate local copies.

Why can creating an observed model in body lose its state?

Short answer: Recomputing a view’s body can create a new model instance and discard the state or subscriptions attached to the previous one. Give the model an owner with a stable lifetime and pass it to children. Observing a supplied object does not by itself establish that lifetime.

Detailed explanation:

Answer focus: body is recomputed; object construction there can replace the reference and reset subscriptions or state. Give the model a stable owner (@State for Observation or @StateObject for legacy ObservableObject) and inject it into children. See state ownership and legacy object ownership.

Applied example — illustrative:

SWIFT
import SwiftUI
import Observation
@Observable final class DraftModel { var name = "" }
struct StableDraftScreen: View {
    @State private var draft = DraftModel()
    var body: some View {
        @Bindable var editing = draft
        TextField("Name", text: $editing.name)
    }
}

The iOS 17+ owner stores the observable reference in State rather than constructing it inside body. Bindable exposes its editable properties; an intentional change to the owning view’s identity can still reset its state.

How do you model loading, empty, content, and failure states?

Short answer: Represent the screen’s allowed states explicitly, such as loading, empty, content, and failure. Define which transitions are allowed and whether existing content remains visible during refresh. This prevents unrelated Boolean flags from describing contradictory screens.

Detailed explanation:

Answer focus: Represent mutually exclusive states with an enum and let the view render each case; model stale content during refresh explicitly if the product needs it. See the feature blueprint.

Applied example — illustrative:

SWIFT
import SwiftUI
enum ResultsState { case loading, empty, content([String]), failed(String) }
struct ResultsBody: View {
    let state: ResultsState
    var body: some View {
        switch state {
        case .loading: ProgressView()
        case .empty: Text("No results")
        case .content(let names): Text(names.joined(separator: ", "))
        case .failed(let message): Text(message)
        }
    }
}

The enum prevents impossible combinations such as empty content being simultaneously marked loading and failed. If stale content remains visible during refresh, model that requirement explicitly rather than scattering independent booleans across the view.

How do Combine subscribe(on:) and receive(on:) differ?

Short answer: subscribe(on:) chooses the scheduler for upstream subscription, request, and cancellation operations. receive(on:) chooses where downstream values and completion are delivered. Neither operator makes arbitrary shared state thread-safe or changes the isolation rules of code that accesses it.

Detailed explanation:

Answer focus: subscribe(on:) affects upstream subscription/request work; receive(on:) schedules downstream values. Choose the UI delivery scheduler deliberately and avoid assuming either operator makes all work thread-safe. See Combine scheduling.

Applied example — illustrative:

SWIFT
import Foundation
import Combine
let decodingQueue = DispatchQueue(label: "names.decode")
let token = Just(Data("[\"Ada\"]".utf8))
    .subscribe(on: decodingQueue)
    .tryMap { try JSONDecoder().decode([String].self, from: $0) }
    .receive(on: DispatchQueue.main)
    .sink(receiveCompletion: { print($0) }, receiveValue: { print($0) })

With this synchronous Just source, subscription-side decoding runs on the selected queue and downstream delivery switches afterward. For other publishers, emission context can differ; receive(on:) is a runtime scheduler choice, not a compiler-proven MainActor annotation or general synchronization guarantee.

How do you identify and fix a Combine retain cycle?

Short answer: Look for an owner that keeps a subscription whose callback strongly captures that same owner. That ownership loop can keep both alive after they are no longer needed. Break the appropriate reference or cancel the subscription at the intended lifetime boundary.

Detailed explanation:

Answer focus: Inspect the ownership path from the owner to its cancellable and back through a stored closure; capture weakly where the callback should not extend owner lifetime, and cancel at the right lifecycle boundary. See Combine memory leaks.

Applied example — illustrative:

SWIFT
import Combine
@MainActor final class QueryObserver {
    var query = ""
    private var tokens: Set<AnyCancellable> = []
    func bind(_ values: AnyPublisher<String, Never>) {
        values.sink { @Sendable [weak self] value in
            Task { @MainActor [weak self] in self?.query = value }
        }.store(in: &tokens)
    }
    func stop() { tokens.removeAll() }
}

The owner retains subscriptions, but the sink and its short UI handoff do not strongly retain the owner. This explicitly crosses to MainActor; long-running or ordered delivery needs an owned processing task/stream rather than assuming arbitrary per-value tasks preserve the desired lifecycle or ordering.

When do you prefer async/await over Combine?

Short answer: Use async/await when the work is naturally a sequence of operations that finish with a result or error. Combine is useful when ongoing values and their transformations form the central model. Choose the abstraction whose ownership, cancellation, and error behavior are easiest to explain for that feature.

Detailed explanation:

Answer focus: Prefer async/await for one-shot request/response work; use Combine for long-lived or composed streams when its operators model the changing inputs clearly. See the Combine mental model.

Applied example — illustrative:

SWIFT
import Foundation
import Combine
func fetchNames(_ url: URL) async throws -> [String] {
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode([String].self, from: data)
}
let typedQueries = PassthroughSubject<String, Never>()
let subscription = typedQueries
    .removeDuplicates()
    .debounce(for: .milliseconds(250), scheduler: DispatchQueue.main)
    .sink { print("Latest input: \($0)") }

The one-shot request reads naturally as async control flow; changing input benefits from stream operators. The debounce interval is an illustrative product choice, not a measured optimum, and the request example still needs status validation, cancellation policy, and domain mapping before production use.

When would you protect a cache with an actor versus GCD barriers?

Short answer: An actor is a useful owner for mutable cache data accessed by asynchronous work. A custom concurrent queue with barrier writes can fit an existing synchronous design, provided every access follows the same queue contract. Choose one consistent protection mechanism and account for state changes across asynchronous waits.

Detailed explanation:

Answer focus: Prefer an actor for isolated async mutable state and clear ownership; a concurrent queue with barrier writes can fit a synchronous legacy boundary, but callers must respect its synchronization contract. See actors and barrier writes.

Applied example — illustrative:

SWIFT
actor ImageKeyCache {
    private var keys: Set<String> = []
    func insert(_ key: String) { keys.insert(key) }
    func contains(_ key: String) -> Bool { keys.contains(key) }
    func insertIfAbsent(_ key: String) -> Bool {
        keys.insert(key).inserted
    }
}

The actor owns all mutable state, and insertIfAbsent expresses one uninterrupted compound operation rather than a check and separate insert across awaits. A legacy GCD implementation requires every read/write to use the same queue, with barrier writes on its own concurrent queue; exposing the raw collection defeats either design.

What do Swift task priority and GCD quality of service actually guarantee?

Short answer: Swift task priority and GCD quality of service both help the scheduler decide which work is more urgent. Neither guarantees an execution order, a deadline, or correctness. Use the priority system appropriate to the work and fix blocking dependencies instead of relying on higher priorities to hide them.

Detailed explanation:

Answer focus: Both are scheduling hints, not correctness or real-time guarantees; use task priority with structured Swift concurrency and QoS for GCD work, and avoid priority escalation as a substitute for fixing dependency bottlenecks. See task lifetime choices.

Applied example — illustrative:

SWIFT
import Dispatch
func refreshUsingTask(
    _ refresh: @escaping @Sendable () async -> Void
) async {
    let task = Task(priority: .userInitiated) { await refresh() }
    await task.value
}
let maintenance = DispatchQueue(label: "cache.maintenance", qos: .utility)
maintenance.async { print("Rebuild a noncritical cache index") }

Priority and QoS communicate scheduling importance without guaranteeing deadlines or execution order. The Task here is still unstructured despite awaiting it, so production ownership/cancellation must be explicit; neither raising priority nor using a high-QoS queue fixes a blocked dependency.

What causes a main-thread GCD deadlock?

Short answer: The main thread deadlocks when it waits for work that needs that same blocked thread to continue. Synchronously dispatching to the main queue from the main queue is a simple example. Avoid blocking that thread and arrange for dependent work to complete asynchronously.

Detailed explanation:

Answer focus: A thread synchronously waiting for work that must execute on that same blocked queue cannot make progress. Avoid sync self-dispatch and blocking waits on the main queue; see GCD deadlocks.

🟥 Broken example — illustrative; do not call:

SWIFT
import Dispatch
​
@MainActor
func renderSynchronously() {
    DispatchQueue.main.sync { print("Render title") }
}

On Apple platforms the main actor executes on the main queue. The caller occupies that queue and waits for an inner block that needs the same queue; Dispatch may stop with a runtime trap instead of leaving a visible hang. A background worker synchronously dispatching to main while main waits for that worker forms a second, two-party cycle.

🟩 Corrected boundary — illustrative:

SWIFT
@MainActor
final class TitlePresenter {
    private(set) var title = ""
    func show(_ title: String) { self.title = title }
}
nonisolated func deliver(_ title: String, to presenter: TitlePresenter) async {
    await presenter.show(title)
}

The caller suspends across the actor boundary instead of blocking the UI thread on a semaphore or synchronously dispatching back to its own queue. Main-queue sync from the main queue cannot progress; async boundaries must be reflected in the API rather than disguised as synchronous work. Walk through the larger deadlock catalog to compare lock order, target queues, barriers, and async task-completion cycles.

Where do access and refresh tokens belong?

Short answer: Keep refresh credentials in storage protected by the platform, such as Keychain on Apple platforms. Keep access tokens in memory when their required lifetime allows it, and define secure persistence only when needed. Exclude credentials from preferences, logs, and analytics, and handle account changes and revocation explicitly.

Detailed explanation:

Answer focus: Keep credentials out of preferences and logs; protect refresh secrets using Keychain-backed storage, keep authorization server-owned, and define expiry/revocation behavior. See authentication and token refresh.

Applied example — illustrative:

SWIFT
import Foundation
import Security
func addRefreshToken(_ token: Data, account: String) throws {
    let item: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: "com.example.session.refresh",
        kSecAttrAccount as String: account,
        kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
        kSecValueData as String: token
    ]
    let status = SecItemAdd(item as CFDictionary, nil)
    guard status == errSecSuccess else {
        throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
    }
}

This add-only Keychain example reports failure, including duplicates, instead of logging the credential; a full store needs update/read/delete and logout handling. Choose accessibility from foreground/background and migration requirements, and keep blocking Keychain work off a latency-sensitive UI path. Apple accessibility policy, SecItemAdd behavior)

How do certificate pinning and public-key pinning differ?

Short answer: Certificate pinning trusts a particular certificate, while public-key pinning trusts a particular key. A key pin can survive certificate renewal when the same key is retained, but a key change still requires a rotation plan. Both add outage and recovery risks, so use them only when the threat model and update process justify them.

Detailed explanation:

Answer focus: Certificate pins bind to a certificate and rotate more often; public-key pins can survive certificate renewal when the key stays constant. Both require a tested backup and rollout plan. See pinning types.

Applied example — illustrative:

SWIFT
import Foundation
enum PinIdentity {
    case certificateDER(Data)
    case publicKeySPKIHash(Data)
}
struct HostPinPolicy {
    let exactHostname: String
    let allowedIdentities: [PinIdentity]
}

This policy model distinguishes whole-certificate bytes from a digest of the defined SPKI key representation; it is not a trust evaluator or hashing implementation. Renewing a certificate may change DER while preserving its public key, but pin rotation and valid system trust/hostname checks remain mandatory. Apple server-trust strategy

How do you rotate pins safely?

Short answer: Distribute the future and backup pins before changing the server’s key or certificate. Allow a planned overlap, monitor adoption and connection failures, and retain a tested recovery path. If old clients cannot receive a safe update, pinning may be unsuitable for that deployment.

Detailed explanation:

Answer focus: Ship future and backup pins before server rotation, wait for sufficient client adoption, monitor trust failures, and keep an emergency release path. See the safe pin rotation plan.

Applied example — illustrative:

YAML
rotation_plan:
  host: api.example.test
  client_release_first:
    accepted_key_labels: [current, next, recovery]
  rotate_server_only_after:
    - supported_clients_accept_next_key
    - staging_validates_hostname_chain_and_pin_failures
  retire_current_only_after:
    - legacy_client_support_policy_allows_removal
  incident_owner: security_and_mobile_on_call

This planning artifact uses key labels, not deployable hashes, and requires adoption evidence before rotation. Pinning tightens normal trust rather than replacing it; an emergency strategy must not simply accept every certificate when a pin fails. Apple identity-pinning guidance

How do you distinguish authentication errors from business errors?

Short answer: An authentication error concerns whether the caller has valid identity or credentials; a business error concerns whether the requested operation is allowed by the product’s rules. Preserve those meanings as distinct failures until the feature chooses an appropriate user action. Logging in again cannot fix an out-of-stock item or an invalid order.

Detailed explanation:

Answer focus: Preserve typed transport, authorization, decoding, and domain failures until the feature boundary can map them to appropriate user actions; do not turn every error into a retry or login prompt. See network error categories.

Applied example — illustrative:

SWIFT
enum APIProblem: Error { case unauthenticated, forbidden, conflict, transient, invalid }
func problem(for status: Int) -> APIProblem? {
    switch status {
    case 200..<300: return nil
    case 401: return .unauthenticated
    case 403: return .forbidden
    case 409: return .conflict
    case 500..<600: return .transient
    default: return .invalid
    }
}

This HTTP mapping is one boundary, not the complete domain error model. A 401 may trigger the session’s eligible one-time refresh policy; a 403 or a conflict should not blindly start login or retry a non-idempotent operation, and decoding/domain failures need their own representation.

Lead iOS Developer and Mobile Tech Lead

Advanced

How would you introduce dependency injection across a feature or module boundary?

Short answer: Let the consuming feature define the small behavior it needs, then supply a concrete implementation when assembling the application. Keep the implementation’s technical details outside that contract. Make ownership and lifetime explicit so tests and production use the same dependency boundary.

Detailed explanation:

Answer focus: Define the consumer-owned capability, keep implementations in the outer layer, compose dependencies once, and make lifetime and failure policy explicit. Use the shared dependency inversion concept and composition-root example.

Optional follow-up questions

What would make you keep a dependency concrete instead?

Applied example — illustrative:

SWIFT
protocol Syncing: Sendable { func sync() async throws }
actor SyncService: Syncing {
    let perform: @Sendable () async throws -> Void
    init(perform: @escaping @Sendable () async throws -> Void) { self.perform = perform }
    func sync() async throws { try await perform() }
}
struct Feature {
    let sync: any Syncing
}
struct FeatureFactory {
    let sharedSync: any Syncing
    func make() -> Feature { Feature(sync: sharedSync) }
}

The app composition root constructs one shared service and supplies the same instance through a small feature factory; features do not query a global container. Decide separately whether sync calls should coalesce, serialize, or overlap—the actor’s isolated ownership alone does not make its whole async operation atomic.

How do you decide when to modularize a mobile codebase?

Short answer: Modularize to solve a measured problem such as unclear ownership, slow builds, or changes spreading across unrelated features. Start with one boundary that has a clear responsibility and a small interface. Check whether that extraction improves delivery before dividing the rest of the application.

Detailed explanation:

Answer focus: Start from team ownership, build cost, change isolation, and dependency direction; pilot one bounded feature and measure the result. See incremental modularization and migration.

Applied example — illustrative:

SWIFT
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
    name: "CommerceFeatures",
    products: [.library(name: "Checkout", targets: ["Checkout"])],
    targets: [
        .target(name: "CheckoutDomain"),
        .target(name: "CheckoutData", dependencies: ["CheckoutDomain"]),
        .target(name: "Checkout", dependencies: ["CheckoutDomain"]),
        .testTarget(name: "CheckoutTests", dependencies: ["Checkout"])
    ]
)

This Package.swift shape pilots one bounded feature and encodes dependency direction rather than splitting files arbitrarily. A separate app composition target can import both UI and Data; evaluate build/change isolation and ownership before repeating this structure across every small type.

How do you choose between MVVM, MVVM-C, VIPER, or Clean Architecture?

Short answer: Choose a design that makes the feature’s state, navigation, dependencies, and ownership clear. Compare its testing needs, expected changes, team experience, and maintenance cost. A pattern’s name is less useful than evidence that its boundaries solve the actual problem.

Detailed explanation:

Answer focus: Compare actual complexity, navigation ownership, test seams, team familiarity, and ongoing ceremony; choose the simplest design that contains likely change. See the architecture decision framework.

Applied example — illustrative:

YAML
feature: checkout
constraints:
  - restore_multistep_navigation
  - validate_totals_without_ui_tests
  - migrate_one_screen_at_a_time
choice: mvvm_with_feature_coordinator
retain:
  - pure_pricing_policy
  - injected_order_repository
avoid_until_needed: extra_presenter_and_interactor_per_small_screen

This architecture decision sketch chooses components for the feature’s navigation and test seams, not a pattern popularity ranking. Compare additional VIPER/Clean boundaries only when their ownership benefits justify the ceremony and migration cost.

Lead-level people and delivery

How do you choose engineering standards and prioritize technical debt?

Short answer: Agree on a small set of standards that protect users and make changes easier to review. Prioritize debt by its effect on delivery, reliability, or risk, and give the chosen work an owner and time. Measure whether the improvement reduces those costs rather than counting refactored files.

Detailed explanation:

Answer focus: Tie debt to delivery or user risk, automate a small set of standards, and measure whether the work improves change cost. See technical debt and standards.

Applied example — illustrative:

YAML
standard: asynchronous_ui_work
review_checks:
  - view_work_has_explicit_owner_and_cancellation
  - expensive_work_is_measured_before_offloading
  - no_unchecked_sendable_without_sync_invariant
tracked_debt:
  item: replace_blocking_legacy_loader
  owner: catalog_team
  evidence: reproducible_main_thread_wait
  done_when: deterministic_test_and_matched_trace_verify_fix

This is an example review/debt policy, not an executed CI configuration or a claimed incident. It connects a narrow standard and debt item to reproducible risk, a responsible team, and evidence of completion rather than counting refactoring activity.

How do you handle a missed deadline or unrealistic commitment?

Short answer: Raise the risk early and explain what is known, what is uncertain, and what remains. Offer concrete choices involving scope, timing, and consequences, then agree on the smallest safe delivery plan. Keep the forecast visible as new evidence appears.

Detailed explanation:

Answer focus: Raise the risk early, show scope/date options with consequences, and agree on the smallest safe delivery plan. See deadline and scope management.

Applied example — illustrative:

YAML
delivery_options:
  safe_slice:
    include: [server_total_validation, accessible_confirmation, retry_recovery]
    defer: [loyalty_animation, optional_theme]
  unchanged_scope:
    requires: revised_forecast_after_backend_contract_is_verified
nonnegotiable: no_duplicate_charge_or_data_loss
owners:
  scope: product_and_mobile_lead
  contract: payments_backend

The artifact makes a scope/date decision reviewable without inventing an estimate or promising an unsafe shortcut. Communicate the dependency and options early, agree on the smallest demonstrable outcome, and update the forecast when the contract becomes evidence rather than an assumption.

How do you support an underperforming teammate?

Short answer: Discuss specific observations privately and first understand what is blocking the teammate. Agree on clear expectations, useful support, and a time to review progress. Involve the manager for formal performance responsibilities while keeping technical coaching respectful and concrete.

Detailed explanation:

Answer focus: Be specific and private, learn the blocker, agree on measurable support and follow-up, and coordinate with the manager on formal responsibilities. See supporting a teammate.

Applied example — illustrative:

YAML
support_agreement_example:
  observed_gap: cancellation_path_missing_from_recent_feature_tests
  first_step: privately_ask_about_requirements_and_tooling_blockers
  support: pair_on_one_controlled_async_test
  deliverable: small_pr_with_cancellation_and_failure_cases
  review: shared_rubric_and_timely_feedback
  follow_up: agree_checkpoint_with_teammate
  formal_performance_process: manager_owned

This fictional support-plan artifact turns a specific work gap into a supported deliverable; it is not a judgment or record about a real teammate. Start by learning the blocker and keep feedback private, while leaving formal staffing/performance responsibilities to the agreed manager role.

How do you plan work with uncertain mobile dependencies?

Short answer: Break the work into small outcomes that can be demonstrated independently. Name uncertain dependencies and owners, and use short investigations to resolve the highest-risk unknowns. Update the forecast as those facts change rather than presenting an uncertain estimate as a fixed promise.

Detailed explanation:

Answer focus: Slice toward demonstrable outcomes, name dependencies and owners, time-box discovery, and update the forecast as evidence changes. See agile planning under uncertainty.

Applied example — illustrative:

YAML
slice: checkout_summary_without_charge_submission
demonstration: fixture_prices_render_and_invalid_totals_block_confirmation
dependencies:
  backend:
    deliverable: versioned_total_response_and_error_examples
    owner: payments_team
  design:
    deliverable: accessible_error_recovery_states
    owner: checkout_designer
exit_from_discovery: contract_examples_pass_consumer_tests

The slice can demonstrate progress before a live charge endpoint is available, while the integration dependency remains visible. Time-box contract discovery and revise the forecast from a passing example rather than treating an unverified dependency as complete.

How can a technical lead help several developers work independently?

Short answer: Give the team shared direction and clear ownership of bounded outcomes. Make interface agreements and integration risks visible so developers can make local decisions confidently. Delegate decisions as well as tasks, with review focused on important boundaries and risks.

Detailed explanation:

Answer focus: Set shared direction and ownership, delegate bounded outcomes, and make integration risks visible while growing decision-making capacity across the team. See leading multiple mobile developers.

Applied example — illustrative:

YAML
workstreams:
  pricing:
    owner: pricing_pair
    contract: immutable_total_snapshot
  confirmation:
    owner: checkout_pair
    contract: typed_submit_intent_and_receipt_state
integration:
  shared_checkpoint: consumer_contract_tests_on_each_change
  decision_owner: feature_owner
  escalation: cross_module_contract_or_release_risk

This ownership map delegates outcomes and integration contracts instead of routing every local decision through the lead. Review cross-cutting changes at the shared boundary and let each owner make reversible implementation choices within it.

How does a Mobile Tech Lead differ from an Engineering Manager?

Short answer: A technical lead usually guides technical direction, engineering decisions, and the quality of implementation. An engineering manager usually owns people development, staffing, and formal performance responsibilities. The exact split varies, so make decision ownership explicit within the team.

Detailed explanation:

Answer focus: Explain the local split: the tech lead commonly owns technical direction and engineering tradeoffs, while people/staffing and broader execution may sit with the manager. See role responsibilities and boundaries.

Applied example — illustrative:

YAML
local_responsibility_agreement:
  technical_direction:
    accountable: tech_lead
    contributors: feature_owners
  hiring_and_performance:
    accountable: engineering_manager
    contributors: tech_lead
  delivery_forecast:
    accountable: engineering_manager
    contributors: [tech_lead, product, team]

This sample agreement makes the organization’s split explicit rather than declaring universal job definitions. The lead supplies technical evidence and mentoring, while formal people decisions follow the locally agreed manager responsibility.

How would you design a scalable authentication system?

Short answer: Keep identity and authorization decisions on the server and use established authentication protocols. On the client, protect credentials, coordinate refresh, and handle expiry, revocation, and account changes consistently. Design and test recovery paths as carefully as the successful sign-in path.

Detailed explanation:

Answer focus: Keep authorization server-owned, protect refresh credentials, coordinate refresh, define revocation and recovery, and test expiry and duplicate requests. See authentication system design.

Applied example — illustrative:

SWIFT
actor SessionEpoch {
    private var generation = 0
    private var accessToken: String?
    func refreshGeneration() -> Int { generation }
    func accept(_ token: String, ifGeneration expected: Int) -> Bool {
        guard expected == generation else { return false }
        accessToken = token
        return true
    }
    func signOut() { generation += 1; accessToken = nil }
}

A refresh started before sign-out cannot reinstall its access token afterward because the session generation changed. This is only the client freshness boundary: add single-flight refresh, protected refresh-token storage, server-side revocation/authorization, and a policy for simultaneous eligible request retries.

How do you manage multiple build environments safely?

Short answer: Treat server endpoints, application identity, entitlements, and feature defaults as one named configuration. Validate the actual signed artifact so a production build cannot silently use a test environment. Client configuration is visible to users and must not be treated as a safe place for private service secrets.

Detailed explanation:

Answer focus: Treat endpoints, bundle identity, entitlements, and feature defaults as one explicit configuration; validate the signed artifact and never embed a secret as if it were private. See environment configuration.

Applied example — illustrative:

SWIFT
import Foundation
enum AppEnvironment {
    case staging, production
    var apiHost: String {
        self == .production ? "api.example.test" : "staging-api.example.test"
    }
    var bundleID: String {
        self == .production ? "com.example.app" : "com.example.app.staging"
    }
}

The example groups endpoint and app identity so one cannot be changed silently without checking the other; these example.test hosts are documentation domains. Validate entitlements, signing, flags, and the final archived artifact as well, and inject secrets through authorized server/CI mechanisms rather than treating app-bundled values as secret.

How do you prevent performance and reliability regressions?

Short answer: Define acceptable behavior and performance for important user journeys before release. Combine reliable automated checks with staged exposure and production measurements against a baseline. Give each warning signal an owner and a clear action for limiting harm.

Detailed explanation:

Answer focus: Set user-journey budgets, combine automated checks with staged rollout, and define owners and mitigations for production signals. See regression prevention.

Applied example — illustrative:

YAML
release_policy:
  before_exposure:
    - deterministic_critical_journey_tests_pass
    - migrations_validate_previous_store_fixtures
    - compare_matched_device_performance_to_agreed_budget
  during_exposure:
    - review_version_and_device_cohort_health
    - pause_when_guardrail_or_data_integrity_signal_fails
  mitigation_owner: mobile_on_call
  rollback: disable_optional_feature_with_old_client_compatibility

These are proposed gates, not claimed test results or fabricated performance thresholds. Set actual budgets and decision rules from product requirements and reliable baselines, then rehearse mitigation instead of assuming App Store distribution can instantly roll every client back.

Staff / Principal

How would you design an offline-first mobile product?

Short answer: Let the interface read from local storage so useful work can continue without a connection. Save pending writes durably, then synchronize them with explicit retry and conflict rules when a connection is available. Show the user which work is pending, failed, or in conflict.

Detailed explanation:

Answer focus: Treat local persistence as the UI read model, make writes durable in an outbox, define conflict and retry semantics, and make sync observable. See the offline-first system design.

Applied example — illustrative:

SQL
BEGIN IMMEDIATE;
UPDATE drafts
SET title = :new_title, local_revision = local_revision + 1
WHERE id = :draft_id;
INSERT INTO outbox(operation_id, draft_id, operation_kind, payload)
VALUES (:operation_id, :draft_id, 'rename', :encoded_payload);
COMMIT;

This SQLite transaction artifact commits the local read model and durable sync intent together, with bound parameters rather than interpolated user strings. The caller must verify the draft exists, and the server must deduplicate operation_id; retries and conflicting remote revisions still need domain-specific policies.

How would you scale a mobile app to millions of users?

Short answer: First identify whether the constraint is traffic, data size, team coordination, or reliability. Measure client journeys and backend demand separately, then address the actual bottleneck. Caching, bounded requests, compatibility, and gradual releases help only when their behavior matches the product’s needs.

Detailed explanation:

Answer focus: Clarify whether scale means traffic, data, team, or reliability; address backend capacity and client behavior separately. See mobile scale and reliability.

Applied example — illustrative:

YAML
scale_review:
  traffic: bounded_requests_with_cache_validation_and_retry_backoff
  client_data: cursor_pagination_and_bounded_decoded_image_cache
  backend: authorization_rate_limits_and_idempotent_write_contracts
  reliability: staged_exposure_and_version_cohort_observability
  team: owned_feature_contracts_and_compatible_api_changes
verify:
  - representative_low_resource_device_journeys
  - server_capacity_tests_for_agreed_workload
  - reconnect_after_offline_without_retry_storm

This review artifact separates client, backend, reliability, and organizational scale. It proposes checks rather than claiming load-test results; increasing users does not justify loading more data into each phone or retrying every failure immediately.

How do you resolve a high-impact architecture disagreement?

Short answer: Agree on the problem and decision criteria before defending an implementation. Compare the options using evidence, and time-box an experiment when an important uncertainty remains. Assign the decision owner, record the tradeoff, and state what future evidence would justify revisiting it.

Detailed explanation:

Answer focus: Align on constraints, compare options against explicit criteria, time-box unknowns, record the decision, and define a revisit trigger. See architecture disagreement.

Applied example — illustrative:

YAML
adr: checkout_state_ownership
options: [feature_owned_store, application_global_store]
criteria:
  - isolated_checkout_tests
  - correct_logout_and_account_switch
  - controlled_cross_feature_resume
unknown: whether_shared_cart_requires_global_mutation
experiment: contract_test_two_features_against_one_cart_owner
decision_owner: mobile_architect
revisit_when: experiment_or_product_constraint_changes

This decision artifact turns disagreement into a falsifiable ownership question and an accountable decision. Record evidence and tradeoffs after the experiment; neither hierarchy nor an invented benchmark should substitute for resolving the actual constraint.

Mobile Software Architect

Advanced

How would you design a secure banking application?

Short answer: Begin with the sensitive assets, trust boundaries, threats, and applicable requirements. Keep authorization and financial operations authoritative on the server, protect credentials and local data, and make failures recoverable and auditable. Organize modules around clear ownership so security checks are consistent across complete user journeys.

Detailed explanation:

Answer focus: Define threat model and regulatory constraints first; minimize sensitive data, isolate authentication, use server-authoritative operations, and design recoverable flows. See the banking app design.

Applied example — illustrative:

SWIFT
import Foundation
struct TransferIntent: Encodable, Sendable {
    let operationID: UUID
    let destinationID: String
    let amountCents: Int
    init(destinationID: String, amountCents: Int) throws {
        guard !destinationID.isEmpty, amountCents > 0 else { throw InvalidTransfer() }
        self.operationID = UUID()
        self.destinationID = destinationID
        self.amountCents = amountCents
    }
}
struct InvalidTransfer: Error { }

The typed client intent rejects obviously invalid input and preserves one operation ID across retries; it never authorizes a transfer by changing a local balance. The server must validate account access, limits, currency/business rules, idempotency, and transaction results, while the client protects credentials and shows recoverable pending/confirmed states.

How would you design a modular super app with multiple teams?

Short answer: Separate product capabilities into modules with clear owners and stable contracts. Share only the platform capabilities that benefit multiple teams, with explicit rules for identity, navigation, and dependencies. Avoid turning a shared core into a place that every feature must modify.

Detailed explanation:

Answer focus: Separate product capabilities behind stable contracts, assign ownership, constrain dependency direction, and avoid a central shared module that becomes a dumping ground. See modularization.

Applied example — illustrative:

YAML
module_policy:
  wallet_feature:
    owner: wallet_team
    imports: [wallet_domain, design_system, feature_contracts]
  orders_feature:
    owner: orders_team
    imports: [orders_domain, design_system, feature_contracts]
  app_composition:
    imports: [wallet_feature, orders_feature, data_adapters]
forbidden: direct_feature_to_feature_internal_imports
cross_feature_navigation: typed_routes_through_app_owner

This proposed module policy makes ownership and allowed dependencies concrete enough for automated graph checks. Keep shared contracts small and deliberate; a global shared module containing business internals would recreate the coupling that module boundaries were intended to remove.

How do you plan a gradual UIKit-to-SwiftUI migration?

Short answer: Migrate one bounded screen or flow while keeping navigation and state ownership clear across the framework boundary. Preserve behavior, accessibility, and test coverage, then compare the result with the existing implementation. Expand the migration when that evidence shows a benefit.

Detailed explanation:

Answer focus: Migrate bounded screens or flows, retain clear navigation and state ownership, use interoperability where it lowers risk, and compare quality and delivery metrics before expanding. See incremental UI framework migration.

Applied example — illustrative:

SWIFT
import UIKit
import SwiftUI
@MainActor
func detailController(id: String, useSwiftUI: Bool) -> UIViewController {
    if useSwiftUI {
        return UIHostingController(rootView: DetailScreen(productID: id))
    }
    return LegacyDetailController(productID: id)
}

This factory excerpt assumes the feature’s existing DetailScreen/LegacyDetailController and retains one UIKit navigation owner. Roll out that bounded entry point behind a tested choice, compare both paths for accessibility/restoration/cancellation, and expand only after evidence supports the migration.

How do you choose native, shared, or cross-platform implementation?

Short answer: Compare the required user experience, platform integrations, performance, team skills, and release ownership. Test the hardest requirement with a small prototype and consider sharing business logic separately from the interface. Choose the approach that lowers long-term delivery risk for this product.

Detailed explanation:

Answer focus: Compare user experience, platform integration, team skills, release coupling, shared logic, and long-term ownership; avoid treating code sharing as the goal by itself. See cross-platform tradeoffs.

Applied example — illustrative:

SWIFT
protocol FeeEstimating: Sendable {
    func estimateCents(amountCents: Int) throws -> Int
}
struct SharedFeeAdapter: FeeEstimating {
    let callSharedCore: @Sendable (Int) throws -> Int
    func estimateCents(amountCents: Int) throws -> Int {
        try callSharedCore(amountCents)
    }
}

The consumer contract makes a candidate shared pure-business capability replaceable without requiring the whole UI or platform integration to migrate. Evaluate the actual shared-runtime bridge, errors, cancellation where relevant, release coupling, accessibility, and ownership; code reuse alone does not establish a better product or cheaper system.

Interview difficulty guide

LevelWhat a strong answer demonstrates
FoundationalCorrect definitions, syntax, ownership, and common failure modes.
IntermediateApplies the concept to an iOS feature and compares a reasonable alternative.
AdvancedMakes constraints, failure behavior, testing, performance, and tradeoffs explicit.
Lead / ArchitectAdds team ownership, migration strategy, risk, observability, delivery, and decision communication.

This is an interview route, not a second copy of the technical reference. Follow each linked answer for the full explanation, code, and related concepts.