Interview Preparation

Fast senior iOS interview hit points, protocol questions, code-review exercises, concise answers, and implementation challenges.

~4 hr 25 min reading~9 min practice estimate
Suggest content

Senior iOS Interview Knowledge Recap

This page is for fast review, not a second answer library. Use Interview Paths to practice questions by role and difficulty; those questions link to the canonical technical and system-design answers.

🟪 Syntax · 🟦 Types/APIs · 🟩 Correct pattern · 🟥 Bug · 🟨 Gotcha · 🧠 Explanation

Quick Recap — Interview hit points

🧠 Use this answer order: definition → owner → iOS example → failure mode → tradeoff. Start with one or two sentences; expand only when asked.

Protocols in 30 seconds

PromptHit point
What is a protocol?A contract for capabilities; a concrete type adopts and implements it.
Can you instantiate one?No. Instantiate a conformer; store it as any P only when type erasure is useful.
Can let or var hold a protocol?Yes: let screen: any P = HomeScreen(); use var to replace it with another conformer.
Generic or any P?Generic preserves type relationships; any P enables runtime substitution and storage.
some P or any P?some hides one fixed type; any can hold different conformers at runtime.
Associated type?A related type chosen by each conformance.
Primary associated type?Lets callers constrain an important associated type, such as any Cache<Data>.
Self requirement?Refers to the exact conforming type and can limit existential operations.
Extension dispatch?Through a protocol-typed value, requirements use the conformer's witness; extension-only members resolve statically.
Class-bound protocol?Add AnyObject when reference identity or a weak delegate is required.
Protocol composition?P & Q requires both capabilities without creating a new hierarchy.
Type erasure?Wraps different generic implementations behind one stable type; use deliberately.
Protocol plus Sendable?Use when conformers must safely cross isolation domains.
Protocol for every type?No. Add one at a real substitution, I/O, ownership, or testing boundary.

Senior iOS in 60 seconds

  • Architecture: dependencies point toward stable business rules; create them in a composition root.
  • Ownership: state, tasks, subscriptions, navigation, and caches each need one clear owner.
  • Models: DTOs mirror transport, domain models express meaning, and view state drives rendering.
  • Concurrency: isolate mutable state, revalidate after await, propagate cancellation, and prevent stale results.
  • SwiftUI: keep body declarative; state lifetime follows ownership and view identity.
  • UIKit: understand lifecycle, reuse, Auto Layout priorities, containment, and main-thread UI work.
  • Networking: model errors, validate responses, retry only when safe, and support cancellation.
  • Security: keep secrets out of logs, store tokens appropriately, and plan pin rotation before pinning.
  • Performance: measure first; investigate launch, hangs, hitches, allocations, and unnecessary main-actor work.
  • Persistence: plan migrations, offline behavior, conflict resolution, and recovery from partial failure.
  • Testing: inject nondeterminism; test behavior, boundaries, cancellation, and failure paths without sleeps.
  • Delivery: use observability, feature flags, staged rollout, and a tested rollback path.
  • Leadership: state tradeoffs, make risks visible, document the decision, and help the team execute it.

Code-review checklist

  • Who owns this state or task?
  • What happens on cancellation, retry, timeout, or partial failure?
  • Can an older async result overwrite newer state?
  • Is mutable shared state isolated correctly?
  • Is the abstraction useful, or is it protocol ceremony?
  • Are UI updates, accessibility, and lifecycle behavior correct?
  • Can the behavior be tested deterministically?

Avoid these interview traps

  • Do not say one architecture is always best; tie the choice to requirements and change axes.
  • Do not describe an actor as a background thread; it is an isolation mechanism.
  • Do not claim async automatically runs work off the main actor.
  • Do not use [weak self] automatically; explain the ownership and closure lifetime.
  • Do not add @unchecked Sendable without proving synchronization.
  • Do not create a protocol only to say the code is testable.

Rapid answers

Can you create an instance of a protocol?

Short answer: No. A protocol describes requirements rather than providing a concrete instance to create. Create a type that conforms to the protocol, then use that instance through the protocol interface when you want to hide or replace its implementation.

Detailed explanation:

No. A protocol defines requirements; instantiate a conforming concrete type, then store it through an existential if needed: let loader: any UserLoading = LiveUserLoader(). See 08-Swift-Types-Protocols-and-Generics.md and 13-Swift-Code-Quizzes.md for examples.

🟦 Illustrative example:

SWIFT
protocol UserLoading {
    func username() -> String
}
struct PreviewUserLoader: UserLoading {
    func username() -> String { "Preview user" }
}
let loader: any UserLoading = PreviewUserLoader()
print(loader.username())

🧠 Construct the conformer on the right; the existential on the left exposes the protocol requirements. Runtime replacement is useful for injected dependencies, while a concrete value can be simpler when substitution is unnecessary.

What is the difference between let and var?

Short answer: Let prevents reassignment of a binding, while var allows it. For a struct, a let binding also prevents changing its stored properties. For a class, let fixes which object is referenced, but the object can still change its own mutable properties.

Detailed explanation:

let makes the binding immutable; var allows reassignment. For structs, a let instance cannot have its stored var properties changed. For a class, let fixes the reference, but the referenced object can still mutate its own var properties.

🟦 Illustrative example:

SWIFT
struct Draft { var title: String }
var draft = Draft(title: "First")
draft.title = "Updated"
​
final class Session { var isActive = true }
let session = Session()
session.isActive = false

🧠 var permits changing the struct value. The let class binding cannot be replaced, but the referenced object remains mutable; this does not make it safe to share concurrently.

Who owns the object with StateObject and ObservedObject?

Short answer: StateObject establishes an ObservableObject instance as state owned by a particular SwiftUI view identity. ObservedObject observes an instance that is supplied and owned elsewhere. The distinction matters because recreating a borrowed model as though it were the owner can reset its state.

Detailed explanation:

@StateObject creates and owns the observable object for the view's lifetime. @ObservedObject observes an object owned and injected by somebody else.

🟦 Illustrative example:

SWIFT
import SwiftUI
​
@MainActor
final class CounterModel: ObservableObject {
    @Published var count = 0
}
struct CounterOwner: View {
    @StateObject private var model = CounterModel()
    var body: some View { CounterChild(model: model) }
}
struct CounterChild: View {
    @ObservedObject var model: CounterModel
    var body: some View {
        Button("Count: \(model.count)") { model.count += 1 }
    }
}

🧠 The parent establishes the object lifetime for its view identity; the child observes that same object. Recreating an owner identity can recreate its state. For Observation-based models, use the corresponding @State/@Bindable approach instead of mechanically combining wrapper families.

What does Binding let a child view do?

Short answer: Binding lets a child read and edit a value whose storage belongs elsewhere, usually in its parent. Both views use the same source of truth rather than independent copies. A binding supplies editable access; it does not own the stored value or publish a Combine stream.

Detailed explanation:

A binding is two-way access to value state owned elsewhere. It does not own the value and is not a Combine publisher.

🟦 Illustrative example:

SWIFT
import SwiftUI
​
struct ConsentRow: View {
    @Binding var accepted: Bool
    var body: some View {
        Toggle("Accept terms", isOn: $accepted)
    }
}
struct ConsentForm: View {
    @State private var accepted = false
    var body: some View { ConsentRow(accepted: $accepted) }
}

🧠 The form owns the Boolean; the row writes through a binding to that storage. A read-only child should receive a plain value rather than a mutable connection.

How is Published different from the Publisher protocol?

Short answer: Published is a property wrapper that provides a stream of changes for one property. Publisher is the general Combine protocol describing a source of values and completion. The projected Published property is one publisher implementation that callers can subscribe to.

Detailed explanation:

@Published is a property wrapper that emits changes for one property. Publisher is the general Combine stream protocol. $property exposes the publisher created by @Published.

🟦 Illustrative example:

SWIFT
import Combine
​
final class DownloadProgress: ObservableObject {
    @Published var fraction = 0.0
}
let progress = DownloadProgress()
let token = progress.$fraction.sink { fraction in
    print(fraction)
}
progress.fraction = 0.5
token.cancel()

🧠 @Published supplies a publisher for one property, while sink consumes that publisher through Combine APIs. Retain the subscription for its intended lifetime; this example prints the emitted value instead of assuming the stored property has already changed during a will-change publication.

Why do Combine subscriptions use AnyCancellable?

Short answer: AnyCancellable is a handle that can cancel a Combine subscription. Retaining it keeps that observation alive, while cancelling or releasing the handle ends its subscription. Store it with the component that owns the observation, and avoid a callback that strongly retains that same owner.

Detailed explanation:

It is a type-erased cancellation token that keeps a Combine subscription alive while retained and cancels it when explicitly cancelled or released.

🟦 Illustrative example:

SWIFT
import Combine
​
final class SearchObserver {
    private var subscription: AnyCancellable?
    func observe(_ values: AnyPublisher<String, Never>) {
        subscription = values.sink { print($0) }
    }
    func stop() {
        subscription?.cancel()
        subscription = nil
    }
}

🧠 The stored token keeps this observation alive and provides an explicit stop point. Replacing it releases the previous token; capturing the owner strongly from a token it stores would need an ownership review.

What problem does a Swift actor solve?

Short answer: An actor coordinates access to its isolated state so tasks do not access that state unsafely at the same time. A call across its isolation boundary may need to wait. However, while an actor operation is suspended, another task can change the state, so assumptions spanning a wait still need checking.

Detailed explanation:

An actor is a reference type that serializes access to its isolated mutable state. External access across the isolation boundary normally requires await.

🟦 Illustrative example:

SWIFT
actor VisitCounter {
    private var count = 0
    func increment() -> Int {
        count += 1
        return count
    }
}
func recordVisit(_ counter: VisitCounter) async -> Int {
    await counter.increment()
}

🧠 The increment is one actor-isolated synchronous operation. Actor isolation protects the counter; operations split by await still need to revalidate business assumptions after suspension.

What does Sendable mean in Swift concurrency?

Short answer: Sendable expresses that a type has a safe way for its values to cross concurrency boundaries. That safety comes from the type design, such as immutable values or protected shared state. It does not encode JSON, enforce request order, or make arbitrary mutable objects thread-safe.

Detailed explanation:

It is a concurrency contract stating that a value can safely cross isolation boundaries. It is unrelated to JSON serialization despite often appearing on Codable value models.

🟦 Illustrative example:

SWIFT
struct SearchInput: Sendable {
    let query: String
    let page: Int
}
actor SearchInbox {
    private var latest: SearchInput?
    func accept(_ input: SearchInput) { latest = input }
}

🧠 The immutable value contains sendable fields and can cross into the actor. This conformance neither encodes JSON nor synchronizes arbitrary mutable class references placed inside a model.

How does a serial queue differ from a concurrent queue?

Short answer: A serial queue executes one submitted block at a time, preserving their submission order. A concurrent queue can allow several blocks to make progress at once. Choosing a concurrent queue does not protect shared mutable data; that data still needs an ownership or synchronization rule.

Detailed explanation:

A serial queue runs one submitted block at a time. A concurrent queue may run multiple blocks simultaneously. The main queue is serial; global queues are concurrent.

🟦 Illustrative example:

SWIFT
import Dispatch
​
let databaseQueue = DispatchQueue(label: "app.database")
databaseQueue.async { print("first write") }
databaseQueue.async { print("second write") }
​
DispatchQueue.global(qos: .utility).async {
    print("independent maintenance")
}

🧠 The two blocks submitted to the same serial queue execute one at a time in submission order. The independent global-queue block may overlap; using a concurrent queue does not make captured mutable data safe.

What causes a GCD deadlock?

Short answer: A deadlock occurs when work waits for something that cannot progress until that waiting work finishes. A common example is synchronously submitting work to the same serial queue that is already executing the caller. Remove the circular dependency rather than assuming that a different thread or queue name will fix it.

Detailed explanation:

The classic case is synchronously dispatching to the same serial queue that is already executing the caller. Circular waits between queues or locks also deadlock.

🟦 Illustrative example:

SWIFT
import Dispatch
​
let work = DispatchQueue(label: "app.work")
work.async {
    // Already executing on work: call synchronous local logic directly.
    print("update protected state")
    DispatchQueue.main.async { print("render completion") }
}

🧠 Calling work.sync from inside this same serial queue would wait for work that cannot start until the caller returns. Direct local work and an asynchronous UI handoff avoid that self-wait; changing every sync to async still requires reasoning about ordering and completion.

Deep-dive assumptions: The following is a catalog of 12 major wait-cycle patterns, not an exhaustive list of every possible application dependency. Examples use illustrative Swift 6+ syntax in an iOS/macOS app with the normal main run loop; they are not one combined runnable file. Each snippet has its own setup unless noted. Do not execute the intentionally broken examples: a runtime may trap, diagnose misuse, hang, or expose the failure only under a particular schedule. Swift 6 checking can also reject unsafe isolation/captures before execution. Do not remove checks or add unchecked conformances just to run a demonstration. Corrected examples illustrate the ownership repair, not a complete production feature.

Deadlock taxonomy and the wait-for model

A wait-for chain records who cannot finish until whom. Include occupied execution capacity as a resource: a serial queue has one active slot, a configured worker pool has finite slots, and a task handle represents a completion that might never become available. A cycle is a deadlock when every participant's only progress path depends on another participant that cannot progress. Merely drawing A → B is not enough; identify the held resource and the unavailable producer.

SymptomDistinctionUseful next evidence
DeadlockA circular dependency or exhausted capacity prevents the required progress.Owners, waiters, producer locations, queue targets, and task dependencies.
ContentionA resource is busy but its holder can still finish and release it.Holder's work and actual wait duration; reduce the critical section if needed.
StarvationSome work repeatedly loses access or scheduling opportunities.Fairness, queue growth, priorities, and progress of competing work.
LivelockParticipants keep reacting/retrying but accomplish no useful work.Repeated state transitions and retry/backoff policy.
Missing completionA callback/continuation never resolves on some path.All terminal paths and exactly-once completion; there need not be a resource cycle.

The categories can overlap: blocked consumers can exhaust a pool, while contention elsewhere delays the producer. A timeout can bound a wait but must define cancellation and late-result handling; it does not make the dependency graph correct. Raising QoS, using recursive locks, or changing a call to async is not a universal repair. Apple synchronization guidance

Catalog index — open a wait-cycle pattern in the canonical lesson:

PatternHeld capacity or completion dependency
01 · Main/same-serial syncCurrent serial slot waits for itself.
02 · Cross-queue syncA waits for B, which needs A.
03 · Main ↔ workerUI waits for delivery requiring UI.
04 · Serial target hierarchySibling labels share one serial ancestor.
05 · Nested barrierBarrier waits for its own blocked predecessor.
06 · Nonrecursive self-lockCurrent thread reacquires its held lock.
07 · ABBA lock orderOpposing acquisitions hold one resource each.
08 · Group/semaphore capacityProducer is queued behind its waiter.
09 · Operation dependenciesCyclic readiness or a worker waiting for its child.
10 · MainActor bridgeBlocking UI executor must run the signal task.
11 · Cooperative-pool exhaustionBlocked consumers occupy producer execution capacity.
12 · Task self-dependencyA task awaits its own completion, directly or transitively.

Pattern 01: main-queue and same-serial-queue self-dispatch

🟥 Broken — two independent self-wait examples; do not execute:

SWIFT
import Dispatch
​
DispatchQueue.main.async {
    DispatchQueue.main.sync { print("render") }
}
​
let serial = DispatchQueue(label: "catalog.serial")
serial.async {
    serial.sync { print("read protected state") }
}

Trigger and chain: the outer block already occupies the only execution slot. It waits for the inner block; the inner block needs the outer to finish first: outer → inner → serial slot → outer. The main queue is a serial instance of this problem. Queue identity matters; a serial queue is not a promise of one dedicated thread.

🟩 Corrected — execute already-isolated local work directly:

SWIFT
import Dispatch
​
let serial = DispatchQueue(label: "catalog.serial")
serial.async {
    print("read protected state directly")
    DispatchQueue.main.async {
        print("render after the read")
    }
}

Why and verification: no second synchronous acquisition of the same queue is required. Keep public scheduling methods distinct from private, already-isolated operations; verify the corrected read-to-render order with an observable completion in the app/test harness. An async handoff changes completion semantics, so callers must not immediately assume rendering has finished. Apple DispatchQueue.sync contract-3segw)

Pattern 02: a synchronous cycle between independent queues

🟥 Broken — A synchronously enters B, then B asks A:

SWIFT
import Dispatch
​
let a = DispatchQueue(label: "orders.state")
let b = DispatchQueue(label: "orders.audit")
a.async {
    b.sync {
        a.sync { print("read orders again") }
    }
}

Trigger and chain: A's active block cannot leave B until B's inner work finishes, while that work requests A's occupied slot: A block → B block → A block. Different queue labels do not remove the cycle; synchronous dispatch may also reuse the caller's thread, so counting threads is not the proof.

🟩 Corrected — coordinate sequential snapshots without holding A while entering B:

SWIFT
import Dispatch
​
let a = DispatchQueue(label: "orders.state")
let b = DispatchQueue(label: "orders.audit")
let coordinator = DispatchQueue(label: "orders.coordinator")
coordinator.async {
    let snapshot = a.sync { 21 }
    b.sync { print("audit snapshot: \(snapshot)") }
}

Why and verification: A's work completes before B is entered, and neither subsystem calls back synchronously into the other. The sample queues have independent targets. Verify the subsystem dependency graph and completion order; if both states must change atomically, a snapshot handoff is insufficient—use one transaction/state owner rather than inventing a nested cross-queue protocol. Apple dispatch execution model

Pattern 03: main thread waits for a worker that needs main

🟥 Broken — blocking the UI while the worker synchronously returns to it:

SWIFT
import Dispatch
​
let worker = DispatchQueue(label: "preview.worker")
DispatchQueue.main.async {
    let finished = DispatchGroup()
    finished.enter()
    worker.async {
        DispatchQueue.main.sync { print("install preview") }
        finished.leave()
    }
    finished.wait()
}

Trigger and chain: main → group completion → worker → main. The worker cannot reach leave until its main-queue work runs; main is blocked waiting for leave. Even if the worker did not need main, blocking it would still freeze interaction until completion.

🟩 Corrected — make result delivery asynchronous and return to the run loop:

SWIFT
import Dispatch
​
let worker = DispatchQueue(label: "preview.worker")
func requestPreview() {
    worker.async {
        let previewTitle = "Prepared preview"
        DispatchQueue.main.async {
            print("install \(previewTitle)")
        }
    }
}

Why and verification: main does not hold a completion wait while delivery needs it. This callback-shaped contract requires the caller to observe completion instead of reading a synchronous return value. Verify that the corrected screen remains interactive and receives one completion/error path; inspect both main and worker stacks when diagnosing an existing freeze. Apple group wait semantics)

Pattern 04: sibling queues share a serial target

🟥 Broken — apparently different queues have the same constrained ancestor:

SWIFT
import Dispatch
​
let owner = DispatchQueue(label: "database.owner")
let reads = DispatchQueue(label: "database.reads", target: owner)
let writes = DispatchQueue(label: "database.writes", target: owner)
reads.async {
    writes.sync { print("save derived value") }
}

Trigger and capacity: reads occupies the serial target's one slot and waits for writes. Writes needs that same target slot: reads → writes → owner capacity → reads. Checking that reads and writes are different objects misses the shared ancestor.

🟩 Corrected — perform the combined state transition under its actual owner:

SWIFT
import Dispatch
​
let owner = DispatchQueue(label: "database.owner")
func rebuildDerivedValue() {
    owner.async {
        dispatchPrecondition(condition: .onQueue(owner))
        let snapshot = 21
        print("save derived value \(snapshot * 2)")
    }
}

Why and verification: one scheduled block performs both synchronous local phases; it does not re-enter a sibling through the target hierarchy. Verify queue targets as well as labels and inspect every synchronous callback leaving the owner. Choosing a concurrent target is only appropriate if the state contract allows that concurrency; it is not a substitute for protecting shared state. Apple target-queue initializer)

Pattern 05: a concurrent queue waits on its own barrier

🟥 Broken — the barrier must wait for the outer work that is waiting for it:

SWIFT
import Dispatch
​
let store = DispatchQueue(label: "cache.concurrent", attributes: .concurrent)
store.async {
    store.sync(flags: .barrier) {
        print("replace cache")
    }
}

Trigger and chain: the barrier cannot begin until earlier work on this private concurrent queue finishes. The outer block is earlier work, but cannot finish until the barrier does: outer → barrier → earlier work → outer. A concurrent queue does not make this nested synchronous barrier safe.

🟩 Corrected — submit the mutation without blocking an earlier queue item:

SWIFT
import Dispatch
​
let store = DispatchQueue(label: "cache.concurrent", attributes: .concurrent)
func enqueueReplacement() {
    store.async(flags: .barrier) {
        print("replace protected cache")
        DispatchQueue.main.async { print("replacement completed") }
    }
}

Why and verification: the scheduling caller can leave; the barrier runs when its earlier items complete and delivers completion without waiting for main. Barriers require the appropriate custom concurrent queue and a consistent access contract; do not assume a global queue becomes a private reader/writer lock. Verify every cache access uses its owner, and test the corrected write/read ordering without introducing another blocking wait inside a queued item. Apple barrier semantics

Pattern 06: a nonrecursive NSLock is acquired twice

🟥 Broken — a locked entry point calls another locking entry point:

SWIFT
import Foundation
​
final class BrokenCounter {
    private let lock = NSLock()
    private var count = 0
    func snapshot() -> Int {
        lock.lock(); defer { lock.unlock() }
        return readCount()
    }
    private func readCount() -> Int {
        lock.lock(); defer { lock.unlock() }
        return count
    }
}

Trigger and chain: snapshot owns the lock and calls readCount, which waits for that same nonrecursive lock. The current thread cannot reach snapshot's unlock while it is waiting: thread → lock → same thread.

🟩 Corrected — separate acquisition from already-locked logic:

SWIFT
import Foundation
​
final class Counter {
    private let lock = NSLock()
    private var count = 0
    func snapshot() -> Int {
        lock.lock(); defer { lock.unlock() }
        return countAssumingLocked()
    }
    private func countAssumingLocked() -> Int { count }
}

Why and verification: one synchronous acquisition protects the read, and the private helper does not acquire again. Audit all helpers/accessors, then verify normal and early-return paths release the lock. Here defer schedules synchronous cleanup on scope exit, in last-in-first-out order; it cannot run while the method is stuck at another lock acquisition. Never hold this thread-owned lock across await. NSRecursiveLock solves intentional same-thread recursion only, not ABBA cycles or invalid reentrant state. Apple NSLock requirements

Pattern 07: ABBA locking and a stable global acquisition order

Shared teaching setup — immutable, unique ranks assigned by the resource owner:

SWIFT
import Foundation
​
final class RankedLock: Sendable {
    let rank: Int
    let lock = NSLock()
    init(rank: Int) { self.rank = rank }
}

🟥 Broken — callers can request opposite orders:

SWIFT
func withUnorderedLocks(_ a: RankedLock, _ b: RankedLock, body: () -> Void) {
    a.lock.lock(); defer { a.lock.unlock() }
    b.lock.lock(); defer { b.lock.unlock() }
    body()
}
// If two threads call (a, b) and (b, a), each can hold one lock
// while waiting for the other. Do not execute this arrangement.

Trigger and chain: T1 holds A and requests B while T2 holds B and requests A: T1 → B → T2 → A → T1. It depends on an interleaving; it need not hang in every run. Supplying the same lock twice also recreates self-acquisition.

🟩 Corrected — all participants obey one immutable, unique rank order:

SWIFT
func withOrderedLocks(_ a: RankedLock, _ b: RankedLock, body: () -> Void) {
    if a === b {
        a.lock.lock(); defer { a.lock.unlock() }
        body()
        return
    }
    precondition(a.rank != b.rank)
    let (first, second) = a.rank < b.rank ? (a, b) : (b, a)
    first.lock.lock(); defer { first.lock.unlock() }
    second.lock.lock(); defer { second.lock.unlock() }
    body()
}

Why and verification: two distinct callers cannot acquire these locks in opposite order, and identical resources acquire once. Every path must share the ordering rule; hash values are not a unique stable resource rank. The synchronous body must be bounded and must not re-enter these locks, await, or call unknown blocking callbacks. Verify acquisition events are ascending for the corrected paths, same-resource handling works, and error/early exits release both locks in reverse order. A single state owner can be simpler than a public multi-lock API. Apple multi-lock deadlock discussion

Pattern 08: group or semaphore wait occupies the producer's capacity

🟥 Broken — group completion is queued behind its waiter:

SWIFT
import Dispatch
​
let serial = DispatchQueue(label: "import.serial")
let group = DispatchGroup()
serial.async {
    group.enter()
    serial.async { group.leave() }
    group.wait()
}

🟩 Corrected — register work before notification and do not block the owner:

SWIFT
import Dispatch
​
let serial = DispatchQueue(label: "import.serial")
let group = DispatchGroup()
group.enter()
serial.async {
    defer { group.leave() }
    print("import chunk")
}
group.notify(queue: .main) { print("import completed") }

🟥 Broken — the same one-slot dependency expressed with a semaphore:

SWIFT
import Dispatch
​
let serial = DispatchQueue(label: "index.serial")
serial.async {
    let ready = DispatchSemaphore(value: 0)
    serial.async { ready.signal() }
    ready.wait()
}

🟩 Corrected — put the continuation of the workflow after the producer:

SWIFT
import Dispatch
​
func rebuildIndex(on serial: DispatchQueue, completion: @escaping @Sendable () -> Void) {
    serial.async {
        print("rebuild index")
        DispatchQueue.main.async(execute: completion)
    }
}

Trigger and capacity: waiter → leave/signal → serial execution slot → waiter. The same pattern occurs when all N workers of a bounded executor wait for producers needing one of those N slots. Notification or a callback releases capacity instead of waiting for future work while holding it. Verify enter/leave balance on every terminal path and arrange enter before observing completion; an empty group can notify immediately. A timeout requires a failure/late-completion policy, and adding a stray signal merely to unblock the wait breaks correctness. Apple group notification), semaphore wait)

Pattern 09: Operation dependency cycles and worker-side waits

🟥 Broken — no operation in this dependency cycle becomes ready:

SWIFT
import Foundation
​
let queue = OperationQueue()
let a = BlockOperation { print("A") }
let b = BlockOperation { print("B") }
a.addDependency(b)
b.addDependency(a)
queue.addOperations([a, b], waitUntilFinished: false)

🟥 Broken — one running operation consumes the only slot its child needs:

SWIFT
import Foundation
​
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
let child = BlockOperation { print("child") }
let parent = BlockOperation {
    queue.addOperation(child)
    child.waitUntilFinished()
}
queue.addOperation(parent)

🟩 Corrected — declare an acyclic graph before enqueueing, without blocking a worker:

SWIFT
import Foundation
​
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
let produce = BlockOperation { print("produce") }
let consume = BlockOperation { print("consume completed producer output") }
consume.addDependency(produce)
queue.addOperations([produce, consume], waitUntilFinished: false)

Trigger and chain: the first graph is A completion → B completion → A completion. The second is parent → child completion → queue's only active slot → parent. A dependency keeps an operation unready without spending a worker on a blocking wait. Configure the graph before submission, verify it is acyclic, and test corrected completion order. Dependencies alone do not pass result values or imply success: propagate failure/cancellation explicitly, including for custom asynchronous operations whose isFinished must eventually become true. Apple operation dependencies, waitUntilFinished warning)

Pattern 10: a MainActor semaphore bridge blocks its own task

🟥 Broken — synchronous MainActor code blocks the executor needed to signal:

SWIFT
import Dispatch
​
@MainActor
func blockedRefresh() {
    let finished = DispatchSemaphore(value: 0)
    Task { @MainActor in
        print("refresh UI state")
        finished.signal()
    }
    finished.wait()
}

Trigger and chain: MainActor call → semaphore → newly scheduled MainActor task → occupied main executor → MainActor call. Task creation does not run that task to completion before the synchronous caller blocks. Raising its priority cannot create another main executor.

🟩 Corrected — expose an async API and suspend rather than blocking the UI thread:

SWIFT
@MainActor
func refreshTitle(
    load: @Sendable () async throws -> String,
    publish: @MainActor (String) -> Void
) async throws {
    let title = try await load()
    try Task.checkCancellation()
    publish(title)
}

Why and verification: the caller awaits refreshTitle through its own task/lifecycle; suspension leaves the executor available for other work. Add the owning request/session generation guard when overlapping loads can become stale, and test cancellation without a blocking bridge. A continuation can adapt a genuine callback API, but it cannot make a synchronous wrapper around future MainActor work safe. Apple Swift concurrency forward-progress contract

Pattern 11: blocking consumers can exhaust the cooperative pool

🟥 Broken — blocked tasks depend on more work from the same execution pool:

SWIFT
import Dispatch
​
nonisolated func blockingBridge() {
    let finished = DispatchSemaphore(value: 0)
    Task.detached { finished.signal() }
    finished.wait()
}
func riskyFanOut(count: Int) async {
    await withTaskGroup(of: Void.self) { group in
        for _ in 0..<count { group.addTask { blockingBridge() } }
    }
}

Trigger and capacity: if blocked consumers occupy all available cooperative execution capacity while their signal tasks still need that capacity, progress can stop: consumers → signals → available pool workers → consumers. This is a scheduling-dependent exhaustion risk, not a guarantee that count = some fixed number always deadlocks. Do not infer a public fixed pool size from CPU count or one successful run.

🟩 Corrected — let the async dependency suspend the task:

SWIFT
func collectValues(
    from loads: [@Sendable () async throws -> Int]
) async throws -> [Int] {
    try await withThrowingTaskGroup(of: Int.self) { group in
        for load in loads { group.addTask { try await load() } }
        var values: [Int] = []
        for try await value in group { values.append(value) }
        return values
    }
}

The inputs here are assumed bounded; results arrive in completion order. Bound concurrency separately for a large workload and ensure each load actually cooperates rather than hiding a blocking semaphore.

🟩 Legacy boundary alternative — offload a genuine blocking synchronous operation and resume once:

SWIFT
import Dispatch
​
func legacyRead(
    on queue: DispatchQueue,
    read: @escaping @Sendable () throws -> Int
) async throws -> Int {
    try await withCheckedThrowingContinuation { continuation in
        queue.async {
            continuation.resume(with: Result { try read() })
        }
    }
}

Why and verification: suspended callers do not occupy cooperative workers while a bounded, independently progressing legacy operation runs elsewhere. This bridge is not permission to move an existing wait cycle to GCD, flood queues with blocking work, or omit cancellation/error ownership. Verify corrected load completion and cancellation under constrained test conditions, inspect executor/thread waits with Instruments, and audit the legacy callback's exactly-once result. Apple pool-exhaustion and continuation guidance

Pattern 12: a cached task waits for its own completion

🟥 Broken — actor isolation prevents data races but the task dependency is cyclic:

SWIFT
actor BrokenBootstrap {
    private var cached: Task<Int, Never>?
    func value() async -> Int {
        if let cached { return await cached.value }
        let task = Task { await self.value() }
        cached = task
        return await task.value
    }
}

Trigger and chain: the first call installs task T, then T calls the public loader again, finds T, and awaits T.value. T cannot finish until T finishes. No thread has to be blocked: a suspended task can still have an unsatisfiable completion dependency. The runtime may diagnose misuse; do not require an observable permanent hang to recognize the cycle.

🟩 Corrected — the shared task performs an acyclic leaf dependency:

SWIFT
actor Bootstrap {
    private var cached: Task<Int, Never>?
    private let fetch: @Sendable () async -> Int
    init(fetch: @escaping @Sendable () async -> Int) { self.fetch = fetch }
    func value() async -> Int {
        if let cached { return await cached.value }
        let leaf = fetch
        let task = Task { await leaf() }
        cached = task
        return await task.value
    }
}

Why and verification: callers share T, while T computes a leaf result instead of re-entering the cache entry point. The injected leaf must not transitively call this same loader or introduce T → U → T. Verify concurrent corrected callers complete with the same intended result and one controlled leaf invocation; inspect task-handle dependencies, not just actor names. Invalidation, errors, and shared-work cancellation need additional policy beyond this minimal lifetime example. Swift structured/unstructured task model

Actor reentrancy compared with task-completion cycles

Ordinary reentrant actors do not keep their executor exclusively occupied for an entire async call. A call from actor A to B and then back to a different method on A can progress while the outer A method is suspended:

SWIFT
actor FirstActor {
    func start(with second: SecondActor) async -> Int {
        await second.reply(to: self)
    }
    func leaf() -> Int { 7 }
}
actor SecondActor {
    func reply(to first: FirstActor) async -> Int {
        await first.leaf()
    }
}

This actor-reference loop is not the self-await completion graph in Pattern 12. Reentrancy has a different hazard: state checked before await may change before resumption, causing a logical race even though each access is isolated. Recheck invariants or reserve state deliberately; do not claim that replacing every queue with an actor proves the business operation correct. SE-0306 actor reentrancy

Verification checklist for a suspected deadlock

  1. Capture all thread stacks or relevant Swift task/executor state while diagnosing the real app; identify each waiter, held resource, required producer, and target/worker capacity.
  2. Follow the chain until it closes or reaches work that can independently finish. Separate a busy UI loop, slow I/O, starvation, and a forgotten completion from a proven cycle.
  3. Repair the dependency or ownership boundary: direct already-isolated work, an acyclic ordering, an async completion, a real async API, or one state owner. Preserve the required data ordering and error/cancellation contract.
  4. Verify only corrected examples in an appropriate harness, using controlled completions and observable ordering. Include early exits, errors, cancellation, same-resource inputs, and account/lifecycle changes where relevant. Do not run the broken snippets to prove that they are dangerous.
  5. Use a test timeout to report noncompletion, not to declare the implementation sound. A clean sanitizer or a successful stress run does not prove absence of deadlock; inspect the dependency design as well.

For investigation mechanics, continue with Xcode debugging and profiling. Compare the related Android concurrency/deadlock answer for executor and lock ownership on another mobile platform. For a server-side companion, see transaction deadlocks and lock order.

Does Automatic Reference Counting remove strong reference cycles?

Short answer: No, objects in a strong reference cycle keep one another alive even when outside code no longer needs them. Automatic Reference Counting releases an object only when its last strong ownership is removed. Break an ownership link deliberately, using weak references or lifecycle cleanup where appropriate.

Detailed explanation:

ARC means Automatic Reference Counting. Swift uses it to manage the lifetime of class instances automatically: strong ownership keeps an object alive, and releasing the last strong ownership lets it deinitialize and be deallocated. The compiler inserts and optimizes retain/release operations, supported by the runtime, so ordinary Swift code does not manually balance retain and release calls. This automates object-memory management while leaving the ownership relationships to the program's design. Swift ARC guide, Apple ARC implementation/lifetime overview

No. ARC releases an instance only when its strong reference count reaches zero. A cycle keeps the count above zero until the cycle is broken.

The benefit is automatic lifetime management as ownership changes, rather than a periodic tracing collector that discovers unreachable object graphs. The tradeoff is that retain/release has a cost and ARC does not collect a disconnected strong cycle merely because the app can no longer reach it. ARC also does not synchronize mutable state or cancel a network operation for you.

Example assumptions: The worked examples are independent, illustrative Swift 6+ snippets, not one combined application. Ownership demos are synchronous unless marked MainActor/async; UI observation examples explicitly use MainActor. A compiler may shorten or extend an observed lifetime around last use, so never make a business workflow depend on the exact placement of a deinit print. Use explicit stop/close operations for required resource behavior. The intentionally invalid unowned path must not be executed.

Jump toApplied concept
Strong owners and deinitAliases own the same object; weak observers do not.
Values versus referencesA struct can still contain a shared class reference.
Strong/weak/unownedChoose the relationship from its lifetime contract.
Object cyclesReplace a non-owning back-reference or redesign the graph.
Stored closure cyclesA closure can own the object that stores it.
DelegatesClass-bound, weak callback relationship.
Tasks and teardownWeak capture, strong scope, and cooperative cancellation differ.
Unowned invariantNo ownership means the referent must still be alive when accessed.
Memory diagnosisTrace the retaining owner and verify the intended lifecycle.

Strong owners, aliases, and deinitialization

An ordinary class reference is strong unless declared/captured otherwise. Multiple variables can own the same instance; assigning one to nil removes that ownership, not every alias. A class's deinit runs automatically before deallocation; you do not call it yourself. It is a cleanup hook, not a cycle detector or a guarantee of cleanup after process termination.

SWIFT
final class TrackedDraft {
    deinit { print("draft released") }
}
func demonstrateOwners() {
    var primary: TrackedDraft? = TrackedDraft()
    var alias = primary
    weak var observer = primary
    primary = nil
    withExtendedLifetime(alias) {
        print(observer != nil)
    }
    alias = nil
    print(observer == nil)
}

Expected outcome when called in this isolated demo: the first Boolean is true because alias is explicitly kept alive; after the owners are released the observer becomes nil and deinit reports release. Do not infer an exact UI event order from a deinit log in a larger optimized app. withExtendedLifetime expresses required retention during a particular operation; a sensible owning API is usually better than scattering lifetime extensions throughout the code. Apple lifetime utility-4mmpv)

Value semantics do not imply a reference-free object graph

Structs and enums are values, not class identities managed in exactly the same way as class instances. However, a value can contain an owning class reference, and standard collections may use shared storage internally. Neither “all structs live on the stack” nor “using a struct removes every ARC concern” is a safe rule.

SWIFT
final class SelectionBox { var selected = false }
struct RowState {
    var title: String
    let selection: SelectionBox
}
let original = RowState(title: "Original", selection: SelectionBox())
var copy = original
copy.title = "Edited"
copy.selection.selected = true
print(original.title, original.selection.selected)

Expected outcome: Original true. The title changed in the copied value, while both values still reference the same SelectionBox. A capture list such as [box] similarly copies an object reference rather than deep-copying the object's contents. Model independent data with value fields when that is the required behavior. Swift value/reference guide, capture-list semantics

Strong, weak, and unowned relationships

RelationshipKeeps the instance aliveAfter its lifetime endsAppropriate contract
strongYesOwnership delays deallocation until released.This object/operation is responsible for keeping it available.
weakNoThe reference zeroes to nil; use an optional var.The related object may disappear independently; absence is valid.
unownedNoIt does not zero automatically; accessing a deallocated referent traps for checked unowned.The referent is guaranteed alive whenever this reference is accessed.

Unowned is commonly nonoptional, but optional unowned references also exist and still require explicit validity/nil management. Choosing weak or unowned is an ownership decision, not an optimization to apply indiscriminately. If a relationship must keep an object alive, weakening it can replace a leak with missing work. unowned(unsafe) removes safety checks and is not a routine repair. Swift weak/unowned reference rules

Two objects can keep each other alive

🟥 Broken ownership: both directions are strong. The following intentionally creates a leak if its function is called; it is not a runtime crash example.

SWIFT
final class CyclicOwner {
    var child: CyclicChild?
    deinit { print("cyclic owner released") }
}
final class CyclicChild {
    var owner: CyclicOwner?
    deinit { print("cyclic child released") }
}
func makeObjectCycle() {
    let owner = CyclicOwner()
    let child = CyclicChild()
    owner.child = child
    child.owner = owner
}
TEXT
After the external owners disappear:
CyclicOwner --strong--> CyclicChild
     ^                     |
     +-------strong--------+
Both objects still have an owning edge from inside the cycle.

Expected outcome: neither deinit message appears merely because makeObjectCycle returns; the internal ownership remains. ARC is behaving according to the references, not overlooking an unreachable cycle that a later tracing pass will necessarily collect.

🟩 Corrected ownership: the parent owns the child; the child observes its parent.

SWIFT
final class FlowOwner {
    var child: FlowChild?
    deinit { print("flow owner released") }
}
final class FlowChild {
    weak var owner: FlowOwner?
    deinit { print("flow child released") }
}
func makeAcyclicFlow() {
    let owner = FlowOwner()
    let child = FlowChild()
    owner.child = child
    child.owner = owner
    withExtendedLifetime(owner) { print(child.owner != nil) }
}

Expected outcome: the check is true while the owner is explicitly alive; without other owners, both instances can be released when their ownership ends. If the child must survive independently, its weak owner becomes nil. Another valid repair is deleting an unnecessary back-reference or explicitly clearing an owned relationship at a defined lifecycle boundary; the choice follows the domain's ownership contract.

Stored closures can close the same ownership cycle

A closure stored by an object can capture that object strongly. Escaping alone does not prove a cycle; trace who retains the closure and whether it retains the owner back.

🟥 Broken stored callback:

SWIFT
final class StrongRetryController {
    var retry: (() -> Void)?
    var attempts = 0
    func installAction() {
        retry = { self.attempts += 1 }
    }
    deinit { print("strong retry controller released") }
}
TEXT
controller --strong retry property--> closure
controller <--strong self capture---- closure

Expected outcome: after installAction, dropping the external controller reference leaves the cycle intact. Calling retry does not clear the property or automatically consume the callback; explicit [self] would still be strong. Swift escaping closure ownership

🟩 Corrected — preserve the existing weak callback contract:

🟦 Illustrative example:

SWIFT
final class RetryController {
    var retry: (() -> Void)?
    var attempts = 0
    func installAction() {
        retry = { [weak self] in
            self?.attempts += 1
        }
    }
}

🧠 The owner retains the closure, so a strong capture of the owner would close a cycle. A weak capture permits the action to become a no-op after deallocation; choose stronger lifetime ownership when the operation must finish rather than weakening references indiscriminately.

Expected outcome: while the controller is owned elsewhere, invoking retry increments attempts. A separately retained copy of this callback does not keep the controller alive and becomes inert after it disappears. If saving must finish independently of a screen, give the operation an appropriate service/task owner instead of silently abandoning required work. For a one-shot callback, clearing the stored property after taking a local copy can also release ownership—provided exactly-once behavior and synchronization are designed explicitly.

A delegate needs a class-bound, non-owning contract

SWIFT
@MainActor
protocol ImportDelegate: AnyObject { func importDidFinish() }
@MainActor
final class Importer {
    weak var delegate: (any ImportDelegate)?
    func finish() { delegate?.importDidFinish() }
}
@MainActor
final class ImportScreen: ImportDelegate {
    let importer = Importer()
    init() { importer.delegate = self }
    func importDidFinish() { print("show imported items") }
}

Expected outcome: ImportScreen strongly owns Importer, and Importer does not keep the screen alive through its delegate. AnyObject restricts adoption to reference types so weak storage is meaningful; MainActor makes UI callback isolation explicit. A weak delegate still needs another real owner, so assigning an otherwise unowned temporary delegate is not a reliable way to keep it available. Swift class-bound delegate protocols

Weak captures and strong scope across suspension

[weak self] controls the initial capture. Once guard let self binds a strong local, that local can remain needed across later suspension. This can be intentional for finite work; it is problematic when an indefinitely active observer keeps the object alive beyond its intended UI lifetime.

🟥 Lifetime trap — self is needed for the entire long-lived loop:

SWIFT
@MainActor
final class LongLivedObserver {
    private var task: Task<Void, Never>?
    var latest = 0
    func start(_ values: AsyncStream<Int>) {
        task = Task { [weak self] in
            guard let self else { return }
            for await value in values { self.latest = value }
        }
    }
    deinit { task?.cancel() }
}

Expected consequence: after the guard succeeds, the task keeps self available for future iterations. A never-ending stream can therefore prevent the deinit that was supposed to cancel it. This is not proof that every finite task retaining self is a permanent leak: tasks release their operation closure when that operation completes. Dropping a Task handle does not itself cancel its work. Apple task closure lifetime

🟩 Corrected — promote only while handling a value and expose explicit stop:

SWIFT
@MainActor
final class ScopedObserver {
    private var task: Task<Void, Never>?
    var latest = 0
    func start(_ values: AsyncStream<Int>) {
        stop()
        task = Task { [weak self] in
            for await value in values {
                guard !Task.isCancelled else { return }
                guard let self else { return }
                self.latest = value
            }
        }
    }
    func stop() { task?.cancel(); task = nil }
    deinit { task?.cancel() }
}

Why and verification: the strong local is scoped to processing one value rather than deliberately covering the next wait; the screen/feature owner calls stop at its lifecycle boundary. Verify replacement cancels previous observation and no updates publish after stop, using controlled stream events rather than timing sleeps. Cancellation is cooperative, and the producer must release its observation/resources on termination. Explicit close/stop is the semantic contract; deinit is a fallback, not the event that must first break an ownership dependency. Apple Task.cancel semantics)

Unowned access requires a real lifetime invariant

Use checked unowned only when the referent is guaranteed alive at every access. “It usually outlives me” is not that guarantee. This example contrasts a protected access with an intentionally invalid escape; do not call invalidUnownedUse.

SWIFT
final class InvoiceOwner { let name = "Account owner" }
final class Invoice {
    unowned let owner: InvoiceOwner
    init(owner: InvoiceOwner) { self.owner = owner }
}
func validUnownedUse() {
    let owner = InvoiceOwner()
    let invoice = Invoice(owner: owner)
    withExtendedLifetime(owner) { print(invoice.owner.name) }
}
func invalidUnownedUse() {
    var owner: InvoiceOwner? = InvoiceOwner()
    let invoice = Invoice(owner: owner!)
    owner = nil
    print(invoice.owner.name)
}

Expected outcomes: validUnownedUse prints the name while its owner is explicitly alive. In the invalid path, accessing a referent after its last strong ownership has gone violates the invariant and checked unowned access traps; it is not automatically converted to nil. If independent disappearance is allowed, use a weak optional and handle absence; if availability is required, retain a strong owner or redesign access through that owner. Optional unowned is not a zeroing substitute for weak.

Teardown and memory diagnosis verify the ownership story

  1. Reproduce a real lifecycle: present → use → dismiss, or start → cancel → stop. State which instances should remain owned afterward.
  2. Use weak probes/deinit logging as supporting evidence, with awareness of optimized lifetimes and hidden owners. Do not use an exact print position as the cleanup protocol.
  3. Inspect Xcode Memory Graph for unexpected survivors and strong incoming references. Follow the owner → callback/subscription/task → owner path instead of changing every reference to weak.
  4. Use Allocations/generations for repeated growth and peaks. A reachable, unbounded cache can waste memory without an ARC cycle; a clean Leaks result does not prove correct retention.
  5. Verify the repair also preserves required work, cancellation, errors, and callback ordering. Removing ownership can create silent dropped actions; keeping ownership until a bounded operation completes can be intentional.

Memory reclamation, resource cleanup, and data-race safety are separate responsibilities. ARC does not close a remote session, force arbitrary async work to stop, or make shared mutation safe. Continue with Xcode ownership diagnosis and ARC/closure practice. Apple Memory Graph workflow

What is the difference between a view's frame and bounds?

Short answer: The frame describes a view's rectangle in its parent's coordinate system. The bounds describes a rectangle in the view's own coordinate system, which its content and children use. Distinguishing those coordinate spaces helps you position, scroll, and transform views without confusing outside placement with inside geometry.

Detailed explanation:

Frame is the view's rectangle in its parent's coordinate system. Bounds is the view's own internal coordinate system.

More precisely, bounds is a rectangle in that local coordinate system: it has both an origin and a size. center locates the view in its parent. These properties answer different layout questions; choosing the right coordinate space prevents misplaced children, broken animations, and incorrect conversions.

🟨 Example assumptions: Swift 6+, UIKit on the main actor, geometry measured in points, not physical screen pixels. Unless a subsection says otherwise, views have identity transforms, default layer anchor points, no Auto Layout constraints, no scrolling/zoom, and ordinary UIKit coordinates with positive y downward. Each Swift block is independent. The original short snippet belongs inside a main-actor UIKit method or function; the other UIKit examples declare that isolation. Expected numbers are derived geometry, not recorded simulator/device output. No UIKit example was executed for these notes.

Work throughFocus
Coordinate spaces and dependenciesframe, bounds, center, and exact numbers
Changing the local originOriginal example and why content appears to shift
Child placementNonzero bounds and local centering
Custom drawingDrawing with local geometry
Nested conversionConvert points and rectangles between views
Scrolling and insetsViewport placement versus content offset
TransformsUndefined frame and valid alternatives
Auto LayoutConstraints and layout timing
Safe areasUnobscured content versus full bounds
SwiftUI layout.frame is a different API

Coordinate spaces and property dependencies

PropertyCoordinate spaceTypical use
badge.frameBadge's superviewPlace/size an untransformed view in manual layout
badge.boundsBadge's own spaceLocal drawing and layout of its children
badge.centerBadge's superviewMove the view; remains meaningful with transforms

For a badge whose frame is (x: 20, y: 30, width: 80, height: 40), initial bounds are (0, 0, 80, 40) and center is (60, 50). Its parent's own frame might locate that parent somewhere else in a grandparent; it does not change which space badge.frame uses. Apple defines these spaces in UIView.frame, UIView.bounds, and UIView.center.

TEXT
container coordinates                    badge coordinates
(0,0)                                    (0,0) ┌────────────┐
   (20,30) ┌────────────┐                       │    (40,20) │
           │  center   │                       │ local mid  │
           │  (60,50)  │                       └────────────┘ (80,40)
           └────────────┘ (100,70)

🟦 Worked dependencies: setting frame affects center and bounds size; setting center moves frame origin; changing bounds size resizes around the existing center. In this simple identity/default-anchor case, center = (frame.midX, frame.midY) and frame.origin = center − bounds.size / 2.

SWIFT
import UIKit
​
@MainActor
func geometryDependencies() {
    let badge = UIView(frame: CGRect(x: 20, y: 30, width: 80, height: 40))
    print(badge.frame, badge.bounds, badge.center)
    badge.frame.origin = CGPoint(x: 40, y: 50)
    print(badge.center)
    badge.center = CGPoint(x: 60, y: 50)
    badge.bounds.size = CGSize(width: 100, height: 60)
    print(badge.frame, badge.center)
    badge.frame.size = CGSize(width: 120, height: 80)
    print(badge.bounds, badge.center)
}
Step in this sequenceFrame (x,y,w,h)Bounds (x,y,w,h)Center (x,y)
Initial(20,30,80,40)(0,0,80,40)(60,50)
Set frame origin(40,50,80,40)(0,0,80,40)(80,70)
Set center back(20,30,80,40)(0,0,80,40)(60,50)
Set bounds size(10,20,100,60)(0,0,100,60)(60,50)
Set frame size(10,20,120,80)(0,0,120,80)(70,60)

Changing bounds.size preserves center here; changing frame.size preserves frame origin here. Do not apply this table to transformed views or views whose constraints/layout code subsequently recompute their geometry.

Bounds origin changes the local mapping

🟦 Illustrative example: the original snippet changes the origin without changing size.

SWIFT
import UIKit
​
let container = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
let badge = UIView(frame: CGRect(x: 20, y: 30, width: 80, height: 40))
container.addSubview(badge)
badge.bounds.origin = CGPoint(x: 5, y: 0)

🧠 The badge is positioned in its parent using its frame, while changing its bounds origin shifts its local coordinate system. With a nonidentity transform, do not treat frame as a simple layout source of truth; work with bounds/center or constraints as appropriate.

After this change, the badge's frame remains (20,30,80,40), center remains (60,50), and bounds become (5,0,80,40). The badge's visible local rectangle now starts at local (5,0). A feature drawn at local (0,0) maps to container (15,30), five points left of the badge's placed left edge. The view's placement did not move; the local-to-parent mapping changed.

For the stated identity/default-anchor assumptions, a local point maps as parentPoint = frame.origin + (localPoint − bounds.origin). Increasing bounds origin therefore shifts existing local content/subviews in the opposite displayed direction. This also explains why bounds.origin is not another name for frame.origin. See Apple's view geometry and coordinate-system guide.

Child placement uses the parent's local bounds

🟥 Bug: treating a parent's local visible top-left as always .zero, or using that parent's center to position a child. The child's frame/center are expressed in the parent's local space; the parent's center belongs to the grandparent's space.

SWIFT
import UIKit
​
@MainActor
func placeChildWithNonzeroBounds() {
    let parent = UIView(frame: CGRect(x: 20, y: 30, width: 80, height: 40))
    parent.bounds.origin = CGPoint(x: 10, y: 5)
    parent.clipsToBounds = true
    let child = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 10))
    parent.addSubview(child)
    child.frame.origin = .zero // Wrong if the goal is visible top-left.
    child.frame.origin = parent.bounds.origin // Correct for that goal.
    child.center = CGPoint(x: parent.bounds.midX, y: parent.bounds.midY)
    print(child.frame)
}

With the wrong origin (0,0), the child's top-left maps to (10,25) in the parent's superview, outside the parent's top-left (20,30). Setting its origin to (10,5) aligns those top-lefts. The final line instead centers it: local center (50,25) gives child frame (40,20,20,10) and displayed center (60,50) in the grandparent. Choose the desired alignment; these two corrections demonstrate different placements.

🟨 Bounds do not automatically clip children. This example explicitly sets clipsToBounds = true; otherwise outside content may remain visible. If the parent later resizes, recalculate manual child layout in layoutSubviews() or use constraints rather than relying on a one-time assignment. Apple's view hierarchy guide documents clipping and subview coordinates.

Custom drawing stays in local coordinates

Use bounds for the shape inside a view. Using frame in draw(_:) adds a parent-space offset to drawing that already happens in the view's local space. Also, rect is the invalidated region, which may be smaller than the full bounds; it is not a replacement definition of the whole shape.

SWIFT
import UIKit
​
@MainActor
final class OutlineBadge: UIView {
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }
        context.saveGState()
        defer { context.restoreGState() }
        context.clip(to: rect)
        UIColor.systemBlue.setStroke()
        let path = UIBezierPath(ovalIn: bounds.insetBy(dx: 2, dy: 2))
        path.lineWidth = 2
        path.stroke()
    }
}

With bounds (0,0,80,40), the oval's rectangle is (2,2,76,36), regardless of whether the view is placed at parent x 20 or 200. With nonzero bounds origin (10,5), it becomes (12,7,76,36), keeping the same two-point local inset. Configure this outline-only view with isOpaque = false; request redraw with setNeedsDisplay() when its drawing inputs change, and consider .redraw content mode when resizing requires fresh drawing. Do not call draw(_:) directly. See UIView.draw(_:).

Conversion crosses nested coordinate spaces

Manually adding frame origins works only for restricted hierarchies. Bounds origins, scrolling, transforms, and deeper nesting make that shortcut fragile. convert(_:to:) takes a point/rect in the receiver's local space; convert(_:from:) takes one in the source view's space. Concrete views must share a window. This example creates one local window for the geometry demonstration; application code normally uses its existing scene/window hierarchy. See point conversion and rectangle conversion.

SWIFT
import UIKit
​
@MainActor
func convertNestedGeometry() {
    let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 320, height: 640))
    let root = UIView(frame: window.bounds)
    let panel = UIView(frame: CGRect(x: 20, y: 30, width: 200, height: 200))
    let badge = UIView(frame: CGRect(x: 10, y: 15, width: 40, height: 20))
    window.addSubview(root)
    root.addSubview(panel)
    panel.addSubview(badge)
    withExtendedLifetime(window) {
        let point = badge.convert(CGPoint.zero, to: root)
        print(point, badge.convert(point, from: root))
        print(badge.convert(badge.bounds, to: root))
    }
}

Expected values are point (30,45), round trip (0,0), and rectangle (30,45,40,20). 🟥 badge.convert(badge.frame, to: root) is wrong: badge.frame is already in panel coordinates, but this call would reinterpret it as badge coordinates. Convert badge.bounds from badge, or convert badge.frame from panel. Use a shared intended ancestor for overlay placement. Under rotation, a converted CGRect describes a rectangle enclosing the converted area, not the exact rotated outline; use converted corners when that distinction matters.

Scrolling separates viewport placement from content position

A scroll view's frame locates its viewport in its superview. Scrolling changes the content mapping via contentOffset, not that placement. The following example isolates a vertical scroll: zoom is 1, inset adjustment is disabled, and content insets start at zero. Use the scroll API rather than manually changing its bounds to implement scrolling. See UIScrollView.contentOffset.

SWIFT
import UIKit
​
@MainActor
func scrollGeometry() {
    let scroll = UIScrollView(frame: CGRect(x: 20, y: 30, width: 200, height: 100))
    scroll.contentInsetAdjustmentBehavior = .never
    scroll.contentInset = .zero
    scroll.contentSize = CGSize(width: 200, height: 600)
    scroll.contentOffset = CGPoint(x: 0, y: 120)
    print(scroll.frame, scroll.bounds.origin)
    let viewportY = CGFloat(150) - scroll.contentOffset.y
    print(viewportY)
    scroll.contentInset.top = 20
    scroll.setContentOffset(CGPoint(x: 0, y: -scroll.adjustedContentInset.top),
                            animated: false)
    print(scroll.contentOffset.y)
}

Initially, frame remains (20,30,200,100) and bounds origin is (0,120). A content feature at y 150 is 30 points below the viewport's top; in the superview that is y 60. The feature's content coordinate did not change. After the explicit 20-point top inset and offset assignment, the offset is -20, exposing that top padding.

With automatic adjustments, safe areas can contribute to adjustedContentInset; a usual top-resting offset is -adjustedContentInset.top, not universally zero. Wait until the view's real container/safe-area layout is established before restoring an intended offset, and account for app-specific zoom, content changes, bounce, and restoration policy. Insets describe padding/adjustment; they do not move the scroll view's frame. See adjustedContentInset.

A transformed view has no usable frame contract

🟨 With a nonidentity transform, Apple declares frame undefined: ignore it and do not assign it. A numerical value observed in the debugger is not a supported bounding-box contract. Use center for position and bounds for local size, or update your layout constraints. UIView.frame and UIView.transform state this limitation.

SWIFT
import UIKit
​
@MainActor
func resizeRotatedBadge() {
    let badge = UIView(frame: CGRect(x: 20, y: 30, width: 80, height: 40))
    badge.transform = CGAffineTransform(rotationAngle: .pi / 4)
    // badge.frame.size.width = 120 // Wrong under the nonidentity transform.
    badge.bounds.size = CGSize(width: 120, height: 40)
    badge.center = CGPoint(x: 150, y: 100)
    print(badge.bounds.size, badge.center)
}

Expected supported values are local size (120,40) and parent-space center (150,100). There is deliberately no expected transformed frame. Transforming a view does not rewrite its local bounds into the rotated outline. Auto Layout still calculates its layout using untransformed geometry; rotation can make rendered content overlap neighboring views even when constraints are satisfied.

Constraints determine frames during layout

🟥 A manual frame assignment does not change active constraints. The next relevant layout pass can replace it. Change the constraint representing your intended relationship, then lay out the appropriate common ancestor if you need the resulting geometry immediately. Calling layoutIfNeeded() on an unrelated view does not flush another subtree; without pending work it does nothing. See Apple's deferred layout pass and layoutIfNeeded().

SWIFT
import UIKit
​
@MainActor
func resizeConstrainedBadge() {
    let container = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
    let badge = UIView()
    badge.translatesAutoresizingMaskIntoConstraints = false
    container.addSubview(badge)
    let width = badge.widthAnchor.constraint(equalToConstant: 80)
    NSLayoutConstraint.activate([
        badge.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 20),
        badge.topAnchor.constraint(equalTo: container.topAnchor, constant: 30),
        width, badge.heightAnchor.constraint(equalToConstant: 40)
    ])
    container.layoutIfNeeded()
    badge.frame.size.width = 999 // Wrong source of truth for this layout.
    width.constant = 100
    container.layoutIfNeeded()
    print(badge.frame)
}

With this isolated identity-transform container, the resolved frame starts at (20,30,80,40) and ends at (20,30,100,40). Setting width to 999 was transient and did not change the constraint. Reading geometry immediately after construction or a constraint update can reveal old/zero values before layout. For geometry-dependent controller work, use the appropriate post-layout callback such as viewDidLayoutSubviews(); for custom subview arrangement, use layoutSubviews() and call super rather than invoking that callback yourself. Recompute only when needed to avoid layout feedback loops.

Safe areas describe unobscured layout space

bounds covers the view's local rectangle; it does not promise that bars or ancestor content leave every part unobscured. Use safeAreaLayoutGuide to place controls within the available area. A nested view already inside its parent's safe area may have zero safe-area insets. Before a view is installed/visible, its guide can simply match its edges; an arbitrary fixed top inset is not a device-independent solution. See safeAreaLayoutGuide and positioning content relative to the safe area.

SWIFT
import UIKit
​
@MainActor
final class SafeBadgeController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let badge = UILabel()
        badge.text = "Ready"
        badge.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(badge)
        let safe = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            badge.topAnchor.constraint(equalTo: safe.topAnchor, constant: 12),
            badge.leadingAnchor.constraint(equalTo: safe.leadingAnchor, constant: 16),
            badge.trailingAnchor.constraint(lessThanOrEqualTo: safe.trailingAnchor,
                                            constant: -16)
        ])
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print(view.bounds, view.safeAreaLayoutGuide.layoutFrame)
    }
}

Mount this controller in the application's normal window/container to inspect meaningful safe-area results. The label's top is 12 points below the safe area's top, not necessarily y 12 in the full bounds. Its intrinsic content size supplies its size. Expected numeric safe-area values depend on the real device, orientation, bars, and container; these notes invent none.

SwiftUI frame participates in SwiftUI layout

SwiftUI's .frame(width:height:alignment:) creates a layout wrapper with specified dimensions and alignment. It is not a mutable UIKit CGRect containing parent x/y. Its parent still decides where the resulting view is placed, and modifier order changes which wrapper an effect applies to. See SwiftUI.frame(width:height:alignment:) and configuring views.

SWIFT
import SwiftUI
​
@MainActor
struct GeometryBadge: View {
    var body: some View {
        VStack(spacing: 12) {
            Text("Ready")
                .frame(width: 120, height: 44, alignment: .leading)
                .border(.blue)
            Text("Ready")
                .border(.blue)
                .frame(width: 120, height: 44, alignment: .leading)
        }
    }
}

The first border surrounds the 120-by-44-point wrapper; the second surrounds the text before that wrapper is added. Neither call sets a UIKit frame origin. A fixed 44-point height is only a teaching choice: production text must accommodate localization and Dynamic Type rather than assuming this box always fits.

🧠 Interview explanation: frame describes placement in a parent, bounds describes local geometry, and center gives a parent-space position. Name the coordinate space before doing arithmetic; then check transforms, constraints, scroll offsets, and safe areas. For nearby UIKit fundamentals, continue with the compact frame/bounds lesson.

How do the Open/Closed and Liskov Substitution principles differ?

Short answer: The Open/Closed Principle asks how you can add behavior without repeatedly changing stable consumers. The Liskov Substitution Principle asks whether a replacement implementation still honors the behavior those consumers rely on. One concerns extending a design; the other concerns whether substituting an implementation remains correct.

Detailed explanation:

OCP concerns adding implementations without modifying stable consumers. LSP requires each implementation to preserve the abstraction's behavioral promises.

SOLID groups five design principles for containing the impact of change. They help a mobile feature survive new delivery options, storage migrations, read-only previews, and SDK replacements without spreading unrelated edits through its screens. They do not require a protocol for every type, a class for every method, or a ban on changing existing code.

🟨 Example scope: independent illustrative Swift 6+ snippets. Run/copy each block separately; repeated names deliberately make the blocks self-contained. UI-facing state holders use @MainActor; all other examples are synchronous local operations with no actor crossings, so no Sendable promise is needed. The catalog clients and archives below are local teaching implementations, not actual SDK, disk, or network calls. Shipping amounts are draft estimates in cents, never payment authorizations or charges.

PrincipleBoundary it protectsWorked mobile scenario
S — Single ResponsibilityThings that change for the same reason belong togetherSaving a draft while presentation and record format evolve
O — Open/ClosedStable consumers and a chosen extension pointAdding express or pickup shipping estimates
L — Liskov SubstitutionBehavioral promises across implementationsA read-only preview must not pretend to support saves
I — Interface SegregationCapabilities each client actually needsA catalog row should not depend on bulk editing/export
D — Dependency InversionFeature policy from volatile implementation detailsReplacing a vendor catalog adapter and testing the screen

SRP — separate independent reasons for change

A module should group a cohesive responsibility: changes requested for the same reason should land together, while independent concerns have separate owners. This is about reasons/stakeholders for change, not counting methods. See Robert C. Martin's Single Responsibility Principle.

Trigger: a user taps Save draft. Product changes title validation, storage engineering changes the record representation, and design changes the confirmation copy. If all three live in the screen's action, each change requires touching code for the other two concerns.

🟥 Broken separation: this compiles, but one action owns validation, a delimiter-based storage format, and presentation. The ad-hoc format needs an explicit parsing/escaping contract as additional fields are introduced.

SWIFT
import Foundation
​
@MainActor
final class DraftScreen {
    private(set) var record = ""
    private(set) var message = ""
    func saveTapped(_ input: String) {
        let title = input.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !title.isEmpty else { message = "Enter a title"; return }
        record = "draft-v1|" + title
        message = "Saved: " + title
    }
}

🟩 Improved separation: DraftNaming owns validation, DraftArchive owns encoding/storage representation, and DraftScreen owns the user action and UI state. These concrete types are sufficient for this small feature; SRP does not itself demand injection protocols.

SWIFT
import Foundation
​
struct DraftNaming {
    func validated(_ input: String) -> String? {
        let value = input.trimmingCharacters(in: .whitespacesAndNewlines)
        return value.isEmpty ? nil : value
    }
}
struct DraftArchive {
    private(set) var records: [Data] = []
    mutating func save(title: String) throws {
        records.append(try JSONEncoder().encode(title))
    }
}
@MainActor
final class DraftScreen {
    private let naming = DraftNaming()
    private(set) var archive = DraftArchive()
    private(set) var message = ""
    func saveTapped(_ input: String) {
        guard let title = naming.validated(input) else {
            message = "Enter a title"; return
        }
        do {
            try archive.save(title: title)
            message = "Saved: " + title
        } catch { message = "Could not save draft" }
    }
}

Expected behavior and acceptance: saving " Summer|Trip " archives one JSON string that decodes to "Summer|Trip" and displays "Saved: Summer|Trip". Blank input adds no record and displays "Enter a title". Test the naming rule independently, round-trip a delimiter-containing title through the archive, and check the action's observable state. A future record-format change stays in the archive; a confirmation-copy change stays in presentation. This local archive is not durable storage, and the generic error label is only a UI example; real adapters should preserve diagnostic context.

Tradeoff: splitting every line into a type would obscure a simple action. Separate real change pressures first; keep closely related validation rules together. When localization becomes a separate concern, introduce a presentation boundary based on that need rather than preemptively adding layers.

OCP — extend a selected policy without editing its consumers

OCP asks you to stabilize a useful consumer while allowing a likely kind of variation through an explicit extension point. It does not mean software is closed against every possible future change. Martin's Open/Closed Principle discusses this selective closure.

Trigger: the delivery-options screen gains an express estimate, then pickup. Every estimate consumer should use the same selected policy instead of repeating an expanding list of delivery kinds.

🟥 Change spreads into the consumer: adding another option requires editing quote, and copying this switch into a summary screen would multiply that work. A switch is appropriate for a deliberately closed set; the problem here is the agreed requirement for independently added policies.

SWIFT
enum DeliveryOption { case standard, express }
enum QuoteError: Error { case invalidWeight }
func quote(option: DeliveryOption, weightGrams: Int) throws -> Int {
    guard (0...20_000).contains(weightGrams) else {
        throw QuoteError.invalidWeight
    }
    switch option {
    case .standard: return 500
    case .express: return 700 + (weightGrams / 1_000) * 100
    }
}

🟦 Original illustrative example: the stable consumer accepts a shipping policy. Its fixed input of 1_000 grams is valid under the teaching contract below.

SWIFT
protocol ShippingFee {
    func cents(forWeightGrams weight: Int) -> Int
}
struct FlatShipping: ShippingFee {
    func cents(forWeightGrams weight: Int) -> Int { 500 }
}
func quote(using policy: any ShippingFee) -> Int {
    policy.cents(forWeightGrams: 1_000)
}

🧠 Adding a new policy leaves quote unchanged, illustrating OCP. Every policy must also preserve documented units, valid input ranges, and nonnegative-result semantics for LSP; matching the signature alone is insufficient.

Documented teaching contract: inputs are whole grams in 0...20_000; results are nonnegative whole cents of the same agreed currency, with no mutation, I/O, or charge. FlatShipping returns 500 cents for every valid weight, including zero. Callers validate external inputs before invoking a policy. Merely naming a parameter weight does not enforce its units or range.

🟩 Independent extended version: a second policy and a validating boundary let the composition choose behavior while the consumer stays unchanged when another conforming policy is added.

SWIFT
protocol ShippingFee {
    func cents(forWeightGrams weight: Int) -> Int
}
struct FlatShipping: ShippingFee {
    func cents(forWeightGrams weight: Int) -> Int { 500 }
}
struct ExpressShipping: ShippingFee {
    func cents(forWeightGrams weight: Int) -> Int {
        700 + (weight / 1_000) * 100
    }
}
enum QuoteError: Error { case invalidWeight, invalidPolicyResult }
func quote(weightGrams: Int, using policy: any ShippingFee) throws -> Int {
    guard (0...20_000).contains(weightGrams) else {
        throw QuoteError.invalidWeight
    }
    let amount = policy.cents(forWeightGrams: weightGrams)
    guard amount >= 0 else { throw QuoteError.invalidPolicyResult }
    return amount
}
func deliveryScreenEstimate() throws -> Int {
    try quote(weightGrams: 1_000, using: ExpressShipping())
}

Expected behavior and acceptance: the original quote(using: FlatShipping()) returns 500; the extended screen returns 800. In the extended version, -1 and 20_001 grams fail validation before a policy is invoked. The bounded input and simple integer formula avoid unchecked large-input arithmetic. Adding a pickup implementation returning zero requires a new policy and wiring/registration changes; it does not require editing quote(weightGrams:using:). Output validation catches a negative result defensively; it does not make a broken policy behaviorally correct.

Tradeoff: the extension point is the estimate calculation, not every aspect of delivery. Changing the meaning of weight, supported currencies, or the contract itself can legitimately require consumer changes. Fix bugs and improve the abstraction when needed; do not preserve an incorrect API merely to claim OCP compliance.

LSP — preserve the promised behavior of the abstraction

A replacement must preserve what consumers can rely on: accepted inputs, promised outputs, invariants, mutation effects, and documented failures. Requiring extra preconditions or weakening a promised postcondition breaks substitution. A matching Swift protocol signature is necessary but cannot establish all these semantics. See Liskov and Wing's A Behavioral Notion of Subtyping and Swift's protocol requirements.

Trigger: a catalog editor is reused for a read-only preview. For this example, EditableCatalog promises that saving a valid product replaces that ID's value and an immediate read returns the saved product, with no concurrent writer or eviction. This is an in-memory editable store contract; an evicting cache would need a different documented contract.

🟥 Broken substitution: ReadOnlyPreview satisfies the method signatures but silently discards the write. Returning normally falsely signals the promised save behavior.

SWIFT
struct Product: Equatable { let id: String; let title: String }
protocol EditableCatalog: AnyObject {
    func product(id: String) -> Product?
    func save(_ product: Product)
}
final class ReadOnlyPreview: EditableCatalog {
    private let item = Product(id: "mug", title: "Old title")
    func product(id: String) -> Product? { id == item.id ? item : nil }
    func save(_ product: Product) { /* Silently unsupported. */ }
}
func renameInPreview() -> String? {
    let store: any EditableCatalog = ReadOnlyPreview()
    store.save(Product(id: "mug", title: "Travel mug"))
    return store.product(id: "mug")?.title
}

The expected result is "Old title", although the editor relies on a successful rename. Throwing a new unsupported-operation error would also violate this nonthrowing save contract; a declared throws would not automatically authorize every undocumented failure either. Do not repair it by teaching every caller to special-case this concrete implementation.

🟩 Improved capability model: a read-only preview adopts reading only; an editable store genuinely fulfills reading plus writing. This also uses ISP, but the LSP repair is that every claimed capability keeps its contract.

SWIFT
struct Product: Equatable { let id: String; let title: String }
protocol CatalogReading {
    func product(id: String) -> Product?
}
protocol CatalogEditing: CatalogReading, AnyObject {
    func save(_ product: Product)
}
struct ReadOnlyPreview: CatalogReading {
    let item = Product(id: "mug", title: "Old title")
    func product(id: String) -> Product? { id == item.id ? item : nil }
}
final class MemoryCatalog: CatalogEditing {
    private var products: [String: Product] = [:]
    func product(id: String) -> Product? { products[id] }
    func save(_ product: Product) { products[product.id] = product }
}
func verifyEditableCatalog(_ store: any CatalogEditing) -> Bool {
    let revised = Product(id: "mug", title: "Travel mug")
    store.save(revised)
    return store.product(id: revised.id) == revised
}

Expected behavior and acceptance: verifyEditableCatalog(MemoryCatalog()) returns true. The read-only preview can feed a display client but cannot be passed to this editing function. Run the same editable-store contract checks against every real editable adapter: create, overwrite an existing ID, retain another ID, and distinguish missing data from operational failure according to the agreed API. If a real store can fail, design an explicit error-bearing editable contract and make all its clients handle those failures; do not silently weaken the original promise.

🟦 Sampled contract check for the original shipping abstraction: this independent block demonstrates why interface conformance and behavior need separate evidence.

SWIFT
protocol ShippingFee {
    func cents(forWeightGrams weight: Int) -> Int
}
struct FlatShipping: ShippingFee {
    func cents(forWeightGrams weight: Int) -> Int { 500 }
}
func sampledShippingContract(_ policy: any ShippingFee) -> Bool {
    [0, 1, 999, 1_000, 20_000].allSatisfy {
        policy.cents(forWeightGrams: $0) >= 0
    }
}
func shippingContractEvidence() -> (nonnegative: Bool, knownQuote: Bool) {
    let policy = FlatShipping()
    return (sampledShippingContract(policy),
            policy.cents(forWeightGrams: 1_000) == 500)
}

Expected evidence is (true, true). Sampling is not proof over the full range, and nonnegative output alone cannot prove correct currency/units, lack of side effects, or policy-specific pricing. Add boundary/property tests and known examples appropriate to each promise. OCP lets you add the type; LSP determines whether using it behind the abstraction remains safe. This reasoning applies to struct conformers as well as class inheritance.

Tradeoff: contracts should be as strong as consumers need and as honest as implementations can satisfy. Do not require read-after-write persistence from a best-effort evicting cache by accident. Do not weaken a required editable-store promise simply to force a read-only object into the hierarchy; give it the capability it actually supports.

ISP — expose cohesive capabilities for each client

Clients should depend on an interface shaped around their needs instead of unrelated operations. The same concrete provider may implement several such interfaces; ISP does not mandate a one-method protocol. See Martin's Interface Segregation Principle.

Trigger: a lightweight catalog row displays a title and thumbnail name. An administrative editor gains bulk replacement and CSV export. The row and its test doubles should not acquire those administrative dependencies.

🟥 Broad interface: the display client receives unnecessary write/export authority. Even a tiny row stub must implement operations the row never uses.

SWIFT
protocol CatalogService {
    func title(id: String) -> String?
    func thumbnailName(id: String) -> String?
    func replaceAll(titles: [String: String])
    func exportCSV() -> String
}
struct CatalogRow {
    let catalog: any CatalogService
    func text(id: String) -> String { catalog.title(id: id) ?? "Missing" }
}
struct RowStub: CatalogService {
    func title(id: String) -> String? { "Travel mug" }
    func thumbnailName(id: String) -> String? { "mug-thumbnail" }
    func replaceAll(titles: [String: String]) { }
    func exportCSV() -> String { "" }
}

The no-op methods here illustrate test-double scaffolding forced by the broad type, not acceptable production replacements for promised administration behavior. An admin API change can now affect the row's dependency and conformers despite no display requirement changing.

🟩 Improved client boundary: keep the two cohesive read operations together, and expose bulk editing separately. A display stub needs only the read interface.

SWIFT
protocol CatalogReading {
    func title(id: String) -> String?
    func thumbnailName(id: String) -> String?
}
protocol CatalogBulkEditing {
    func replaceAll(titles: [String: String])
}
struct CatalogRow {
    let catalog: any CatalogReading
    func text(id: String) -> String { catalog.title(id: id) ?? "Missing" }
    func thumbnail(id: String) -> String? { catalog.thumbnailName(id: id) }
}
struct RowStub: CatalogReading {
    func title(id: String) -> String? { id == "mug" ? "Travel mug" : nil }
    func thumbnailName(id: String) -> String? {
        id == "mug" ? "mug-thumbnail" : nil
    }
}
func rowEvidence() -> (title: String, missing: String) {
    let row = CatalogRow(catalog: RowStub())
    return (row.text(id: "mug"), row.text(id: "unknown"))
}

Expected behavior and acceptance: rowEvidence() returns ("Travel mug", "Missing"). Add a new bulk-edit requirement and confirm the row and RowStub need no changes. A real catalog object may conform to both interfaces, while the row receives only its read view; the editor can require CatalogReading & CatalogBulkEditing when it genuinely needs both. Separate CSV export into its own capability if a distinct export client needs it.

Tradeoff: avoid creating dozens of overlapping protocols named after individual methods. Group operations that serve a cohesive client role and change together. A read-only interface narrows what this client can ask through that reference; it is not an authorization/security boundary by itself.

DIP — let feature policy own the abstraction

High-level feature rules and low-level details should depend toward a suitable abstraction rather than making the feature depend directly on a volatile vendor/storage API. Runtime calls can still go from feature to adapter; DIP concerns source dependencies. See Martin's Dependency Inversion Principle and the Separated Interface pattern.

Trigger: the catalog screen shows only available products. A vendor changes its DTO fields, an offline adapter is introduced, or a deterministic preview/test needs a fixed catalog. The screen's availability rule should remain independent of those details.

🟥 Constructor injection without dependency inversion: the screen receives its dependency instead of constructing it, but still names the concrete vendor client and understands its DTO. This is DI as a construction technique; it has not removed the policy-to-detail source dependency.

SWIFT
struct VendorProductDTO { let name: String; let canOrder: Bool }
struct VendorCatalogClient {
    func fetch() -> [VendorProductDTO] {
        [VendorProductDTO(name: "Travel mug", canOrder: true)]
    }
}
@MainActor
final class CatalogScreen {
    private let client: VendorCatalogClient
    private(set) var rows: [String] = []
    init(client: VendorCatalogClient) { self.client = client }
    func refresh() {
        rows = client.fetch().filter { $0.canOrder }.map { $0.name }
    }
}

🟩 Improved source dependency and composition: the feature owns CatalogListing and its domain-shaped CatalogItem. The adapter maps vendor DTOs; the composition root chooses concrete wiring. The screen never requests a service locator or imports a vendor type. For compact copyability these logical module boundaries are shown in one block; an actual package split also needs appropriate access control/dependency declarations.

SWIFT
// Feature boundary.
struct CatalogItem { let title: String; let isAvailable: Bool }
protocol CatalogListing { func load() -> [CatalogItem] }
@MainActor
final class CatalogScreen {
    private let catalog: any CatalogListing
    private(set) var rows: [String] = []
    init(catalog: any CatalogListing) { self.catalog = catalog }
    func refresh() {
        rows = catalog.load().filter { $0.isAvailable }.map { $0.title }
    }
}
// Adapter boundary: local vendor stand-in, not a network SDK call.
struct VendorProductDTO { let name: String; let canOrder: Bool }
struct VendorCatalogClient {
    func fetch() -> [VendorProductDTO] {
        [VendorProductDTO(name: "Travel mug", canOrder: true)]
    }
}
struct VendorCatalogAdapter: CatalogListing {
    let client: VendorCatalogClient
    func load() -> [CatalogItem] {
        client.fetch().map { CatalogItem(title: $0.name, isAvailable: $0.canOrder) }
    }
}
// Composition root.
@MainActor
func makeCatalogScreen() -> CatalogScreen {
    CatalogScreen(catalog: VendorCatalogAdapter(client: VendorCatalogClient()))
}
// Test consumer without a vendor dependency.
struct StubCatalog: CatalogListing {
    let items: [CatalogItem]
    func load() -> [CatalogItem] { items }
}
@MainActor
func catalogScreenEvidence() -> Bool {
    let screen = CatalogScreen(catalog: StubCatalog(items: [
        CatalogItem(title: "Travel mug", isAvailable: true),
        CatalogItem(title: "Retired cup", isAvailable: false)
    ]))
    screen.refresh()
    return screen.rows == ["Travel mug"]
}
TEXT
Source dependencies: Feature ──> CatalogListing <── Vendor adapter
                     App composition ──> Feature + Vendor adapter
Runtime call:        Screen ──> selected adapter ──> local data provider

Expected behavior and acceptance: catalogScreenEvidence() returns true; unavailable items stay out of the rows. The composed local vendor example also displays "Travel mug". Replace or rename vendor DTO fields inside the adapter/client boundary without editing the screen, its protocol, or its stub. Test the adapter mapping separately; a stub-only feature check cannot prove an adapter's correctness.

DIP versus DI: DIP chooses the dependency direction and meaningful contract; constructor DI supplies a chosen implementation. A composition root is expected to name concrete adapters. No DI container is required. A closure or generic constraint can express the dependency just as well when it fits the feature. Fowler's dependency injection article explains separating configuration from use.

Tradeoff: replacing a concrete type with Any or a giant SDK-shaped protocol would hide useful information without creating a feature boundary. A stable value type/helper may remain concrete. Real remote loading needs an honest asynchronous/error/cancellation contract and correct isolation, not a blocking SDK call on the main actor; this synchronous local example deliberately has none of those effects. Design that richer contract when introducing the actual adapter, and validate its behavior under LSP.

Applying the principles to a real change

Start with a user-visible change and its acceptance behavior, then identify the smallest boundary that contains it. Record the consumer contract before adding interchangeable implementations; verify both feature behavior and adapters. Swift's API Design Guidelines emphasize clarity at use sites and documenting APIs, which makes these boundaries reviewable.

Review observationUseful responseEvidence to request
UI copy, validation, and record encoding change for different reasonsSRP: separate those responsibilitiesA record migration leaves naming/presentation checks intact
Another estimate policy requires editing every screenOCP: share a stable policy consumerNew policy is selected in composition; existing cases still pass
A replacement ignores writes or changes accepted inputsLSP: correct the contract/type relationshipShared contract checks plus implementation-specific cases
A row mock needs unrelated administration methodsISP: narrow the client-facing capabilityRow compiles/tests without admin/export dependencies
Feature code imports vendor DTOs or builds the SDK clientDIP: feature-shaped abstraction and adapterStub-driven feature check plus adapter mapping check

These principles reinforce each other: SRP identifies separate change pressures, ISP shapes a client's capability, DIP places the dependency boundary, OCP supports selected extensions, and LSP keeps those extensions trustworthy. Use them to explain a concrete design decision and its tradeoff, rather than counting protocols or labeling every switch a violation.

Why separate transport models from domain models?

Short answer: A transport model follows an external API schema, while a domain model represents what the application means and needs. Mapping between them contains external naming, optional fields, and validation at one boundary. This costs some extra code but prevents routine API changes from spreading through business logic and screens.

Detailed explanation:

DTOs follow external schemas; domain models follow application meaning. Separation prevents API changes and transport concerns from spreading through business and UI code.

🟦 Illustrative example:

SWIFT
struct UserDTO: Decodable {
    let user_id: String
    let display_name: String?
}
struct User {
    let id: String
    let displayName: String
}
func domainUser(from dto: UserDTO) -> User {
    User(id: dto.user_id, displayName: dto.display_name ?? "Unnamed user")
}

🧠 The adapter contains transport spelling and the explicit missing-name policy. This extra mapping costs code but stops a wire-schema rename from forcing changes throughout UI and business logic.

What does TLS pinning add to normal server trust checks?

Short answer: Pinning adds an app-controlled certificate or public-key requirement after normal TLS trust checks succeed. This narrows which server identities the app accepts and can resist some interception attacks. It also creates operational risk: rotation and recovery must be planned so a legitimate server change does not lock users out.

Detailed explanation:

It adds an application-controlled certificate or public-key check on top of normal TLS trust evaluation. It improves resistance to certain interception attacks but requires careful rotation and backup-pin planning.

TLS trust and the extra pin requirement

TLS — Transport Layer Security protects data in transit and authenticates the server. “SSL pinning” is a common historical name; modern mobile connections use TLS, not the obsolete SSL protocol. Normal server authentication checks the certificate chain, signatures, validity, and hostname under platform policy. Encryption alone does not establish that the peer is your intended server. ATS adds platform transport requirements; keep those enabled. See Apple's network connection security overview.

Pinning narrows the acceptable identities further. A connection must pass normal platform trust and match an app-controlled pin. A matching pin cannot rescue an expired certificate, wrong hostname, or untrusted chain. Conversely, a normally trusted certificate with an unexpected pinned identity is rejected. For example, a catalog app connecting to its own API can reject a substituted identity even when a device trusts an interception proxy's CA. That same restriction can break legitimate managed-network access; choose it for an explicit threat model and an endpoint you can operate through rotations.

Normal trust, including hostnamePin matchResult
PassYesEligible to connect; HTTP/application checks still apply
PassNoReject
FailYesReject
FailNoReject

Apple says most apps can rely on default trust and should deploy pinning cautiously. It is not a substitute for user authentication, authorization, safe token storage, or protection against a compromised/instrumented app. See Apple's identity-pinning guidance.

🟦 Original illustrative policy:

YAML
tls_policy:
  platform_certificate_validation: required
  additional_pin_check: required
  pins:
    - current_public_key_hash
    - independently_provisioned_backup_key_hash
  on_pin_mismatch: reject_connection
  rotation_check: exercise_backup_before_retiring_current_key

🧠 This is an illustrative policy contract, not executable TLS configuration or real key material. The pin check supplements hostname/chain validation and needs a tested backup/rotation strategy; bypassing platform trust after a pin mismatch destroys the intended protection.

Pin choices · ATS configuration · Derive pins · Swift client · Decision checks · Rotation and recovery

Certificate identity and public-key identity have different lifetimes

PinCompared materialChange behavior and tradeoff
Whole leaf certificateExact DER certificate bytes, or a digest of those bytesNarrow and straightforward; renewal changes the certificate even if its key stays the same
Leaf SPKIDigest of the leaf's DER SubjectPublicKeyInfo structureSurvives renewal with the same key; a new key still needs a preprovisioned pin
CA SPKIDigest of a chosen intermediate/root CA's SPKI in the chainAllows more leaf-key changes under that CA, but trusts a broader issuance scope; chain/CA changes still matter

SPKI contains the public key and its algorithm information. It is not the entire certificate and is not necessarily the bytes returned by a raw key-export API. A certificate DER digest and an SPKI digest are not interchangeable. Public certificates/pins are not private keys and do not need secrecy; their provisioning needs authenticity. Apple's leaf-identity key and CA-identity key define these encodings.

Prefer declarative ATS identity pinning when it fits

For URL Loading System traffic on iOS/iPadOS 14+, NSPinnedDomains lets the platform enforce a domain's identity pins. This often avoids custom trust-delegate code. The following is a complete plist-shaped template, to merge into the app's existing Info.plist, not a replacement for unrelated app settings. Replace api.example.com and both placeholder strings with owner-verified values before use. The placeholders are deliberately not usable pins; build/release validation must reject them rather than relying on malformed configuration to block traffic. See NSPinnedDomains availability and structure.

XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSPinnedDomains</key>
        <dict>
            <key>api.example.com</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <false/>
                <key>NSPinnedLeafIdentities</key>
                <array>
                    <dict>
                        <key>SPKI-SHA256-BASE64</key>
                        <string>REPLACE_WITH_CURRENT_LEAF_SPKI_BASE64</string>
                    </dict>
                    <dict>
                        <key>SPKI-SHA256-BASE64</key>
                        <string>REPLACE_WITH_INDEPENDENT_BACKUP_SPKI_BASE64</string>
                    </dict>
                </array>
            </dict>
        </dict>
    </dict>
</dict>
</plist>

Within NSPinnedLeafIdentities, current or backup may match. If you also configure NSPinnedCAIdentities, a CA match and a leaf match are required; the categories are not alternatives. NSIncludesSubdomains = false keeps this example exact-domain. Apple's true behavior covers one additional DNS label, not arbitrary recursive depth; explicitly configure other API hosts. These pins tighten default trust and do not install a new trust anchor. See leaf matching and subdomain scope.

Provision pins from owner-verified public certificates

Obtain the current and independently controlled backup public certificates through your server/security team's authenticated process, and verify which host/key each represents. Do not establish trust by downloading whatever an unverified connection happens to present. The following local Bash commands assume those approved PEM certificate files already exist. They produce ATS SPKI digests, then DER files for the separate manual example. They do not contact a server or read private keys.

BASH
set -euo pipefail
for certificate in api-current.pem api-backup.pem; do
    printf '%s: ' "$certificate"
    openssl x509 -in "$certificate" -pubkey -noout |
        openssl pkey -pubin -outform DER |
        openssl dgst -sha256 -binary |
        openssl base64 -A
    printf '\n'
done
openssl x509 -in api-current.pem -outform DER -out api-current.der
openssl x509 -in api-backup.pem -outform DER -out api-backup.der

Each ATS value must decode as a 32-byte SHA-256 digest. Cross-check the output independently against approved certificate/key records and validate the built app's actual plist, target membership, and release configuration. Distinct certificates do not prove independent keys: compare their SPKI identities too. Apple documents the SPKI calculation pipeline. Never place a private-key PEM in the app bundle.

A bounded certificate-DER URLSession client

This alternative demonstrates whole leaf-certificate pinning, not the ATS SPKI scheme. Prefer one clearly owned production strategy; installing both creates intersecting requirements that must be tested together. Assumptions: Swift 6 with nonisolated default isolation, iOS 15+ for SecTrustCopyCertificateChain, and the Security/Foundation SDK. Replace api.example.com in the client and usage URL with your owned exact host. The approved public api-current.der and api-backup.der resources must belong to the app target. The example is illustrative and requires app integration and TLS validation before production use. No live TLS testing is reported for these notes; compilation alone would not establish that the security policy works.

The delegate keeps immutable, sendable configuration, rejects missing/malformed/duplicate required resources during initialization, and checks the unchanged URLSession-provided trust before comparing the leaf. That preserves the session's SSL/hostname policies; do not replace them with a generic X.509 policy, trust exceptions, custom anchors, or an unconditional .useCredential. Manual server trust authentication explains the callback; SecTrustEvaluateWithError may fetch certificates/revocation information, so evaluation must stay off the main run loop.

SWIFT
import Foundation
import Security
​
private enum PinnedEndpoint {
    static let host = "api.example.com"
    static func allows(_ url: URL?) -> Bool {
        guard let url else { return false }
        return url.scheme?.lowercased() == "https"
            && url.host?.lowercased() == host
            && (url.port == nil || url.port == 443)
            && url.user == nil && url.password == nil
    }
}
enum PinConfigurationError: Error {
    case missingCertificate(String), invalidCertificate(String), duplicatePins
}
@available(iOS 15.0, *)
private final class CertificatePinDelegate: NSObject, URLSessionTaskDelegate {
    private let certificates: Set<Data>
    init(bundle: Bundle) throws {
        let names = ["api-current", "api-backup"]
        let loaded = try names.map { name -> Data in
            guard let url = bundle.url(forResource: name, withExtension: "der") else {
                throw PinConfigurationError.missingCertificate(name)
            }
            let data = try Data(contentsOf: url)
            guard SecCertificateCreateWithData(nil, data as CFData) != nil else {
                throw PinConfigurationError.invalidCertificate(name)
            }
            return data
        }
        guard Set(loaded).count == names.count else {
            throw PinConfigurationError.duplicatePins
        }
        certificates = Set(loaded)
        super.init()
    }
    func urlSession(_ session: URLSession,
                    didReceive challenge: URLAuthenticationChallenge,
                    completionHandler: @escaping @Sendable
                    (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        let space = challenge.protectionSpace
        guard space.authenticationMethod == NSURLAuthenticationMethodServerTrust else {
            completionHandler(.performDefaultHandling, nil)
            return
        }
        guard space.host.lowercased() == PinnedEndpoint.host, space.port == 443,
              let trust = space.serverTrust,
              SecTrustEvaluateWithError(trust, nil),
              let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate],
              let leaf = chain.first,
              certificates.contains(SecCertificateCopyData(leaf) as Data) else {
            completionHandler(.cancelAuthenticationChallenge, nil)
            return
        }
        completionHandler(.useCredential, URLCredential(trust: trust))
    }
    func urlSession(_ session: URLSession, task: URLSessionTask,
                    willPerformHTTPRedirection response: HTTPURLResponse,
                    newRequest request: URLRequest,
                    completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
        guard PinnedEndpoint.allows(request.url) else {
            task.cancel()
            completionHandler(nil)
            return
        }
        completionHandler(request)
    }
}
@available(iOS 15.0, *)
final class PinnedAPIClient: Sendable {
    private let session: URLSession
    init(bundle: Bundle = .main) throws {
        let delegate = try CertificatePinDelegate(bundle: bundle)
        let queue = OperationQueue()
        queue.maxConcurrentOperationCount = 1
        queue.qualityOfService = .utility
        let configuration = URLSessionConfiguration.ephemeral
        configuration.urlCache = nil
        session = URLSession(configuration: configuration,
                             delegate: delegate, delegateQueue: queue)
    }
    func data(from url: URL) async throws -> Data {
        guard PinnedEndpoint.allows(url) else { throw URLError(.unsupportedURL) }
        try Task.checkCancellation()
        let (data, response) = try await session.data(from: url)
        try Task.checkCancellation()
        guard let http = response as? HTTPURLResponse,
              (200..<300).contains(http.statusCode),
              PinnedEndpoint.allows(http.url) else { throw URLError(.badServerResponse) }
        return data
    }
    func close() { session.invalidateAndCancel() }
}

Boundaries: the private ephemeral session handles only HTTPS, the exact host, and default/443 port. Neither .contains("example.com") nor a suffix test is a host allowlist. The entry point checks the initial URL, and the task delegate refuses HTTP/cross-host/other-port redirects. A refused redirect is not a successful catalog response; cancellation or a non-2xx result is an error. Background sessions have different redirect behavior and are outside this example. See redirect handling.

Ownership: append this usage example to the client block. It owns one finite operation and explicitly invalidates the session on every exit; production owners can reuse a client for their lifecycle, then close it at shutdown. Cancellation of URLSession's async methods is supported; do not suppress cancellation and display old results as new data. The session retains its delegate until invalidation. See session/delegate lifetime and URLSession async cancellation.

SWIFT
@available(iOS 15.0, *)
func loadCatalogOnce(bundle: Bundle = .main) async throws -> Data {
    let client = try PinnedAPIClient(bundle: bundle)
    defer { client.close() }
    guard let url = URL(string: "https://api.example.com/catalog") else {
        throw URLError(.badURL)
    }
    return try await client.data(from: url)
}

The backup is accepted only when its certificate also passes normal trust. No pin resources means initialization throws, not an unpinned request. Keep delegate methods nonisolated if an app enables MainActor-by-default isolation; do not silence isolation errors with unsafe Sendable. Pin decisions occur during connection authentication, not necessarily on every request over a reused connection. Configuration changes require a new appropriately configured session; a mutable pin array is not a reliable rotation mechanism. Third-party networking stacks need their own verified enforcement path.

Pure decision checks complement actual TLS tests

This independent Swift block checks the AND rule only. Its booleans stand for externally established facts; it does not parse certificates, evaluate trust, validate plist behavior, or prove the delegate works.

SWIFT
struct PinCase {
    let normalTrust: Bool
    let pinMatches: Bool
    let expected: Bool
}
func acceptsPinnedIdentity(normalTrust: Bool, pinMatches: Bool) -> Bool {
    normalTrust && pinMatches
}
func pinDecisionEvidence() -> Bool {
    let cases = [
        PinCase(normalTrust: true, pinMatches: true, expected: true),
        PinCase(normalTrust: true, pinMatches: false, expected: false),
        PinCase(normalTrust: false, pinMatches: true, expected: false),
        PinCase(normalTrust: false, pinMatches: false, expected: false)
    ]
    return cases.allSatisfy {
        acceptsPinnedIdentity(normalTrust: $0.normalTrust,
                              pinMatches: $0.pinMatches) == $0.expected
    }
}

Expected result is true. A real acceptance plan must exercise owner-controlled TLS endpoints and release builds on supported OS versions, including both current and backup credentials. The following YAML is a test specification, not an executable runner or evidence of completed tests:

YAML
pin_acceptance:
  valid_current_identity: connect
  valid_backup_identity: connect
  trusted_chain_with_unlisted_identity: reject
  expired_or_wrong_host_even_if_pinned: reject
  missing_or_malformed_required_DER_resource: initialization_error
  http_initial_URL: reject_before_request
  cross_host_or_http_redirect: reject
  same_host_https_redirect_with_valid_identity: eligible
  cancellation_during_request: stop_without_success_UI
  renewed_certificate_same_key:
    ATS_leaf_SPKI: remains_eligible_if_normal_trust_passes
    exact_leaf_DER: reject_unless_new_certificate_preprovisioned

Also check deceptive hosts such as api.example.com.attacker.test, non-443 ports, backup target membership, placeholder-free built plist, failure UI, and adapter/stack coverage. A custom URLProtocol mock can test response flow but does not perform a genuine TLS handshake; don't treat it as pin-verification evidence. Keep trust/pin failures distinct from HTTP 401/5xx responses and user cancellation in your error handling. Do not promise one URLError code for a pin rejection: challenge cancellation and platform TLS failures can surface differently across paths/OS versions. Record sanitized failure categories without logging tokens, private key material, or entire sensitive responses.

Rotation and recovery are part of the design

StageApp/server actionAcceptance before moving on
PrepareProvision current A and independent backup B; assign operational ownersApproved key/cert records, validity windows, domains and hash format agree
PredeployRelease apps accepting A or B while server still uses ARelease-build tests accept both; installed versions and update constraints are understood
RotateSwitch the owned server to B after the client overlap plan is satisfiedSupported old/new versions connect; mismatch telemetry/failure UI are checked
Renew overlapShip B plus future independent C before retiring A coverageRenewed DER certificates are separately included when using exact-certificate pins
RecoverUse a previously trusted compatible server identity when safe, or deliver an authenticated app updateNo downgrade to HTTP, default-trust-only fallback, or “accept all” switch

There is no universal safe adoption percentage or overlap duration: derive it from your supported-client policy, forced-update capabilities, certificate expirations, and server rollback constraints. A configuration fetch available only through the already-broken pinned channel cannot repair that channel. Do not fetch replacement pins from an unauthenticated alternate endpoint. If no safe identity works, fail closed and provide a useful offline/retry/update experience; a retry alone cannot repair an identity mismatch. Apple describes planning for credential change and recovery.

🧠 Interview explanation: TLS establishes platform trust; pinning adds a narrower app identity rule. Choose certificate, leaf-SPKI, or CA-SPKI scope deliberately, enforce host boundaries, and explain how users survive renewal, key rotation, and emergency recovery. A pin that cannot be rotated safely is an availability defect waiting for a server change.

Protocol interview deep dive

Which protocol form should an API expose?

Short answer: A protocol states a contract, but different API forms preserve different type information. A generic retains a concrete type relationship; an opaque result hides one fixed implementation; an existential stores a conforming value while hiding its concrete type. Choose according to the relationships and runtime replacement the caller actually needs.

Detailed explanation:

FormWhat the compiler knowsStrong use caseMain tradeoff
P in a conformanceA concrete type promises P's requirementsAdding a capability to a typeThe conformance must satisfy the complete contract
T: PThe concrete T stays known and related across the APIReusable algorithms and compile-time specializationCan make public signatures more complex
some POne fixed concrete type is hidden from the callerReturning implementation detail, especially SwiftUI viewsEvery return path must resolve to the same underlying type
any PThe value conforms to P, but its concrete type is erasedStored dependencies and heterogeneous collectionsErases type relationships and can add indirection

🧠 A protocol is the contract. T: P, some P, and any P are different ways to use that contract; they are not interchangeable spellings.

🟦 Illustrative example:

SWIFT
protocol Labelled { var label: String { get } }
struct AccountLabel: Labelled { let label: String }
func retainType<T: Labelled>(_ value: T) -> T { value }
func makeLabel() -> some Labelled { AccountLabel(label: "Account") }
let stored: any Labelled = AccountLabel(label: "Stored")
let exact: AccountLabel = retainType(AccountLabel(label: "Exact"))

🧠 The generic preserves the input/output concrete-type relationship, the opaque result hides one fixed implementation, and the existential supports erased storage. Pick the relationship callers need rather than treating the spellings as interchangeable.

When should you prefer a generic to an existential?

Short answer: Prefer a generic when the operation needs to preserve a concrete type relationship, such as returning the same kind of value it receives. An existential is useful when simple storage or choosing an implementation at runtime matters more. These choices express different API contracts rather than a universal performance ranking.

Detailed explanation:

Choose a generic when the concrete type relationship matters to the operation. The compiler retains associated-type information and can specialize the implementation. Choose an existential when runtime substitution and simple storage matter more than preserving the exact concrete type.

The practical question is which type relationships the consumer needs. A generic parameter names one type for an operation/type instantiation; any P stores an implementation selected at runtime, exposing the protocol's available interface. A constrained existential can retain a particular associated output while hiding the provider. some P is different again: in a result position, the implementation chooses an underlying type rather than an arbitrary caller-selected one. See Swift's generics and opaque/boxed types chapters.

🟨 Copying and scope: illustrative Swift 6 examples, with nonisolated default isolation; the constrained-existential/SwiftUI examples target iOS 16+ or macOS 13+. Each block is independent except the explicitly marked invalid pipeline call, which uses its preceding setup. Repeated names are deliberate. Data is local and deterministic: no network, database, or image SDK is being simulated as a real integration. Expected results describe behavior to verify; no UI/performance measurements are claimed.

Same-type return · Typed pipeline · Runtime injection · Constrained existential · Implicit opening · Concurrent loading · SwiftUI boundary · Selection guide

A generic preserves the input's concrete result type

Trigger: an order-draft editor renames several kinds of draft. Its reusable operation must return the same concrete kind it received, so the caller can still use order-specific fields. D connects the input and result; independently writing any DraftEditing at both ends does not express that static relationship.

SWIFT
protocol DraftEditing {
    func renamed(to title: String) -> Self
}
struct OrderDraft: DraftEditing {
    let id: String
    let title: String
    let itemCount: Int
    func renamed(to title: String) -> OrderDraft {
        OrderDraft(id: id, title: title, itemCount: itemCount)
    }
}
func rename<D: DraftEditing>(_ draft: D, to title: String) -> D {
    draft.renamed(to: title)
}
func erasedRename(_ draft: any DraftEditing, to title: String) -> any DraftEditing {
    draft.renamed(to: title)
}
func sameTypeEvidence() -> Bool {
    let original = OrderDraft(id: "draft-1", title: "Old", itemCount: 3)
    let updated: OrderDraft = rename(original, to: "Weekend order")
    return updated.title == "Weekend order" && updated.itemCount == 3
}

Expected: sameTypeEvidence() returns true; updated.itemCount remains statically available. erasedRename can perform the operation too, but its returned existential does not directly provide OrderDraft.itemCount; assigning it to OrderDraft requires recovering/checking that type. The compiler preserves type identity here, not business invariants: retaining the draft ID/items is the conformer's behavior and needs tests. Avoid a generic when consumers genuinely need only the erased interface.

Associated outputs connect decoding to compatible persistence

Trigger: a catalog refresh decodes a wire DTO, maps it into domain products, and saves that exact model shape. The import helper should reject a store for the wrong model before the app runs. R.Model == S.Model relates two different provider types; it does not require reader and store themselves to have the same type.

SWIFT
import Foundation
​
struct Product: Equatable { let id: String; let title: String }
struct ProductDTO: Decodable { let sku: String; let name: String }
protocol CatalogReading {
    associatedtype Model
    func read() throws -> Model
}
protocol ModelSaving {
    associatedtype Model
    mutating func save(_ model: Model)
}
struct JSONCatalogReader: CatalogReading {
    let data: Data
    func read() throws -> [Product] {
        try JSONDecoder().decode([ProductDTO].self, from: data)
            .map { Product(id: $0.sku, title: $0.name) }
    }
}
struct MemoryStore<Model>: ModelSaving {
    private(set) var value: Model?
    mutating func save(_ model: Model) { value = model }
}
func readAndSave<R: CatalogReading, S: ModelSaving>(
    _ reader: R, into store: inout S
) throws -> R.Model where R.Model == S.Model {
    let model = try reader.read()
    store.save(model)
    return model
}
func catalogImportEvidence() throws -> Bool {
    let data = Data(#"[{"sku":"mug","name":"Travel mug"}]"#.utf8)
    var store = MemoryStore<[Product]>()
    let products = try readAndSave(JSONCatalogReader(data: data), into: &store)
    return products == [Product(id: "mug", title: "Travel mug")]
        && store.value == products
}

Expected: catalogImportEvidence() returns true. The wire field sku becomes domain id, and both returned/saved values are [Product]. Malformed JSON throws before saving; test that a preexisting store value remains intact. This memory store is not durable persistence, and model compatibility alone does not guarantee transactional writes or valid business data.

🟥 Deliberate compile-time failure — append only to the preceding setup: the reader produces [Product], while the store accepts String.

SWIFT
func invalidCatalogImport() throws {
    let reader = JSONCatalogReader(data: Data("[]".utf8))
    var wrongStore = MemoryStore<String>()
    _ = try readAndSave(reader, into: &wrongStore)
}

The compiler rejects the incompatible same-type requirement; diagnostic wording depends on the toolchain. 🟩 Use MemoryStore<[Product]> as in the working block, or introduce an explicit, meaningful transformation before storing a different model. Casting to Any merely moves this mismatch to runtime. Same-type requirements are documented in Swift Generics.

An existential makes runtime selection and injection straightforward

Trigger: the catalog screen uses a bundled source normally and a fixed source in previews/tests. It only needs [String], not provider-specific types or an associated-type relationship. A stored any CatalogTitles lets composition select either implementation while keeping the screen's type unchanged.

SWIFT
protocol CatalogTitles { func titles() -> [String] }
struct BundledCatalog: CatalogTitles {
    func titles() -> [String] { ["Travel mug", "Notebook"] }
}
struct PreviewCatalog: CatalogTitles {
    let values: [String]
    func titles() -> [String] { values }
}
func makeCatalog(preview: Bool) -> any CatalogTitles {
    if preview { return PreviewCatalog(values: ["Preview mug"]) }
    return BundledCatalog()
}
@MainActor
final class CatalogModel {
    private let catalog: any CatalogTitles
    private(set) var rows: [String] = []
    init(catalog: any CatalogTitles) { self.catalog = catalog }
    func refresh() { rows = catalog.titles() }
}
@MainActor
func injectedCatalogEvidence() -> Bool {
    let model = CatalogModel(catalog: PreviewCatalog(values: ["Test mug"]))
    model.refresh()
    return model.rows == ["Test mug"]
}

Expected: the evidence returns true; selecting preview composition yields "Preview mug" instead of the bundled list. Existential storage hides the catalog's implementation type, not every result type: the declared [String] output stays known. A generic CatalogModel<Source> could also accept stubs, so testability alone does not require any. Prefer the existential here when avoiding propagation of a provider type through UI/coordinator declarations is useful.

A constrained existential retains the model while erasing the provider

Trigger: runtime-selected catalog readers must all return [Product]. Keeping the provider generic everywhere is unnecessary, while unconstrained any CatalogReading would hide the associated model. A primary associated type names Model; any CatalogReading<[Product]> constrains it to [Product].

SWIFT
struct Product { let title: String }
protocol CatalogReading<Model> {
    associatedtype Model
    func read() -> Model
}
struct BundledReader: CatalogReading {
    func read() -> [Product] { [Product(title: "Travel mug")] }
}
struct PreviewReader: CatalogReading {
    func read() -> [Product] { [Product(title: "Preview mug")] }
}
func selectReader(preview: Bool) -> any CatalogReading<[Product]> {
    if preview { return PreviewReader() }
    return BundledReader()
}
func constrainedReaderEvidence(preview: Bool) -> [String] {
    let reader: any CatalogReading<[Product]> = selectReader(preview: preview)
    let products: [Product] = reader.read()
    return products.map { $0.title }
}

Expected: false produces ["Travel mug"]; true produces ["Preview mug"]. Both providers can inhabit that existential, but one returning [String] cannot. Model remains an associated type, not an ordinary generic parameter declaring a separate protocol per model. This preserves a useful output equality while erasing the reader's concrete identity; it does not establish that two such readers have the same provider type. See SE-0346 and SE-0353. Check deployment/runtime support when adopting this syntax in older targets.

Implicit opening allows many existential-to-generic calls

🟨 “An existential can never be passed to a generic function” is incorrect. Swift can implicitly open a suitable existential argument and bind the generic parameter to that value's hidden underlying type for the call. It does not infer that two independently boxed values share one concrete type. SE-0352 defines the rules and restrictions.

SWIFT
protocol RowDescribing { var summary: String { get } }
struct ProductRow: RowDescribing { let summary: String }
struct LoadingRow: RowDescribing { let summary = "Loading" }
func render<R: RowDescribing>(_ row: R) -> String { row.summary }
func sameSummaryWithinType<R: RowDescribing>(_ first: R, _ second: R) -> Bool {
    first.summary == second.summary
}
func openingEvidence() -> [String] {
    let rows: [any RowDescribing] = [
        ProductRow(summary: "Travel mug"), LoadingRow()
    ]
    return rows.map { render($0) }
}

Expected: openingEvidence() returns ["Travel mug", "Loading"]; each element is opened for its own render call. Calling sameSummaryWithinType(a, b) with two independent any RowDescribing values cannot generally satisfy one shared R, even if both happen to hold ProductRow at runtime. Move work requiring a single hidden type inside an appropriate generic boundary; if only summaries matter, compare the known strings without inventing a same-type requirement. Opening is local and is not general existential self-conformance or unrestricted escape of a hidden type into stored generic containers.

The original concurrent loader needs a Sendable contract

Trigger: an image pipeline loads two outputs concurrently and returns a pair with one known image representation. Keep the original ImageLoading/loadTwice idea, but a bare protocol does not promise that sharing its loader and returning results across child tasks is safe. This version explicitly requires both to be Sendable and uses local byte values instead of a UI image object.

SWIFT
protocol ImageLoading<Image>: Sendable {
    associatedtype Image: Sendable
    func load() async throws -> Image
}
func loadTwice<Loader: ImageLoading>(
    with loader: Loader
) async throws -> (Loader.Image, Loader.Image) {
    try Task.checkCancellation()
    async let first = loader.load()
    async let second = loader.load()
    let pair = try await (first, second)
    try Task.checkCancellation()
    return pair
}
struct ImageBytes: Sendable, Equatable { let bytes: [UInt8] }
struct LocalImageLoader: ImageLoading {
    let image: ImageBytes
    func load() async throws -> ImageBytes {
        try Task.checkCancellation()
        return image
    }
}
func imagePairEvidence() async throws -> Bool {
    let image = ImageBytes(bytes: [1, 2, 3])
    let pair = try await loadTwice(with: LocalImageLoader(image: image))
    return pair.0 == image && pair.1 == image
}

The generic signature guarantees that both results have the same Loader.Image type. A plain, unconstrained existential hides that associated relationship; a constrained existential can retain a specified output as shown earlier. Expected: this local evidence returns true. Cancellation/error can exit by throwing; scoped child tasks finish or cooperate with cancellation before their scope exits. Do not swallow those errors or assume simultaneous CPU execution. Sendable is a safety promise, not a scheduling guarantee. An actor-backed provider may serialize its work; a UI-isolated non-Sendable image representation needs a different boundary, not @unchecked Sendable. See SE-0317 async let and SE-0302 Sendable.

SwiftUI combines generic input with an opaque result

Trigger: a reusable catalog card accepts different content views. Its Content parameter preserves the supplied view type, while body: some View hides its composed return type from the caller. The two boundaries serve different directions of choice.

SWIFT
import SwiftUI
​
@MainActor
struct CatalogCard<Content: View>: View {
    let title: String
    private let content: Content
    init(title: String, @ViewBuilder content: () -> Content) {
        self.title = title
        self.content = content()
    }
    var body: some View {
        VStack(alignment: .leading) {
            Text(title).font(.headline)
            content
        }
        .padding()
    }
}
@MainActor
struct CatalogPreview: View {
    var body: some View {
        CatalogCard(title: "Catalog") { Text("Travel mug") }
    }
}

Expected UI content is a Catalog heading and Travel mug text inside the padded card. some View is one implementation-chosen underlying result type per declaration/generic substitutions; it cannot directly stand for arbitrary runtime conformers. Result builders can encode conditional branches in a single composed type. An opaque parameter such as some P is instead unnamed generic input; two independently written some P parameters do not mean the same type. See Swift opaque types and SwiftUI.View.

Choose the required relationship before tuning performance

NeedGood starting point
Input and result retain the same concrete typeA named generic T
Reader output must equal store inputGenerics with a same-type where requirement
Store interchangeable providers behind one dependencyany P
Select provider at runtime but keep a known modelany P<Model> with a primary associated type
Hide one implementation-chosen return typesome P result

Specialization/inlining can remove generic overhead when sufficient information is available; an unspecialized generic can still use metadata/witness-table operations. Existentials may add indirection, dispatch or storage costs, but every any value does not necessarily allocate on the heap or run slower. Measure representative optimized app work, code size and build costs before redesigning boundaries for speed. Apple's Explore Swift performance explains these mechanisms.

🧠 Interview explanation: choose generics to state relationships the compiler must preserve; use existentials for useful runtime abstraction, optionally retaining a known associated output. Explain the real consumer requirement first, then concurrency/isolation and measured tradeoffs. Neither spelling makes a dependency correct, testable, or faster by itself.

When is an existential useful for a stored dependency?

Short answer: Use an existential when a consumer needs a protocol's declared capability but does not need to know the service's concrete type. The application can then choose a real service or a test replacement at composition time. Hiding that type does not itself decide ownership, execution context, or thread safety.

Detailed explanation:

Use it when a consumer needs only the protocol requirements and the implementation may be selected at runtime. A small dependency protocol can make ownership and test substitution explicit without exposing the concrete service.

A stored existential is useful when a screen/action needs a stable capability, while composition chooses its implementation. It hides the service's concrete type; it does not hide declared outputs such as User, choose an executor, or make access thread-safe. See Swift's boxed protocol types.

🟨 Example scope: illustrative Swift 6 with nonisolated default isolation, iOS 16+/macOS 13+ targets. The first block supplies shared User/repository definitions for the next three: the broken model, corrected model, and deterministic test. Copy blocks 1 + 3 + 4 for the working profile example; block 2 is the bug demonstration. The final two blocks are independent. All providers are local fixtures/snapshots; no HTTP server, durable database, or live integration is claimed. These state holders omit observation/UI bindings to keep the dependency contract visible.

Composition · Stale-result bug · Owned profile loading · Deterministic tests · Mixed rules · UI capability · Tradeoffs

Composition selects a provider before the screen uses it

Trigger: the same profile screen needs approved preview records or an offline snapshot. The composition root selects a repository and injects it, rather than making the screen inspect a global mode/singleton. Its contract returns the requested user's ID or throws; a missing record does not become a fabricated empty user.

SWIFT
import Foundation
​
struct User: Sendable, Equatable { let id: UUID; let name: String }
enum UserLookupError: Error { case notFound, wrongIdentity }
protocol UserRepository: Sendable {
    func user(id: UUID) async throws -> User
}
struct PreviewUserRepository: UserRepository {
    let users: [UUID: User]
    func user(id: UUID) async throws -> User {
        try Task.checkCancellation()
        guard let user = users[id] else { throw UserLookupError.notFound }
        guard user.id == id else { throw UserLookupError.wrongIdentity }
        return user
    }
}
actor OfflineUserRepository: UserRepository {
    private var users: [UUID: User]
    init(users: [UUID: User]) { self.users = users }
    func user(id: UUID) async throws -> User {
        try Task.checkCancellation()
        guard let user = users[id] else { throw UserLookupError.notFound }
        guard user.id == id else { throw UserLookupError.wrongIdentity }
        return user
    }
    func update(_ user: User) { users[user.id] = user }
}
enum ProfileSource { case preview, offline }
func makeUserRepository(source: ProfileSource, users: [UUID: User]) -> any UserRepository {
    switch source {
    case .preview: return PreviewUserRepository(users: users)
    case .offline: return OfflineUserRepository(users: users)
    }
}

Both implementations fulfill one consumer-facing capability. The actor owns its mutable snapshot; the preview holds immutable value data. A real HTTP adapter would separately own request scope, TLS, status handling, DTO mapping and error/cancellation normalization; a local fixture does not establish that adapter's correctness. Sendable explicitly covers the repository crossing isolation boundaries and User being returned. It does not guarantee background execution: async isolation depends on the API and language settings. See Sendable and async isolation.

MainActor alone does not preserve the latest selection

🟥 Bug — uses block 1: the user selects A, then B. B completes first, but the slower A response overwrites it. There is no simultaneous state access here; this is an ordering bug across suspension points, not evidence that any causes a data race.

SWIFT
@MainActor
final class NaiveProfileModel {
    private let repository: any UserRepository
    private(set) var user: User?
    init(repository: any UserRepository) { self.repository = repository }
    func load(id: UUID) async throws {
        user = try await repository.user(id: id)
    }
}

The repository binding is immutable, but two calls can still be outstanding. Main-actor work can interleave while a call awaits; callers cannot assume completion order matches selection order. The same bug could occur with a concrete or generic dependency. See actor reentrancy.

Own cancellation and guard every publication

🟩 Corrected model — uses block 1: each selection creates a new request token, cancels previous work, clears the previous user's display, and owns its task. Token checks protect both success and failure/loading cleanup. Cancellation requests resource cleanup; token identity determines which result still belongs to the UI.

SWIFT
@MainActor
final class ProfileModel {
    private let repository: any UserRepository
    private var request: UUID?
    private var loadTask: Task<Void, Never>?
    private(set) var user: User?
    private(set) var isLoading = false
    private(set) var errorMessage: String?
    init(repository: any UserRepository) { self.repository = repository }
​
    @discardableResult
    func select(id: UUID) -> Task<Void, Never> {
        loadTask?.cancel()
        let token = UUID()
        request = token
        user = nil
        errorMessage = nil
        isLoading = true
        let repository = self.repository
        let task = Task { [weak self] in
            do {
                try Task.checkCancellation()
                let loaded = try await repository.user(id: id)
                try Task.checkCancellation()
                guard loaded.id == id else { throw UserLookupError.wrongIdentity }
                guard let self, self.request == token else { return }
                self.user = loaded
                self.isLoading = false
                self.loadTask = nil
            } catch {
                guard let self, self.request == token else { return }
                self.isLoading = false
                self.loadTask = nil
                if !Task.isCancelled && !(error is CancellationError) {
                    self.errorMessage = "Could not load profile"
                }
            }
        }
        loadTask = task
        return task
    }
    func cancel() {
        request = nil
        loadTask?.cancel()
        loadTask = nil
        user = nil
        isLoading = false
        errorMessage = nil
    }
}
@MainActor
func makeProfileModel(source: ProfileSource, users: [UUID: User]) -> ProfileModel {
    ProfileModel(repository: makeUserRepository(source: source, users: users))
}

Expected: B remains visible after late A success or failure; a current lookup failure clears loading and displays the error state. A fresh token also distinguishes A→B→A requests; checking only the selected user's ID would not. An old request must never clear B's spinner or replace B's error/success. Avoid an unguarded defer { isLoading = false } spanning these overlapping requests.

The task inherits MainActor isolation for UI state changes. It captures the repository separately and only promotes weak self after awaiting, so long work does not require retaining the model. The screen/coordinator must call cancel() at its lifecycle boundary; dropping a task handle or model is not a cancellation policy. Cancellation is cooperative, and a provider may finish despite it. See Task.cancel. The generic message is display copy; retain sanitized diagnostic context through the app's error reporting rather than converting failures into success/empty data.

A controlled repository proves out-of-order behavior without sleeps

Test fixture — uses blocks 1 + 3: this actor intentionally ignores cancellation while suspended so the test can deliver an obsolete result. It allows one pending call per distinct ID and resumes every call in this bounded scenario; it is not a production repository or a general cancellation implementation.

SWIFT
actor ControlledUserRepository: UserRepository {
    private var pending: [UUID: CheckedContinuation<User, any Error>] = [:]
    private var observers: [UUID: CheckedContinuation<Void, Never>] = [:]
    func user(id: UUID) async throws -> User {
        try await withCheckedThrowingContinuation { continuation in
            pending[id] = continuation
            observers.removeValue(forKey: id)?.resume()
        }
    }
    func waitUntilRequested(_ id: UUID) async {
        if pending[id] != nil { return }
        await withCheckedContinuation { observers[id] = $0 }
    }
    func succeed(_ id: UUID, name: String) {
        pending.removeValue(forKey: id)?.resume(returning: User(id: id, name: name))
    }
    func fail(_ id: UUID) {
        pending.removeValue(forKey: id)?.resume(throwing: UserLookupError.notFound)
    }
}
@MainActor
func latestProfileEvidence(oldFails: Bool) async -> Bool {
    let oldID = UUID(), newID = UUID()
    let repository = ControlledUserRepository()
    let model = ProfileModel(repository: repository)
    let oldTask = model.select(id: oldID)
    await repository.waitUntilRequested(oldID)
    let newTask = model.select(id: newID)
    await repository.waitUntilRequested(newID)
    await repository.succeed(newID, name: "New selection")
    await newTask.value
    if oldFails { await repository.fail(oldID) }
    else { await repository.succeed(oldID, name: "Obsolete selection") }
    await oldTask.value
    return model.user == User(id: newID, name: "New selection")
        && !model.isLoading && model.errorMessage == nil
}

Expected: both latestProfileEvidence(oldFails: false) and true return true. The repository is injected as any UserRepository; no provider-specific logic enters the model. Also exercise current failure, explicit cancel followed by a late completion, wrong-ID responses, and preview/offline composition. Assert loading/error state as well as the displayed user. This proves consumer ordering, not network behavior; fixed delays or repeated Task.yield() calls would be weaker synchronization than the explicit request gates.

Heterogeneous rules share one declared output contract

Trigger: profile-name editing applies different pure rules in an explicit order. A [any NameRule] can hold a trim rule and validation rules with different concrete types because every step accepts and returns String.

SWIFT
import Foundation
​
enum NameError: Error, Equatable { case empty, tooLong }
protocol NameRule { func apply(_ name: String) throws -> String }
struct TrimName: NameRule {
    func apply(_ name: String) -> String {
        name.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}
struct RequireName: NameRule {
    func apply(_ name: String) throws -> String {
        guard !name.isEmpty else { throw NameError.empty }
        return name
    }
}
struct LimitName: NameRule {
    func apply(_ name: String) throws -> String {
        guard name.count <= 20 else { throw NameError.tooLong }
        return name
    }
}
func validatedName(_ input: String) throws -> String {
    let rules: [any NameRule] = [TrimName(), RequireName(), LimitName()]
    return try rules.reduce(input) { try $1.apply($0) }
}

Expected: " Çağrı " becomes "Çağrı"; whitespace-only input throws .empty, and 21 repeated ASCII characters throw .tooLong. The first thrown error stops the pipeline. Order is meaningful, and these rules are pure: a side-effecting pipeline would not automatically roll back completed effects or become safe to parallelize. See Swift's heterogeneous boxed collections.

A UI-only capability can stay on MainActor

A presenter can be stored behind a narrow UI protocol without making its methods callable from arbitrary executors. This independent example also shows that let fixes the binding, not a referenced object's mutable state.

SWIFT
@MainActor
protocol ProfilePresenting: AnyObject {
    func show(name: String)
}
@MainActor
final class RecordingPresenter: ProfilePresenting {
    private(set) var names: [String] = []
    func show(name: String) { names.append(name) }
}
@MainActor
struct GreetingAction {
    let presenter: any ProfilePresenting
    func complete(name: String) { presenter.show(name: name) }
}
@MainActor
func presenterEvidence() -> Bool {
    let recorder = RecordingPresenter()
    let action = GreetingAction(presenter: recorder)
    action.complete(name: "Çağrı")
    action.complete(name: "Ada")
    return recorder.names == ["Çağrı", "Ada"]
}

Expected: presenterEvidence() returns true; two calls mutate the same referenced recorder even though action.presenter is a let. That strong stored reference intentionally owns a presenter. any neither makes it weak nor prevents mutation. MainActor enforces the UI capability's access; the repository instead declares a Sendable service/result boundary. Adding Sendable would not remove UI actor isolation. See global actors.

Keep the abstraction proportional to the consumer

private let repository: any UserRepository does not mean implementations swap during an in-flight call. This model chooses once at construction. If product requirements demand replacing an account/environment, define ownership and cancellation explicitly, often by creating a new scoped model, rather than silently mutating a global dependency.

🟨 Do not add a protocol only because mocking is possible. Add one when there is a useful boundary, more than one implementation, external I/O, nondeterminism, or a dependency whose behavior the consumer should not own.

A concrete dependency is reasonable for a stable local helper. A generic consumer is appropriate when it must preserve provider/associated-type relationships. A constrained existential can keep a known output while selecting providers at runtime. Continue with the generic-versus-existential scenarios for those details and performance: existential storage does not imply universal heap allocation or guaranteed slowdown. Choose the useful contract first, then measure optimized app behavior when cost matters.

What does an associated type describe?

Short answer: An associated type names a type relationship within a protocol, and each conforming type chooses what that name means for its conformance. For example, a store can declare one value type that connects what it accepts when saving with what it returns when loading.

Detailed explanation:

An associated type is a placeholder chosen by each conforming type. It expresses a relationship among a protocol's requirements. It differs from a generic parameter because the conformer selects it for the conformance, not the caller for each function call.

For a settings store, Value connects what can be saved with what can be loaded. It is fixed for that conformance: SettingsStore.Value is Settings, not a choice that changes with the next call or an instance's fields. See Swift's associated types and associated-type declarations.

🟨 Scope and copying: illustrative Swift 6 with nonisolated default isolation; constrained-existential example targets iOS 16+/macOS 13+. Block 1 defines shared Settings/Store. Blocks 2, 3 and 4 use that setup. Block 5 uses blocks 1 + 3; its deliberately invalid follow-up, block 6, uses the same setup plus block 5. Block 7 is independent and redeclares its types. Examples use local actor-owned memory only, not durable disk or a real settings service. Expected round trips assume no competing writer; no integration/performance measurements are claimed.

Working store · Explicit witness · Generic conformer · Method-generic choice · Compatible pipeline · Known existential input · Storage limits

A real settings store connects save and load

Trigger: the user toggles dark mode and the feature reads its latest saved preferences. The original empty save/always-nil implementation would discard every change. This implementation actually replaces and reads an owned settings value. nil means no snapshot has been saved; cancellation throws rather than masquerading as absence.

SWIFT
import Foundation
​
struct Settings: Codable, Sendable, Equatable {
    var isDarkModeEnabled: Bool
}
protocol Store: Sendable {
    associatedtype Value: Sendable
    func save(_ value: Value) async throws
    func load() async throws -> Value?
}
actor SettingsStore: Store {
    private var stored: Settings?
    func save(_ value: Settings) async throws {
        try Task.checkCancellation()
        stored = value
    }
    func load() async throws -> Settings? {
        try Task.checkCancellation()
        return stored
    }
}
func settingsRoundTripEvidence() async throws -> Bool {
    let store = SettingsStore()
    let initiallyEmpty = try await store.load() == nil
    let settings = Settings(isDarkModeEnabled: true)
    try await store.save(settings)
    let loaded = try await store.load()
    return initiallyEmpty && loaded == settings
}

Expected: the evidence returns true; a new store is empty and saving enabled dark mode makes it loadable. Swift infers Value == Settings from the consistently typed requirements. Writing save(Settings) and load() -> String? would not satisfy one shared Value; separate method signatures cannot silently choose different witnesses. The actor serializes its stored state, and Sendable covers transferred settings values; associated-type syntax alone provides neither guarantee.

An explicit typealias makes an adapter's witness visible

Trigger: an adapter serializes settings to an in-memory JSON record, so its internal storage is Data, while its public Value must remain Settings. typealias explicitly states that distinction. It names an existing type; it does not introduce a second settings type.

SWIFT
actor JSONSettingsStore: Store {
    typealias Value = Settings
    private var record: Data?
    func save(_ value: Value) async throws {
        try Task.checkCancellation()
        let encoded = try JSONEncoder().encode(value)
        try Task.checkCancellation()
        record = encoded
    }
    func load() async throws -> Value? {
        try Task.checkCancellation()
        guard let record else { return nil }
        return try JSONDecoder().decode(Value.self, from: record)
    }
}
func encodedSettingsEvidence() async throws -> Bool {
    let store = JSONSettingsStore()
    try await store.save(Settings(isDarkModeEnabled: true))
    try await store.save(Settings(isDarkModeEnabled: false))
    return try await store.load() == Settings(isDarkModeEnabled: false)
}

Expected: the evidence returns true, demonstrating replacement rather than merging. Encoding finishes before the record is replaced; an encoding failure would leave the previous record intact. Decoding errors would be thrown, not returned as nil. This adapter owns a serialized buffer, not a file; process termination loses it. The explicit alias is useful for API clarity, although inference is sufficient in many conformers.

A generic conformer binds Value for each concrete instantiation

Trigger: preview features need the same storage mechanics for settings and a last-viewed product ID. A generic actor reuses the mechanics without erasing which value each instance accepts. Here MemoryStore<Settings>.Value is Settings, while MemoryStore<String>.Value is String.

SWIFT
actor MemoryStore<Model: Sendable>: Store {
    typealias Value = Model
    private var stored: Model?
    func save(_ value: Model) async throws {
        try Task.checkCancellation()
        stored = value
    }
    func load() async throws -> Model? {
        try Task.checkCancellation()
        return stored
    }
}
func roundTrip<S: Store>(_ value: S.Value, in store: S) async throws -> S.Value? {
    try await store.save(value)
    return try await store.load()
}
func separateStoreEvidence() async throws -> Bool {
    let preferences = MemoryStore<Settings>()
    let lastProduct = MemoryStore<String>()
    let settings = try await roundTrip(Settings(isDarkModeEnabled: true), in: preferences)
    let productID = try await roundTrip("mug", in: lastProduct)
    return settings == Settings(isDarkModeEnabled: true) && productID == "mug"
}

Expected: the evidence returns true; each actor owns its own stored value. S.Value connects the helper's input and output to the chosen store. The two generic instantiations are different concrete types, not one type switching its conformance. A single concrete type cannot adopt Store twice with unrelated Value witnesses; introduce a generic wrapper or separate adapter types. See Swift's multiple-conformance restrictions.

A method-generic parameter is chosen anew per call

Trigger: a local import utility decodes several document shapes. Unlike a settings store's fixed Value, a generic decode<T> operation accepts a type chosen by each caller. It must handle every allowed Decodable type or throw a decoding error; it cannot assume every T is Settings.

SWIFT
struct SnapshotDecoder {
    func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T {
        try JSONDecoder().decode(type, from: data)
    }
}
func methodGenericEvidence() throws -> Bool {
    let decoder = SnapshotDecoder()
    let settings = try decoder.decode(Settings.self,
        from: Data(#"{"isDarkModeEnabled":true}"#.utf8))
    let productIDs = try decoder.decode([String].self,
        from: Data(#"["mug","notebook"]"#.utf8))
    return settings.isDarkModeEnabled && productIDs == ["mug", "notebook"]
}

Expected: this returns true with the same decoder value used for two result types. Supplying malformed JSON or a shape incompatible with the selected type throws. Neither type mechanism validates all business rules automatically: successfully decoding a string does not prove it is an authorized product ID.

Type choiceWho fixes itLifetime of the relationship
Store.ValueThe conforming typeIts conformance
MemoryStore<Model>'s ModelCode choosing a concrete generic instantiationThat instantiated store type
decode<T>'s TThe call site/inferenceThat invocation

A where clause pairs the decoder output with the store input

Trigger: importing a settings snapshot should only write to a compatible store. This helper relates two associated types without requiring the decoder and store to be the same concrete type. The decoder owns format interpretation; the store owns replacement/storage.

SWIFT
protocol SnapshotDecoding: Sendable {
    associatedtype Output: Sendable
    func decode(_ data: Data) throws -> Output
}
struct SettingsDecoder: SnapshotDecoding {
    func decode(_ data: Data) throws -> Settings {
        try JSONDecoder().decode(Settings.self, from: data)
    }
}
func importSnapshot<D: SnapshotDecoding, S: Store>(
    _ data: Data, using decoder: D, into store: S
) async throws -> D.Output where D.Output == S.Value {
    let value = try decoder.decode(data)
    try Task.checkCancellation()
    try await store.save(value)
    return value
}
func compatibleImportEvidence() async throws -> Bool {
    let store = MemoryStore<Settings>()
    let imported = try await importSnapshot(
        Data(#"{"isDarkModeEnabled":true}"#.utf8),
        using: SettingsDecoder(), into: store)
    let loaded = try await store.load()
    return imported.isDarkModeEnabled && loaded == imported
}

Expected: the evidence returns true; malformed input throws before the save call, leaving prior storage unchanged. Type equality proves that the decoded output can be passed to save, not that data is semantically valid or storage is durable. See generic where clauses.

🟥 Deliberately invalid follow-up — uses blocks 1 + 3 + 5: this pairing cannot compile because SettingsDecoder.Output is Settings while the store's Value is String.

SWIFT
func incompatibleImport() async throws {
    let store = MemoryStore<String>()
    _ = try await importSnapshot(
        Data(#"{"isDarkModeEnabled":true}"#.utf8),
        using: SettingsDecoder(), into: store)
}

🟩 Change the store to MemoryStore<Settings> as in the working example. If the internal representation must be text, introduce an adapter that accepts Settings and explicitly encodes/decodes that text. JSONSettingsStore demonstrates the same boundary using Data internally while keeping Value == Settings; it is not a Store of String. Do not force-cast or erase the mismatch to Any. Diagnostic text varies by compiler, but the incompatible same-type requirement must be rejected.

A known associated value also makes existential writes safe

This independent version marks Value as a primary associated type. any Store<Settings> hides the provider but fixes its accepted/returned value. An unconstrained any Store cannot safely accept an arbitrary Settings, because its hidden Value could be another type.

SWIFT
struct Settings: Sendable, Equatable { var isDarkModeEnabled: Bool }
protocol Store<Value>: Sendable {
    associatedtype Value: Sendable
    func save(_ value: Value) async throws
    func load() async throws -> Value?
}
actor SettingsStore: Store {
    private var stored: Settings?
    func save(_ value: Settings) async throws {
        try Task.checkCancellation()
        stored = value
    }
    func load() async throws -> Settings? {
        try Task.checkCancellation()
        return stored
    }
}
func enableDarkMode(in store: any Store<Settings>) async throws -> Settings? {
    try await store.save(Settings(isDarkModeEnabled: true))
    return try await store.load()
}
func constrainedStoreEvidence() async throws -> Bool {
    try await enableDarkMode(in: SettingsStore()) == Settings(isDarkModeEnabled: true)
}

Expected: the evidence returns true; safe write input follows from Value == Settings. The angle brackets name an associated-type constraint, not a nominal generic protocol instantiation. See SE-0346 and SE-0353. For wider tradeoffs, continue with generic type relationships and stored existential capabilities.

Type compatibility is only one part of the storage contract

These actors contain no await inside an individual mutation, but a caller's save followed by load is two operations: another writer can intervene. Actor serialization is not a multi-operation transaction or a guarantee of invocation order among concurrent tasks. Define an atomic update/transaction capability when the feature needs it. Sendable also does not imply deep-copy semantics for every possible generic value; reference values may still refer to shared objects.

Cancellation is checked before mutation in these implementations. Cancellation arriving after that check or after a commit does not roll back a saved value; callers must not infer “nothing changed” merely from a cancellation signal. Real persistence adds disk failures, migration, atomic replacement, durability and recovery policies. Use typed compatibility to prevent wiring errors, then test missing, replacement, malformed, cancellation and concurrent-update behavior separately.

Why declare a primary associated type?

Short answer: A primary associated type makes a commonly constrained associated type easier to name at the point where the protocol is used. This helps an API express which output or element type it needs while still hiding the provider's concrete type. It does not make the protocol itself a generic concrete type.

Detailed explanation:

It lets clients name a commonly constrained associated type in angle brackets. It improves generic constraints and constrained existential storage; it does not turn the protocol itself into a nominal generic type.

SWIFT
import Foundation
​
protocol Cache<Value> {
    associatedtype Value
    func value(for key: String) -> Value?
}
​
func readAvatar(
    from cache: any Cache<Data>,
    key: String
) -> Data? {
    cache.value(for: key)
}

Why can Self requirements limit calls through an existential?

Short answer: Self means the particular type that conforms to the protocol. An existential hides that concrete type, so the caller may no longer have enough information to safely provide a value that must be the exact same type. A generic boundary or another deliberately designed API can preserve the relationship the operation needs.

Detailed explanation:

Self means the exact conforming type. A requirement that accepts or returns Self preserves a relationship the existential may erase, so not every such operation can be called meaningfully on any P. Keep the consumer generic, expose a constrained associated type, or add deliberate type erasure.

SWIFT
protocol Mergeable {
    func merged(with other: Self) -> Self
}
​
func merge<T: Mergeable>(_ first: T, _ second: T) -> T {
    first.merged(with: second)
}

When does a protocol call reach a conformer's implementation?

Short answer: If the method is a protocol requirement, calls through the protocol can use the implementation supplied by its conformance. A method declared only in an extension is different: a call through the protocol constraint resolves to that extension member. Declare customization points as requirements when conformers are expected to provide the behavior.

Detailed explanation:

If a method is a protocol requirement, a conformer's implementation is used through the protocol witness table. If it exists only in an extension, a call made through an existential or generic protocol constraint resolves to the extension implementation known at that static call site.

SWIFT
protocol StatusReporting {
    func status() -> String
}
​
extension StatusReporting {
    func status() -> String { "default" }
}
​
struct LiveReporter: StatusReporting {
    func status() -> String { "live" }
}
​
let reporter: any StatusReporting = LiveReporter()
print(reporter.status()) // "live" because status is a requirement

🟨 If status() were removed from the protocol declaration and existed only in the extension, the existential call would use the extension implementation. This is a frequent senior-level dispatch question.

Why are delegate protocols often restricted to class types?

Short answer: Delegates are often held weakly so the delegating object does not keep the delegate alive or create a strong reference cycle. Weak storage requires a reference type, so a class-bound protocol limits conformers to objects that support that ownership model. The restriction should reflect the intended lifetime contract.

Detailed explanation:

A delegate is commonly held weakly to avoid a retain cycle. AnyObject restricts conformers to reference types, which makes weak storage possible.

SWIFT
@MainActor
protocol ProfileCoordinatorDelegate: AnyObject {
    func profileCoordinatorDidFinish()
}
​
@MainActor
final class ProfileCoordinator {
    weak var delegate: (any ProfileCoordinatorDelegate)?
​
    func finish() {
        delegate?.profileCoordinatorDidFinish()
    }
}

How does protocol composition differ from protocol inheritance?

Short answer: Protocol inheritance declares a new, refined contract that includes another protocol's requirements. Composition describes a value that must satisfy several existing contracts at one use site. Use inheritance when naming a reusable capability and composition when a particular operation just needs those capabilities together.

Detailed explanation:

Protocol inheritance defines a new refined contract. Composition with & describes a use-site value that must satisfy several existing contracts.

SWIFT
protocol Logging {
    func log(_ message: String)
}
​
protocol MetricsRecording {
    func increment(_ name: String)
}
​
func recordLaunch(using client: any Logging & MetricsRecording) {
    client.log("Application launched")
    client.increment("launch")
}

When is a type-erasing wrapper useful?

Short answer: A type-erasing wrapper hides different concrete implementations behind one stable public type while exposing selected operations. It is useful when ordinary generic or existential forms cannot express the storage or API boundary clearly. The cost is extra code and hidden capabilities, so use the simpler form when it already fits.

Detailed explanation:

Type erasure is useful when an API must store different generic implementations behind one stable type while preserving a selected operation. It costs boilerplate and can hide capabilities, so prefer a constrained existential when it expresses the requirement directly.

🟦 Illustrative example:

SWIFT
struct AnyLoader<Value> {
    private let operation: () throws -> Value
    init(_ operation: @escaping () throws -> Value) {
        self.operation = operation
    }
    func load() throws -> Value { try operation() }
}
let preview = AnyLoader<String> { "Preview account" }
let name = try preview.load()

🧠 The wrapper exposes only loading a Value while hiding the captured implementation. It trades boilerplate and closure indirection for a stable surface; this synchronous example makes no cross-actor safety guarantee.

Can a protocol decide how a property is stored?

Short answer: No. A Swift protocol requires access to a property, such as reading it or reading and writing it, rather than requiring a particular storage mechanism. A conforming type can satisfy that same access requirement with a stored or computed property.

Detailed explanation:

A protocol requires property access, not storage. A conformer may satisfy { get } or { get set } with stored or computed properties. Native Swift protocol requirements are not optional. @objc optional is limited to Objective-C-compatible, class-only designs; in pure Swift, split capabilities into smaller protocols or provide an intentional default implementation.

🟦 Illustrative example:

SWIFT
protocol Named { var name: String { get } }
struct StoredName: Named { let name: String }
struct ComputedName: Named {
    let first: String
    let last: String
    var name: String { "\(first) \(last)" }
}

🧠 Both storage strategies satisfy the same readable-property requirement. An optional Swift property value is not an optional protocol requirement; pure-Swift optional capabilities usually deserve a separate protocol or an intentional default.

What can go wrong with a protocol's default implementation?

Short answer: A default implementation can silently satisfy a requirement with behavior that is wrong for a particular conformer. That is especially risky for important actions such as saving or auditing, where a no-op may compile but lose required work. Use defaults for genuinely shared behavior and require an explicit decision when correctness depends on the conformer.

Detailed explanation:

Defaults are helpful for universal behavior and reusable algorithms. They are dangerous when they silently satisfy important business requirements, create surprising dispatch, or make a new requirement compile without every conformer making an explicit decision.

🟦 Illustrative example:

SWIFT
protocol AuditRecording {
    func record(_ event: String)
}
struct InMemoryAudit: AuditRecording {
    private(set) var note = "test-only sink"
    func record(_ event: String) { print("TEST: \(event)") }
}
func complete(using audit: any AuditRecording) {
    audit.record("checkout-completed")
}

🧠 Leaving the requirement without a silent no-op default makes each conformer choose behavior. The printing implementation is explicitly test-only; a production audit sink needs durability/redaction semantics, and a default that silently discards events could make conformance compile while violating that contract.

Does every Swift type need a protocol?

Short answer: No, a protocol is useful when it captures a meaningful shared capability, replaceable dependency, or generic relationship. A concrete type is often clearer when there is one stable implementation and no useful substitution boundary. Adding a protocol everywhere increases design work without automatically improving testability or flexibility.

Detailed explanation:

No. Protocol-oriented design uses behavior-focused abstractions where substitutability or generic algorithms provide value. Concrete types are clearer when there is one stable implementation and no meaningful abstraction boundary.

🟦 Illustrative example:

SWIFT
struct CurrencyAmount {
    let minorUnits: Int
    let currency: String
}
protocol ExchangeRateLoading {
    func rate(from: String, to: String) async throws -> Double
}

🧠 The amount is an ordinary value type; the external, replaceable rate-loading capability supplies a meaningful protocol boundary. Adding an empty protocol to every value would not improve testability or substitution.

Protocol code-review exercises

Try each prompt before opening the answer section.

Prompt 1: Can this protocol dependency be constructed directly?

This code tries to create a payment-processing dependency directly from its protocol.

SWIFT
protocol PaymentProcessing {
    func charge(cents: Int) async throws
}
​
let processor = PaymentProcessing()
Optional follow-up questions
  • Explain the declaration or ownership change that makes the intended contract explicit.

Prompt 2: Why must this protocol allow its struct conformer to mutate?

A struct resets its stored count while conforming to a reset protocol.

SWIFT
protocol Resettable {
    func reset()
}
​
struct RetryPolicy: Resettable {
    private(set) var attempts = 3
​
    func reset() {
        attempts = 0
    }
}
Optional follow-up questions
  • Explain the declaration or ownership change that makes the intended contract explicit.

Prompt 3: Why does this call use the protocol extension's description?

Compare the concrete type's description method with the method available through its protocol.

SWIFT
protocol Describable { }
​
extension Describable {
    func describe() -> String { "extension" }
}
​
struct Screen: Describable {
    func describe() -> String { "screen" }
}
​
let item: any Describable = Screen()
print(item.describe())
Optional follow-up questions
  • Explain the declaration or ownership change that makes the intended contract explicit.

Prompt 4: Who may safely own or share this token-reading dependency?

An actor stores a token reader. Decide whether that reader is exclusively owned or shared elsewhere.

SWIFT
protocol TokenReading {
    func token() async -> String?
}
​
actor APIClient {
    let reader: any TokenReading
​
    init(reader: any TokenReading) {
        self.reader = reader
    }
}
Optional follow-up questions
  • Explain the declaration or ownership change that makes the intended contract explicit.

🟩 Protocol exercise answers

🟥 Answer 1: A protocol has no initializer

Short answer: No. The protocol describes the operations a payment processor must provide, but is not a concrete processor instance. Construct a conforming implementation first, then store that object through the protocol interface if the consumer should depend only on the contract.

Detailed explanation:

Construct a concrete conformer and optionally store it as an existential.

SWIFT
protocol PaymentProcessing {
    func charge(cents: Int) async throws
}
​
struct LivePaymentProcessor: PaymentProcessing {
    func charge(cents: Int) async throws { }
}
​
let processor: any PaymentProcessing = LivePaymentProcessor()

🟥 Answer 2: The requirement and implementation must be mutating

Short answer: A struct method that changes the struct or one of its stored properties must be declared mutating. The protocol requirement must also allow that kind of method, so value-type conformers can satisfy it without violating the contract. Update both sides of the declaration rather than only the implementation.

Detailed explanation:

A struct method that changes self or one of its stored properties must be mutating. The protocol must permit value-type conformers to mutate too.

SWIFT
protocol Resettable {
    mutating func reset()
}
​
struct RetryPolicy: Resettable {
    private(set) var attempts = 3
​
    mutating func reset() {
        attempts = 0
    }
}

🟨 Answer 3: It prints extension

Short answer: The description method exists only in the extension, so a call through the protocol interface selects that extension member instead of the concrete type's same-named method. Make it a protocol requirement when conforming types should customize the behavior. That changes the contract used by callers through the abstraction.

Detailed explanation:

describe() is not a protocol requirement, so the call through any Describable uses the extension-only member selected from the static type. Declare it as a requirement when conformers are expected to customize behavior.

SWIFT
protocol Describable {
    func describe() -> String
}

With that requirement, Screen supplies the witness and the same call prints screen.

🟨 Answer 4: Decide whether the dependency crosses isolation domains

Short answer: An actor may exclusively own a dependency that is safely transferred to it, even if the dependency is not Sendable. If the same dependency must be shared across isolation boundaries, that sharing needs an explicit safe contract. Choose real ownership or synchronization first; unchecked conformance does not manufacture safety.

Detailed explanation:

An actor can own a non-Sendable dependency when the value is safely transferred and not shared elsewhere. If the same reader is intended to cross or be shared across isolation domains, make that contract explicit with Sendable and ensure conformers honor it.

SWIFT
protocol TokenReading: Sendable {
    func token() async -> String?
}

Do not add @unchecked Sendable just to silence the compiler. Use value semantics, actor isolation, locking, or another real synchronization strategy first.

Senior iOS question bank

Swift language and API design

  1. Explain value semantics, copy-on-write, and reference identity with an example from an app.
  2. When would you use an enum with associated values instead of a protocol hierarchy?
  3. Compare some P, any P, and T: P in a public API.
  4. How do primary associated types improve an API without making the protocol generic?
  5. What is the difference between Sendable and Codable?
  6. How do escaping closures affect ownership and actor isolation?
  7. When is @unchecked Sendable legitimate, and what proof must accompany it?
  8. How would you evolve a public Swift package API without breaking source compatibility?

Architecture and modularity

  1. Draw the dependency direction for UI, domain, data, and platform layers.
  2. Which boundaries deserve protocols, and which should stay concrete?
  3. Where is the composition root, and who owns long-lived dependencies?
  4. How do you stop a “core” module from becoming a dumping ground?
  5. How would you split a large feature into packages without creating cyclic dependencies?
  6. How do DTOs, domain models, and view state differ in lifetime and responsibility?
  7. Describe an incremental migration from UIKit MVC to a testable architecture.
  8. How do deep links and navigation state cross feature-module boundaries?

Concurrency and reliability

  1. What can change after an await, and how do you revalidate actor state?
  2. Compare structured tasks, unstructured Task, and Task.detached.
  3. How do you propagate cancellation through networking, parsing, and UI state?
  4. Design single-flight token refresh without duplicate requests.
  5. How would you prevent an old search response from replacing a newer result?
  6. What does priority inversion look like, and how can it appear with locks or tasks?
  7. How do you bridge a callback API to async/await safely with continuations?
  8. When is an actor insufficient because an operation must be atomic across await?

SwiftUI, UIKit, and lifecycle

  1. Who owns a SwiftUI model, and how do Observation and bindings expose it?
  2. Why is doing work in body unsafe, and where should side effects live?
  3. How do view identity and list identifiers affect state preservation and animation?
  4. How do you cancel image loading when a reusable cell or view disappears?
  5. Explain Auto Layout priorities and diagnose an ambiguous or unsatisfiable layout.
  6. How would you embed SwiftUI inside UIKit while preserving navigation ownership?
  7. How do you model restoration for a multi-step flow?
  8. Which accessibility behaviors must a custom control implement?

Performance, persistence, and networking

  1. How do you investigate a slow launch using measurements rather than guesses?
  2. What causes scrolling hitches, and which work belongs off the main actor?
  3. How do memory graphs, allocations, and time profiling answer different questions?
  4. When would you cache decoded models, raw responses, or rendered images?
  5. How do HTTP caching, ETags, retries, idempotency, and backoff interact?
  6. How do you migrate a persistent store while preserving user data and rollback options?
  7. What is your offline conflict strategy: last-write-wins, merge, or user resolution?
  8. How do you avoid decoding a very large response into multiple temporary copies?

Testing, delivery, and leadership

  1. What belongs in unit, integration, UI, snapshot, and performance tests?
  2. How do you make time, randomness, UUID generation, and network behavior deterministic?
  3. How would you test cancellation and actor-isolated state without timing sleeps?
  4. What makes a test double a fake, stub, spy, or mock, and when does the distinction help?
  5. How do feature flags support rollout and rollback without becoming permanent debt?
  6. Which metrics and logs would prove a release is healthy without exposing user data?
  7. How do you review an architectural proposal and surface tradeoffs constructively?
  8. Describe a production incident you owned: detection, mitigation, root cause, and prevention.

Senior code discussion: stale-result protection

An interviewer may ask you to review a search implementation. State the invariant first: only the latest query may update visible results.

SWIFT
import Foundation
​
@MainActor
final class SearchModel {
    private let search: @Sendable (String) async throws -> [String]
    private var searchTask: Task<Void, Never>?
    private(set) var results: [String] = []
    private(set) var errorMessage: String?
​
    init(search: @escaping @Sendable (String) async throws -> [String]) {
        self.search = search
    }
​
    func submit(query: String) {
        searchTask?.cancel()
​
        guard !query.isEmpty else {
            results = []
            errorMessage = nil
            return
        }
​
        searchTask = Task {
            do {
                try await Task.sleep(for: .milliseconds(300))
                let newResults = try await search(query)
                try Task.checkCancellation()
                results = newResults
                errorMessage = nil
            } catch is CancellationError {
                // Expected when a newer query replaces this one.
            } catch {
                guard !Task.isCancelled else { return }
                errorMessage = "Search failed"
            }
        }
    }
​
    deinit {
        searchTask?.cancel()
    }
}

A strong discussion covers task ownership, cancellation, debounce behavior, stale results, error policy, main-actor UI state, and deterministic tests with an injected clock or controllable search closure.

Architecture questions to rehearse

  1. Design a modular iOS application used by multiple clients or tenants.
  2. Where do dependency creation and object lifetimes belong?
  3. How do you stop a shared/core module from becoming a dumping ground?
  4. Explain your choice between MVVM-C, VIPER, and a simpler MVVM design.
  5. Where do DTO mapping, validation, formatting, and navigation belong?
  6. How would you migrate a tightly coupled UIKit feature incrementally?
  7. How do you test coordinators, presenters, repositories, and mappers?

Strong answer characteristics:

  • Starts from requirements and change axes
  • Defines ownership and dependency direction
  • Describes failure, cancellation, and threading
  • Explains tradeoffs and incremental adoption
  • Includes observability and testing

SwiftUI/Combine questions to rehearse

  1. Explain state ownership through a parent and two child views.
  2. Why can recreating an observed object in body be a bug?
  3. How would you model loading, empty, content, and error states?
  4. How do subscribe(on:) and receive(on:) differ?
  5. How do you prevent stale search responses?
  6. Show a Combine retain cycle and fix it.
  7. When would you prefer async/await over Combine?

Good comparison:

Async/await is usually clearer for one-shot request/response workflows. Combine remains useful for long-lived or composed streams such as search text, connectivity, notifications, and multiple changing inputs.

Concurrency questions to rehearse

  1. Explain actor reentrancy and why assumptions can change after await.
  2. Build a single-flight token refresh mechanism.
  3. Protect a cache using an actor and then using GCD barriers.
  4. Explain cancellation propagation in structured concurrency.
  5. Compare Task priority with GCD QoS.
  6. Identify a main-thread deadlock from code.
  7. Explain when a value should conform to Sendable.

Security questions to rehearse

  1. Where do access and refresh tokens belong?
  2. How do you prevent simultaneous refresh requests?
  3. What happens after refresh failure?
  4. Certificate versus public-key pinning?
  5. How do you rotate pins safely?
  6. What should never appear in logs or analytics?
  7. How do you separate authentication errors from business errors?

Practical coding challenges

API list

Implement:

  • Codable DTO
  • Repository protocol
  • Async or Combine client
  • Explicit view state
  • Main-actor state update
  • Error and retry UI
  • Cancellation
  • Unit tests with a fake repository

Implement:

  • Query state
  • Debounce and duplicate removal
  • Empty-query handling
  • Cancellation/switching to latest request
  • Loading and error states
  • Deterministic scheduler or async clock tests

Pagination

Implement:

  • isLoading guard
  • cursor/page state
  • end-of-list detection
  • deduplication
  • reset for a new query
  • retry without corrupting the current page

Thread-safe store

Implement twice:

  • Actor-based store
  • Concurrent queue with barrier writes

Explain the consistency and completion semantics of each version.

Final reminders

  • Say who owns each piece of state.
  • Say which layer performs each transformation.
  • Mention cancellation and errors in asynchronous designs.
  • Avoid claiming that a pattern is always best.
  • Prefer domain-specific examples from your own applications.
  • If asked for code, first state the intended contract and edge cases.