Swift Code Quizzes: Choose the Valid Line and Find the Bug
🟪 Syntax · 🟦 Types/APIs · 🟩 Correct pattern · 🟥 Bug · 🟨 Gotcha · 🧠 Explanation
Try each question before reading the answer key. These examples target modern Swift syntax. Some compiler diagnostics differ in wording between Xcode versions.
First: what is wrong with the Abs example?
Given:
protocol Abs {}
let value = Abs()
var value = Abs()
let: Abs = Abs()🟥 None of these lines is a valid way to create a value. The protocol declares a contract; it is not a concrete type with a constructor. The second line also redeclares value if all lines are in the same scope, and the third line has invalid declaration syntax.
🟩 Correct version:
protocol Abs {}
struct ConcreteAbs: Abs {}
let value: any Abs = ConcreteAbs()
var replaceable: any Abs = ConcreteAbs()The right-hand side constructs ConcreteAbs. The left-hand type any Abs says the binding may hold a value of any concrete type that conforms to Abs.
Questions
1. Which declaration creates a mutable integer binding?
A. let count = 0
B. var count = 0
C. Int count = 0
D. var: count Int = 02. Find the bug
let score = 10
score += 13. Find the bug
var nickname: String = nil4. Can this let class reference still change the object's property?
final class Profile {
var name = "Sam"
}
let profile = Profile()
profile.name = "Alex"5. Find the conformance bug
protocol Drivable {
func drive()
}
struct Car: Drivable {}
let car: any Drivable = Car()6. Does this make UserID a distinct type from UUID?
typealias UserID = UUID
func openProfile(for id: UserID) {}
openProfile(for: UUID())7. Find the concurrency bug
actor Counter {
private var value = 0
func currentValue() -> Int { value }
}
func printCounter(_ counter: Counter) {
print(counter.currentValue())
}8. Find the return-type bug
func greeting(_ name: String) -> String {
print("Hello, \(name)")
}9. Which type can go in this array?
import Foundation
protocol Identified {
var id: UUID { get }
}
struct Note: Identified {
let id: UUID
}
let notes: [____] = [Note(id: UUID())]10. What happens here?
struct Settings {
var theme = "light"
}
let settings = Settings()
settings.theme = "dark"🟩 Answer key and explanations
🟩 1. B
var count = 0 declares a mutable binding, and Swift infers Int from 0. let creates an immutable binding. The type annotation, when needed, goes after the name: var count: Int = 0.
🟥 2. score is a let
let prevents reassignment. Use var if this value must change:
var score = 10
score += 1🟥 3. String is non-optional
nil can only be assigned to an optional. If “no nickname” is a valid state, write var nickname: String? = nil. Otherwise, provide a real string value.
🟩 4. Yes
let profile prevents assigning a different Profile reference to profile. It doesn't freeze the class instance. Because name is var, profile.name can change. With a struct, a let instance and its properties are immutable.
🟥 5. Car has not implemented drive()
Car declares conformance but omits a required method. Fix the conformance:
struct Car: Drivable {
func drive() {}
}🟨 6. It is still UUID
typealias is a second name for the same type, so UUID() is accepted. For a distinct domain type, create a wrapper:
struct UserID: Hashable, Sendable {
let rawValue: UUID
}Now a function requiring UserID cannot be passed an arbitrary UUID without an explicit conversion.
🟥 7. The call needs await, and the caller must be async
Reading actor-isolated state crosses the actor boundary:
func printCounter(_ counter: Counter) async {
print(await counter.currentValue())
}An actor protects mutable state; it is not a normal synchronous object. Callers use await when accessing isolated members from outside.
🟥 8. The function promises String, but returns Void
print writes output and returns no string. Return a string instead:
func greeting(_ name: String) -> String {
"Hello, \(name)"
}Swift permits the implicit return because this function body contains one expression.
🟦 9. [any Identified]
Note is a concrete conformer, and an existential array can hold values conforming to the protocol:
let notes: [any Identified] = [Note(id: UUID())]If the API needs a single concrete type relationship, use a generic function that preserves it:
func firstID<T: Identified>(in values: [T]) -> UUID? {
values.first?.id
}🟥 10. It fails because Settings is a struct held by let
Structs have value semantics. A constant struct value cannot have its var property mutated through that binding. Use var settings = Settings() if it should change, or use a class only when shared reference identity is actually needed.
More quick “spot the bug” prompts
For each one, say what the compiler rejects and how you would fix the design:
// A. Optional state
let selectedID: UUID = nil
// B. Protocol construction
protocol Parser {}
let parser = Parser()
// C. Immutable binding
let names = ["A", "B"]
names.append("C")
// D. Missing conformance requirement
protocol Resettable { func reset() }
struct Cache: Resettable {}
// E. Type annotation placement
let: Int total = 4Answers: A needs UUID? if nil is valid. B needs a concrete conforming parser type. C needs var for a mutable array binding. D needs an implementation of reset() or a valid default implementation. E should be let total: Int = 4.
The declaration pattern to memorize
let constantName: SomeType = makeSomeType()
var variableName: SomeType = makeSomeType()The type annotation is optional when Swift can infer it:
let count = 3 // inferred as Int
var name = "Aylin" // inferred as String
let user: any UserLoading = LiveLoader() // existential type + concrete valueRemember: a protocol says what a conforming type can do; a struct, class, or enum gives you a concrete type to instantiate.
Advanced Swift and SwiftUI questionnaire
For Xcode compiler diagnostics, breakpoint/LLDB investigation, and CPU/GPU or memory measurements, use the Xcode debugging and profiling questionnaire.
These are independent practice questions, not an official exam. Attempt the prompts before opening the separate answers below. Suggested practice: 5–10 minutes per code exercise, with extra discussion for Tech Lead questions. Snippets are illustrative, self-contained where practical, and intentionally defective where the prompt asks for a bug. They are not a complete application. Use a Swift 6 language-mode target with explicit isolation settings; SwiftUI examples assume iOS 17+ unless stated otherwise. Compiler version, language mode, isolation settings, and SDK availability are separate concerns.
SWIFT-01 — Can a computed property change the value you assign to it?
An invoice calculates tax from its subtotal. After assigning a total, check whether reading that total returns the same amount.
struct Invoice {
var subtotalCents = 1_000
var taxCents: Int { subtotalCents / 10 }
var totalCents: Int {
get { subtotalCents + taxCents }
set { subtotalCents = newValue - taxCents }
}
}
var invoice = Invoice()
invoice.totalCents = 2_200
print(invoice.subtotalCents, invoice.taxCents, invoice.totalCents)Optional follow-up questions
- Explain whether computed properties automatically cache results.
- Propose a clear tax and rounding policy.
SWIFT-02 — Does private(set) prevent an invalid wallet withdrawal?
This wallet intends to allow withdrawals without increasing the balance or spending more than it holds. Find the missing validation.
struct Wallet {
private(set) var balanceCents = 1_000
mutating func withdraw(_ cents: Int) -> Bool {
guard cents <= balanceCents else { return false }
balanceCents -= cents
return true
}
}Optional follow-up questions
- Write a throwing withdrawal operation.
- Explain why access control does not provide thread safety.
SWIFT-03 — How do overloading and overriding choose an implementation?
Compare the three calls below: one uses an overloaded free function and another calls an overridden class method.
class Screen {
func title() -> String { "Screen" }
}
final class PaymentScreen: Screen {
override func title() -> String { "Payment" }
}
func describe(_ screen: Screen) -> String { "base overload" }
func describe(_ screen: PaymentScreen) -> String { "payment overload" }
let screen: Screen = PaymentScreen()
print(describe(screen))
print(screen.title())
print(describe(PaymentScreen()))Optional follow-up questions
- Predict each printed result.
- Explain whether changing let to var affects dispatch.
SWIFT-04 — Why does this protocol call use the extension's default method?
The concrete Payment type and the protocol extension both define label. Compare a concrete call with calls through the protocol abstraction.
protocol Labelled {}
extension Labelled {
func label() -> String { "default" }
}
struct Payment: Labelled {
func label() -> String { "payment" }
}
func genericLabel<T: Labelled>(_ value: T) -> String { value.label() }
let concrete = Payment()
let erased: any Labelled = concrete
print(concrete.label())
print(erased.label())
print(genericLabel(concrete))Optional follow-up questions
- Predict all printed values.
- Add the missing protocol requirement and explain why the result changes.
SWIFT-05 — Why does this stored callback keep its owner alive?
After the external editor reference is removed, determine whether the stored callback still keeps the editor alive.
final class Editor {
var title = "Draft"
var onSave: (() -> Void)?
func configure() {
onSave = { print(self.title) }
}
deinit { print("Editor released") }
}
var editor: Editor? = Editor()
editor?.configure()
editor = nilOptional follow-up questions
- Draw the ownership links.
- Compare clearing a callback, weak capture, and an unowned capture with a proven lifetime guarantee.
SWIFT-06 — Can a task keep its owner alive even when it starts with a weak capture?
Assume events is a long-lived AsyncStream of integers. Check how long the task retains the owner after guard let self succeeds.
@MainActor
final class ObserverModel {
private var task: Task<Void, Never>?
private(set) var latest = 0
func start(events: AsyncStream<Int>) {
task = Task { [weak self] in
guard let self else { return }
for await value in events {
self.latest = value
}
}
}
deinit { task?.cancel() }
}Optional follow-up questions
- Explain why cancellation only in deinit may never happen.
- Show how the feature explicitly stops observation.
SWIFT-07 — Does a capture list copy an object or only its reference?
Compare a captured integer with a captured reference to a mutable object after both original values are changed.
final class Box {
var value = 1
}
var count = 1
let box = Box()
let report = { [count, box] in
print(count, box.value)
}
count = 2
box.value = 2
report()
print(count)Optional follow-up questions
- Predict the printed values.
- Explain how removing the integer's capture-list entry changes the result.
SWIFT-08 — Why does synchronous work on the same serial queue deadlock?
This intentionally invalid example schedules synchronous work from inside the same serial queue. Review it without running the blocking path.
import Dispatch
let queue = DispatchQueue(label: "cache.serial")
queue.async {
queue.sync {
print("refresh cache")
}
}Optional follow-up questions
- Explain why using the main queue would not fix the wait cycle.
- Compare an internal synchronous helper with an asynchronous API.
SWIFT-09 — Why are these concurrent increments unsafe?
Several concurrent operations increment one mutable counter. Identify the shared access that needs protection; Swift concurrency checking may reject this unsafe example.
import Dispatch
final class CounterBox {
var value = 0
}
func incrementConcurrently() {
let counter = CounterBox()
DispatchQueue.concurrentPerform(iterations: 1_000) { _ in
counter.value += 1
}
print(counter.value)
}Optional follow-up questions
- Compare actor ownership with a lock-protected critical section.
- Explain what diagnostics and controlled tests can establish.
SWIFT-10 — Why can an older search replace newer results on MainActor?
A user searches for s and then swift. Assume the first request finishes last, and the service is a Sendable dependency returning string results.
protocol Searching: Sendable {
func results(for query: String) async throws -> [String]
}
@MainActor
final class SearchModel {
var results: [String] = []
let service: any Searching
init(service: any Searching) { self.service = service }
func search(_ query: String) async throws {
results = try await service.results(for: query)
}
}Optional follow-up questions
- Distinguish a logical ordering bug from a data race.
- Describe a deterministic test that completes the requests in reverse order.
SWIFT-11 — Can an actor's state change while it waits for authorization?
Two calls each try to withdraw 80 from a balance of 100. Assume authorize suspends, allowing another withdrawal to run before the first continues.
actor Account {
private var balance = 100
func withdraw(
_ amount: Int,
authorize: @Sendable () async throws -> Void
) async throws -> Bool {
guard amount > 0, balance >= amount else { return false }
try await authorize()
balance -= amount
return true
}
}Optional follow-up questions
- Compare rechecking after the wait with reserving funds before it.
- Identify which remote-payment guarantees must be enforced by the server.
SWIFT-12 — How can an old refresh accidentally clear a newer refresh task?
Refresh A starts, invalidation runs, refresh B starts, and then A completes. Examine what A's cleanup does to the shared task slot.
actor TokenCache {
private var inFlight: Task<String, Error>?
func invalidate() { inFlight = nil }
func token(
refresh: @escaping @Sendable () async throws -> String
) async throws -> String {
if let inFlight { return try await inFlight.value }
let task = Task { try await refresh() }
inFlight = task
defer { inFlight = nil }
return try await task.value
}
}Optional follow-up questions
- Define whether callers already waiting for A may still receive its result.
- Explain who may cancel work shared by several callers.
SWIFT-13 — Does awaiting a detached task automatically connect its cancellation to the caller?
Assume download is an appropriately isolated asynchronous service. The caller creates a detached worker and waits for its result; consider what happens when the caller is cancelled.
func load() async throws -> String {
let worker = Task.detached {
try await download()
}
return try await worker.value
}Optional follow-up questions
- Explain why discarding a task handle does not stop the work.
- Give a case where independent detached work has a justified owner.
SWIFT-14 — Does Sendable make mutable shared state safe by itself?
This class declares checked Sendable conformance while exposing mutable stored state. Explain why the conformance does not establish safety.
final class UserDraft: Sendable {
var displayName = ""
}
let draft = UserDraft()
draft.displayName = "Updated"Optional follow-up questions
- Compare an immutable value snapshot with an actor-owned model.
- Separate safe sharing from business ordering and freshness.
SWIFT-15 — Does a nonisolated async function always leave the calling actor?
Assume a Swift 6.2 or newer toolchain. Review where this CPU-heavy helper runs when called from MainActor, considering whether NonisolatedNonsendingByDefault is enabled.
nonisolated func checksum(_ bytes: [UInt8]) async -> UInt64 {
bytes.reduce(0) { ($0 &* 31) &+ UInt64($1) }
}
@MainActor
func checksumForDisplay(_ bytes: [UInt8]) async -> UInt64 {
await checksum(bytes)
}Optional follow-up questions
- Distinguish language mode, default actor isolation, and the upcoming-feature setting.
- Explain how an explicit concurrent boundary and profiling would address UI responsiveness.
SWIFT-16 — How does async cleanup in defer work in Swift 6.4?
This version-specific example requires Swift 6.4 or newer and an async function. Follow the order in which scope-exit cleanup completes.
protocol UploadSession: Sendable {
func upload() async throws
func close() async
}
func run(_ session: some UploadSession) async throws {
defer { await session.close() }
try await session.upload()
}Optional follow-up questions
- Compare normal return, thrown error, and cancellation.
- Explain why a synchronous function cannot use the body unchanged.
- Discuss bounded cancellation shielding for essential cleanup.
SWIFT-17 — Why can a task group keep waiting after its first result arrives?
Independent requests run in a throwing task group. The function returns the first result from next; consider what happens to the remaining requests.
func firstResponse(
_ requests: [@Sendable () async throws -> String]
) async throws -> String? {
try await withThrowingTaskGroup(of: String.self) { group in
for request in requests {
group.addTask { try await request() }
}
return try await group.next()
}
}Optional follow-up questions
- Define behavior for a first error, empty input, and all failures.
- Explain how to verify cancellation without relying on timing sleeps.
SWIFT-18 — How should a SwiftUI view keep its Observable model across updates?
Assume iOS 17 or newer. A parent reconstructs this child view while the user is editing; identify whether the model instance is preserved.
import SwiftUI
import Observation
@Observable
final class ProfileDraft {
var name = ""
}
struct ProfileEditor: View {
private var draft = ProfileDraft()
var body: some View {
@Bindable var editableDraft = draft
TextField("Name", text: $editableDraft.name)
}
}Optional follow-up questions
- Compare the older StateObject and ObservedObject ownership roles.
- Distinguish an ordinary view update from an intentional identity change.
SWIFT-19 — Why should list rows use stable item IDs rather than array positions?
Rows can be inserted, removed, or reordered, and each row holds local editing state. Check what happens when positions are used as row identity.
struct EditableRow: View {
let name: String
@State private var expanded = false
var body: some View {
Toggle(name, isOn: $expanded)
}
}
struct NamesView: View {
let names: [String]
var body: some View {
List {
ForEach(names.indices, id: \.self) { index in
EditableRow(name: names[index])
}
}
}
}Optional follow-up questions
- Describe a UI test that exposes state moving to another item.
- Decide where state belongs if it must survive removal of the row.
SWIFT-20 — Why should a binding update local state before saving asynchronously?
A toggle starts an asynchronous save from its binding setter. Assume save is an application dependency and that requests may complete out of order.
Toggle("Notifications", isOn: Binding(
get: { notificationsEnabled },
set: { newValue in
Task {
try await save(newValue)
notificationsEnabled = newValue
}
}
))Optional follow-up questions
- Choose an optimistic-update, rollback, or unsaved-indicator policy.
- Explain why cancelling a client task does not undo a completed server write.
SWIFT-21 — How should a navigation path represent a restorable deep link?
A product link should open a product detail or checkout screen and be restorable after relaunch. Decide what information belongs in the route.
Optional follow-up questions
- Sketch a typed path using NavigationStack.
- Explain how to handle deleted items, expired sessions, and competing path owners.
SWIFT-22 — Why is one optional sheet route safer than two presentation flags?
This screen uses separate flags for creating and editing a document. Identify which invalid presentation combinations those flags allow.
@State private var showingEditor = false
@State private var showingHelp = false
@State private var selectedDocumentID: String?Optional follow-up questions
- Replace the flags with an optional item-based route.
- Define how unsaved edits affect dismissal and a request to open a different sheet.
SWIFT-23 — Why do two text fields need distinct FocusState values?
Both text fields below bind to the same focus value. Consider which field should be focused when the model selects that value.
@FocusState private var focused: Bool
// Inside a view body:
TextField("Email", text: $email).focused($focused)
SecureField("Password", text: $password).focused($focused)Optional follow-up questions
- Add an email-to-password submit sequence.
- Explain how to reject a stale validation response that tries to move focus.
SWIFT-24 — Does task(id:) prevent every outdated search result from appearing?
Assume an asynchronous search service sometimes returns a result even after cancellation. Review whether this view accepts only the newest request.
// Illustrative body modifier; the service is a Sendable dependency.
.task(id: query) {
do {
results = try await service.results(for: query)
} catch {
errorMessage = "Search failed"
}
}Optional follow-up questions
- Explain how task lifetime changes when the ID changes or the view disappears.
- Define who may update loading and error state after a newer request starts.
SWIFT-25 — Why should this tappable label be a semantic Button?
Review this payment action at large text sizes and when operated through accessibility tools rather than a touch gesture.
Text("Pay now")
.font(.system(size: 12))
.frame(width: 72, height: 24)
.onTapGesture { submitPayment() }Optional follow-up questions
- Check VoiceOver, keyboard and Switch Control activation.
- Test longer translations, right-to-left layout, and duplicate-action prevention.
SWIFT-26 — Why should a computed property used by a view avoid starting work?
Assume a large collection and an asynchronous repository. This view's computed getter both derives visible data and starts refresh work.
var visibleNames: [String] {
Task { await repository.refresh() }
return records
.filter { $0.name.localizedCaseInsensitiveContains(query) }
.sorted { $0.name < $1.name }
.map(\.name)
}
var body: some View {
List(visibleNames, id: \.self) { Text($0) }
}Optional follow-up questions
- Explain where cancellation and stale-result handling belong.
- Decide whether caching is justified using recomputation and responsiveness measurements.
SWIFT-27 — How should a continuation handle a legacy API that calls back twice?
A receipt SDK may invoke its completion twice from different queues, and the waiting screen may be cancelled. Design one terminal result for that wait.
Optional follow-up questions
- Explain how completion competes with cancellation before and after registration.
- Decide what can stop when the underlying SDK itself is not cancellable.
SWIFT-28 — Does AsyncStream make a fast producer wait for a slow consumer?
A sensor produces 100 readings per second while a chart can render 10. Choose an explicit policy for values that arrive while rendering is busy.
Optional follow-up questions
- Compare newest-value, oldest-value, and unbounded buffering.
- Explain who stops the producer after cancellation or an early exit from the loop.
SWIFT-29 — What happens to an async-let sibling when an error exits the parent scope?
A profile screen loads account details and processes an avatar concurrently. The account request fails while avatar processing continues.
Optional follow-up questions
- Explain how changing await order affects when the error is observed.
- Show how long CPU work can respond to cancellation in bounded steps.
SWIFT-30 — Why can retrying a payment after cancellation cause a duplicate charge?
The server commits a payment but its response is lost. A retry helper creates a new operation ID for every attempt and retries even cancellation errors.
Optional follow-up questions
- Define which transient errors may be retried and how backoff is bounded.
- Explain the server guarantees needed to deduplicate and later reconcile the payment.
SWIFT-31 — Should cancelling one screen stop a download shared with another screen?
Two screens wait for the same catalog download owned by an application-scoped service. One screen disappears while the other still needs the result.
Optional follow-up questions
- Define the service's shutdown authority.
- Explain whether a cancelled caller must return immediately or may wait for shared work to finish.
SWIFT-32 — Does copying a struct also copy the mutable objects inside it?
An edit screen copies a struct that contains a mutable address object. The user changes the draft and then cancels editing.
final class AddressBox {
var city = "Ankara"
}
struct ShippingDraft {
let address: AddressBox
}
let original = ShippingDraft(address: AddressBox())
let editing = original
editing.address.city = "Izmir"
print(original.address.city)Optional follow-up questions
- Predict whether the saved address changes.
- Explain why a struct containing a class is not automatically deeply immutable or safe to share concurrently.
SWIFT-33 — Does an async computed property automatically reuse a previous result?
A view reads a repository's asynchronous latest-receipt property twice and expects only one network request.
Optional follow-up questions
- Compare two getter accesses with one explicit load reused locally.
- Discuss whether a loading method would communicate the operation's cost more clearly.
SWIFT-34 — Why does a detached task not inherit a task-local trace ID?
A checkout operation sets a task-local trace ID. Compare reads in the same task, a structured child, an ordinary Task, and a detached task.
Optional follow-up questions
- Show explicit propagation to justified independent work.
- Explain how context inheritance differs from cancellation and lifetime ownership.
SWIFT-35 — Why can a reused cell show the wrong product image?
A catalog cell starts an image request for one product, then is configured for another product before that request finishes.
// Illustrative bug: both callbacks can refer to the same reused cell.
func configure(photoURL: URL) {
Task { [weak self] in
let (data, _) = try await URLSession.shared.data(from: photoURL)
self?.imageView?.image = UIImage(data: data)
}
}Optional follow-up questions
- Explain why cleanup is needed on every configuration, not only prepareForReuse.
- Design a test that completes the old request after the new one.
SWIFT-36 — Does SwiftUI task guarantee that a screen loads only once?
A profile screen starts loading from both onAppear and task, and navigating away and back increases its request count.
Optional follow-up questions
- Remove the duplicate loading owner.
- Define when cached success is reused and which work stops when the view leaves.
SWIFT-37 — Why does recreating a view not replace its existing State value?
A parent selects a different note, but an editor initialized from that note still shows the previous document's draft.
struct NoteEditor: View {
let note: Note
@State private var draft: String
init(note: Note) {
self.note = note
_draft = State(initialValue: note.text)
}
var body: some View { TextField("Note", text: $draft) }
}Optional follow-up questions
- Show a deliberate document-switch reset.
- Explain how to preserve edits during unrelated parent updates.
SWIFT-38 — Which direction should updates flow in a UIViewRepresentable wrapper?
A UITextView wrapper copies text in both directions during updateUIView. New parent text is sometimes lost and the cursor jumps.
Optional follow-up questions
- Explain how a coordinator reports user edits without creating a feedback loop.
- Discuss cursor position and text composition during programmatic updates.
SWIFT-39 — Do debounce and duplicate removal cancel an earlier search request?
A Combine search pipeline debounces input, removes duplicate text, and starts requests with flatMap. An older response sometimes replaces newer results.
Optional follow-up questions
- Explain what may finish while a newer query is still being debounced.
- Place error recovery so a failed request does not end the input stream.
SWIFT-40 — How can one some View return include different conditional views?
A badge returns a ProgressView while uploading and a Label afterward. The ordinary function declares some View but uses separate return statements.
Optional follow-up questions
- Show a builder-based version.
- Give a case where deliberate type erasure is useful.
SWIFT-41 — What belongs in AppStorage, and what belongs in secure storage?
A reader app wants to remember its theme. A proposed design uses AppStorage for an arbitrary settings struct and for an access token.
Optional follow-up questions
- Choose a stable stored representation and a fallback for unknown theme values.
- Explain why preference storage is not a substitute for secure credential storage.
SWIFT-42 — Why can a diffable cell keep old text when its item ID is unchanged?
A product's name changes while its ID stays the same. Applying another snapshot with the same IDs leaves a visible cell showing old content.
Optional follow-up questions
- Show how a model store and reconfigureItems work together.
- Explain why changing identity to force a refresh can disrupt selection or state.
SWIFT-43 — Why can a Published subscriber see a new value before the property changes?
A cart subscriber receives quantity 3, but reading the cart's quantity inside that callback still returns 1.
Optional follow-up questions
- Explain the initial value delivered when subscribing.
- Discuss why scheduling alone does not make several property changes atomic.
SWIFT-44 — How does a SwiftUI binding differ from a Published property publisher?
A profile editor needs both editable text and a stream of name changes. Compare the view wrapper's model-property projection with the model's Published-property projection.
Optional follow-up questions
- Identify which view owns the model and which child borrows it.
- Explain why creating a new observed model during rendering can reset its state.
SWIFT-45 — Which subject should represent a one-time event and which should represent current state?
A new dashboard subscribes after a Refresh tap and after connection status changes to connected. Choose what that late subscriber should receive.
Optional follow-up questions
- Predict each subject's delivery to a late subscriber.
- Explain what completion means for later values and subscriptions.
SWIFT-46 — Why can a retained Combine subscription keep its owner alive?
A banner model retains its cancellation token, and the subscription callback strongly captures that same model.
Optional follow-up questions
- Draw the ownership links and compare weak capture with the assign variants.
- Decide who ends observation when the screen stops needing updates.
SWIFT-47 — What do subscribe(on:) and receive(on:) each control?
A network publisher schedules subscription on a worker queue and then updates an observable UI model in its subscriber.
Optional follow-up questions
- Place decoding and UI publication boundaries explicitly.
- Distinguish main-queue delivery from compiler-checked actor isolation.
SWIFT-48 — Why does combineLatest suit form validation better than zip?
A password form uses zip to combine password and confirmation changes. Editing only one field sometimes leaves the Save button unchanged.
Optional follow-up questions
- Explain when combineLatest can produce its first result.
- Avoid rereading Published properties during their pre-write callbacks.
SWIFT-49 — How do Future and Deferred differ in when they start work?
An export Future is constructed before Export is tapped, and a second subscriber later receives the same result without starting another export.
Optional follow-up questions
- Decide whether subscribers should share an operation or start independent attempts.
- Explain how subscription cancellation relates to the underlying export's cancellation support.
SWIFT-50 — Where should error recovery go so later Submit taps still work?
A form catches an error after flattening request publishers from Submit taps. The first failure displays feedback, but later taps no longer start requests.
Optional follow-up questions
- Place retry and catch at the appropriate scope.
- Define what happens to taps during an active submission and to uncertain server outcomes.
SWIFT-51 — Do two ordinary await calls run concurrently?
A dashboard loads a display name and an unread count independently, but its function awaits one call before starting the other.
Optional follow-up questions
- Compare sequential calls with separate async-let children.
- Describe a controlled test that proves whether both operations started before either completed.
SWIFT-52 — Who handles failure and cancellation for a Task started by a button?
An Export button discards a throwing Task's handle. Errors disappear, repeated taps create multiple exports, and leaving the screen does not stop work.
Optional follow-up questions
- Compare awaiting a throwing handle with catching errors inside the owned task.
- Protect a newer operation's loading state from an older task's cleanup.
SWIFT-53 — How can a task group limit active requests while preserving input order?
A catalog needs results for 200 IDs, but the service should have no more than four requests active at once. Responses may finish out of order.
Optional follow-up questions
- Define error and cancellation behavior for unfinished requests.
- Explain why limiting active work does not make the whole result collection use constant memory.
SWIFT-54 — Why can a refresh spinner finish before the loading operation does?
A list starts a nested Task inside refreshable. Its spinner disappears immediately, and an older initial-load error can replace a successful manual refresh.
Optional follow-up questions
- Preserve useful rows on failure and distinguish cancellation from an error.
- Define which operation may update loading state after requests overlap.
SWIFT-55 — How can a form edit one shared Observable draft without duplicating state?
A shipping form edits city and postal code in one child while another view displays validation. A proposed design duplicates the fields and synchronizes them with callbacks.
Optional follow-up questions
- Identify where the draft is created and injected.
- Explain how required environment injection and country-specific validation affect previews and real addresses.
SWIFT-56 — Does async iteration over a publisher guarantee that every value is retained?
A download-progress subject emits a burst while its asynchronous consumer is busy rendering an earlier value. Decide which values the screen actually needs.
Optional follow-up questions
- Establish subscription readiness before the first emission.
- Define bounded buffering, subscription cleanup, and a different contract for lossless business events.
SWIFT-57 — Why should a countdown calculate from an expiry date rather than count timer events?
A verification-code countdown decrements once per timer event and becomes inaccurate after heavy UI work or time in the background.
Optional follow-up questions
- Compare a stable Timer publisher with a view-owned cancellable sleep loop.
- Explain disappearance, scene activation, and the difference between display time and server-enforced expiry.
SWIFT-58 — Does creating a MainActor Task wait for its UI update to finish?
Checkout preparation schedules one MainActor Task for loading feedback and another for navigation, then returns before its caller can rely on the final route.
Optional follow-up questions
- Compare an awaited MainActor.run with making the whole orchestration method MainActor-isolated.
- Prevent older or cancelled requests from publishing a destination.
Advanced questionnaire answers
Use these as discussion rubrics: a good answer explains the failure mechanism, offers a proportionate correction, and names a test or observable outcome. Multiple designs can be valid when their ownership and consistency policies are explicit.
SWIFT-01 — Answer
Short answer: Yes. A computed setter runs your own logic rather than storing the assigned value automatically. Here it uses the old tax to calculate a new subtotal, so reading the total again produces a different amount; keep one authoritative amount and define how the others are derived.
Detailed explanation:
Illustrative correction: keep one stored amount and derive the rest; this integer example deliberately rounds tax down and bounds input to avoid overflow.
struct Invoice {
let subtotalCents: Int
var taxCents: Int { subtotalCents / 10 }
var totalCents: Int { subtotalCents + taxCents }
init(subtotalCents: Int) {
precondition((0...Int.max / 2).contains(subtotalCents))
self.subtotalCents = subtotalCents
}
}The output is 2100 210 2310. The setter reads the old tax of 100, assigns a new subtotal of 2100, and the next getter recomputes tax as 210. Computed properties execute accessors rather than storing an automatic cached result. A writable projection needs a coherent inverse and an explicit rounding policy; changing one derived field while using another old derived value violates that relationship.
Prefer a single canonical subtotal and a read-only total. If users enter tax-inclusive totals, expose a named operation that applies the agreed tax and rounding rules, rather than promising that this setter preserves an impossible or ambiguous integer relationship. Add boundary tests for rounding, zero, negative input, and overflow. Swift properties
SWIFT-02 — Answer
Short answer: No. Restricting outside assignment does not validate the wallet's own methods. A withdrawal must reject zero or negative amounts and amounts greater than the balance before changing state; otherwise a negative withdrawal can increase the balance.
Detailed explanation:
withdraw(-100) increases the balance. private(set) restricts outside assignment but does not make the type's own methods valid. The domain operation must enforce positive amounts and sufficient funds before mutation.
struct Wallet {
enum WithdrawalError: Error { case invalidAmount, insufficientFunds }
private(set) var balanceCents = 1_000
mutating func withdraw(_ cents: Int) throws {
guard cents > 0 else { throw WithdrawalError.invalidAmount }
guard cents <= balanceCents else {
throw WithdrawalError.insufficientFunds
}
balanceCents -= cents
}
}The initial balance is nonnegative and successful withdrawals preserve that invariant. Test zero, negative, exact-balance, and excessive withdrawals, including that failure leaves state unchanged. Concurrent access to a shared wallet needs separate isolation; access control is not synchronization. Swift access control
SWIFT-03 — Answer
Short answer: Overloading chooses between different function signatures using the types known at compile time. Overriding lets a subclass replace an inherited method, so a call can use the object's runtime class. Changing a reference from let to var does not change those dispatch rules.
Detailed explanation:
Illustrative member contract: a caller accepting the base type still reaches the subclass's override, without depending on overload selection.
class Screen {
func title() -> String { "Screen" }
}
final class PaymentScreen: Screen {
override func title() -> String { "Payment" }
}
func label(for screen: Screen) -> String { screen.title() }
assert(label(for: PaymentScreen()) == "Payment")The outputs are base overload, Payment, and payment overload. The compiler selects an overload using the statically available argument type. screen is declared as Screen, so its describe call selects the base overload. Calling an overridable class method uses dynamic dispatch and reaches PaymentScreen.title().
let controls reassignment of the reference; it does not select static versus dynamic dispatch. Overloading provides different callable signatures; overriding specializes an inherited implementation under the same method contract. Neither mechanism alone proves substitutability: a subclass that changes preconditions or violates promised results can still break callers. Swift inheritance and overriding
SWIFT-04 — Answer
Short answer: The method is declared only in the protocol extension, so it is not a requirement that conforming types can replace through the protocol's contract. Declare the method in the protocol itself when callers using a generic constraint or protocol value must reach the conformer's implementation.
Detailed explanation:
The outputs are payment, default, and default. With no label() requirement, the generic and existential contexts resolve the extension member from their protocol constraint. The concrete struct's same-named method is visible to a concrete call but is not an override of a requirement.
protocol Labelled {
func label() -> String
}
extension Labelled {
func label() -> String { "default" }
}With this declaration and the same Payment implementation, all three calls produce payment. The extension supplies a default implementation for a protocol requirement, and conformance dispatch can select the conformer's witness. Ask separately about class inheritance and inherited conformances; they introduce additional dispatch cases. Swift protocol extensions
SWIFT-05 — Answer
Short answer: The owner retains its callback, and the callback retains the owner, creating a strong reference cycle. Removing the outside reference cannot break that cycle. Use a weak capture when the callback may outlive the owner, or clear the callback at a deliberate lifecycle boundary.
Detailed explanation:
For the definition and purpose of Automatic Reference Counting, start with the worked ARC explanation and ownership examples.
Editor → onSave closure → Editor is a strong cycle. Removing the external reference does not release the cycle, so deinit does not run. One repair is:
func configure() {
onSave = { [weak self] in
guard let self else { return }
print(self.title)
}
}Clearing a one-shot callback after invocation or at an explicit lifecycle boundary can also break ownership and release resources. A weak capture is appropriate when the callback may outlive its owner and should do nothing afterward. unowned assumes the object still exists when used; a violated assumption can trap. Explain whether losing the callback's action is acceptable instead of applying weak captures mechanically. Swift ARC and closure cycles
SWIFT-06 — Answer
Short answer: Yes. Turning a weak reference into a strong reference before a long-running loop keeps the owner alive across the loop's waits. Limit that strong reference to the work for one event, and explicitly stop observation when the screen or feature no longer needs it.
Detailed explanation:
Promoting weak self before the loop retains it across every suspended iteration. A stream that never terminates can therefore keep the model alive; relying only on its deinit to cancel creates a lifecycle dependency that may never resolve. Stop the previous task before starting another and expose explicit cancellation when the observation scope ends.
func start(events: AsyncStream<Int>) {
task?.cancel()
task = Task { [weak self] in
for await value in events {
guard !Task.isCancelled else { return }
guard let self else { return }
self.latest = value
}
}
}
func stop() {
task?.cancel()
task = nil
}Here the strong reference is scoped to one iteration rather than the next wait. The sequence must also cooperate with cancellation and clean up its producer. Explicit stopping remains useful even without a permanent ownership cycle. Compare ARC ownership and task lifetime. Swift task cancellation
SWIFT-07 — Answer
Short answer: A capture list captures the value available when the closure is created. Capturing an integer preserves that integer, but capturing a class reference still points to the same object, so later changes to the object remain visible. It does not create a deep copy or make shared state thread-safe.
Detailed explanation:
For a stable display snapshot, capture the value rather than the mutable object. This illustrative example is sequential.
final class Box { var count = 1 }
let box = Box()
let renderSnapshot = { [count = box.count] in String(count) }
box.count = 2
assert(renderSnapshot() == "1")
assert(box.count == 2)The closure prints 1 2, followed by the outer 2. [count] captures the integer value at closure creation. [box] captures the reference value; the object is still shared, so its later mutation is visible. Without [count], an ordinary escaping closure over the local mutable binding observes subsequent changes to that captured binding.
This is a sequential example. Capture syntax does not make shared reference state thread-safe, and moving the closure into concurrent work requires appropriate isolation and sendability. A capture list controls ownership/value capture; it does not deep-copy arbitrary object graphs. Swift closure captures
SWIFT-08 — Answer
Short answer: The outer operation occupies the serial queue while waiting for an inner operation on that same queue. The inner operation cannot start until the outer one finishes, so neither can make progress. Call an already-isolated helper directly or redesign the boundary to avoid that synchronous wait.
Detailed explanation:
Illustrative queue-owned work calls its synchronous helper directly after entering the queue, avoiding a nested synchronous dispatch.
import Dispatch
let storageQueue = DispatchQueue(label: "report.storage")
func formatOnStorageQueue(_ values: [Int]) -> String {
dispatchPrecondition(condition: .onQueue(storageQueue))
return values.map(String.init).joined(separator: ",")
}
storageQueue.async {
print(formatOnStorageQueue([3, 5, 8]))
}The outer block occupies a serial queue while synchronously waiting for another block on the same queue. That inner block cannot proceed until the outer finishes: a wait cycle. Dispatch may detect this and trap rather than hang; neither is valid program behavior. A serial queue guarantees ordered execution, not a private permanent thread.
Remove the nested sync by making the isolated operation directly callable inside the existing queue context, or expose an async API/actor that owns the state. Dispatching asynchronously changes ordering and result delivery, so the API contract must reflect that. Main-queue synchronous self-dispatch has the same fundamental issue. Do not block Swift's cooperative executor with semaphores while waiting for future async work. DispatchQueue.sync documentation-3segw)
🟦 A diagnostic boundary for callers outside a queue — illustrative:
func readFromOutside<T>(
on queue: DispatchQueue,
_ read: () throws -> T
) rethrows -> T {
dispatchPrecondition(condition: .notOnQueue(queue))
return try queue.sync(execute: read)
}The precondition exposes a violated entry contract; it does not repair a cycle or establish that the whole program is deadlock-free. Queue-internal code uses the direct helper above. External synchronous callers must also prove they hold no resource needed by the queue. Prefer an async boundary when that ownership proof is difficult. Test both entry contracts with controlled execution order rather than sleeps. Compare the full deadlock catalog and corrected patterns, including shared target queues and task-completion cycles. Apple queue preconditions)
SWIFT-09 — Answer
Short answer: Each increment reads and writes shared mutable state without synchronization, so concurrent increments can interfere with one another. Give the counter one actor owner or protect every access with the same lock. Declaring unchecked Sendable does not add either protection; it only makes the programmer responsible for safety.
Detailed explanation:
Illustrative actor ownership makes each increment an isolated operation; await completion before reading the total.
actor Counter {
private var value = 0
func increment() { value += 1 }
func total() -> Int { value }
}
let counter = Counter()
await withTaskGroup(of: Void.self) { group in
for _ in 0..<100 { group.addTask { await counter.increment() } }
}
let total = await counter.total()
assert(total == 100)value += 1 is a read-modify-write on shared memory with no synchronization; iterations can overlap. The final read occurs after concurrentPerform returns, but that does not repair races among the increments. Swift 6 should reject unsafe non-Sendable captures or isolated access under relevant settings. @unchecked Sendable merely transfers responsibility to the programmer.
An actor can own the counter and expose isolated increments; a lock can protect every access and the complete increment as one critical section. Neither design should expose the underlying mutable box. Check strict concurrency diagnostics, use Thread Sanitizer for applicable legacy code, and test exact totals and cancellation behavior under controlled schedules. Passing one stress run cannot prove race freedom. Swift data-race safety
SWIFT-10 — Answer
Short answer: MainActor prevents simultaneous access to its isolated state, but it does not make network responses finish in request order. An old search can resume later and overwrite the newest result. Give each request an identity and publish only if that identity is still current.
Detailed explanation:
MainActor serializes accesses, but an earlier search can resume after a later search and overwrite newer results. This is a logical ordering race without simultaneous unsynchronized memory access. Assign a generation when each request begins, then publish only if it is still current. A query-string check alone misses repeated queries such as A → B → A.
// Add inside SearchModel:
private var generation = 0
func search(_ query: String) async throws {
generation += 1
let requestGeneration = generation
let loaded = try await service.results(for: query)
try Task.checkCancellation()
guard requestGeneration == generation else { return }
results = loaded
}Replace the original method. Keep the guard and assignment in one uninterrupted actor-isolated segment. A fake service with manually resumed continuations can finish B before A and assert that B remains visible. Swift isolation and suspension
SWIFT-11 — Answer
Short answer: Yes. While an actor waits for an asynchronous operation, another task may run and change its state. A balance check made before the wait can therefore be outdated afterward; recheck the relevant state or reserve funds before waiting, with a clear failure and rollback policy.
Detailed explanation:
An illustrative local reservation happens before suspension. The orchestration layer later commits the reservation or releases it on failure; remote reconciliation still needs its own protocol.
actor Funds {
private var available = 100
private var reservations: [UUID: Int] = [:]
func reserve(_ amount: Int) -> UUID? {
guard amount > 0, amount <= available else { return nil }
let id = UUID()
available -= amount
reservations[id] = amount
return id
}
func finish(_ id: UUID, succeeded: Bool) {
guard let amount = reservations.removeValue(forKey: id) else { return }
if !succeeded { available += amount }
}
}A checks 100 and suspends; B checks 100 and suspends; A resumes and reduces it to 20; B resumes and reduces it to −60. An actor protects accesses, but its whole async method is not one indivisible transaction. Other actor work can interleave at suspension points.
Rechecking after authorization protects the local balance but may leave an external authorization that needs reversal. Reserving funds before suspension preserves the local invariant; failures must release the reservation through a defined state transition. Use operation IDs and explicit states when cancellation, retries, or duplicate responses can occur. An actor cannot make a remote debit atomic with local memory or ensure server idempotency. Test the interleaving using a controlled authorization dependency. SE-0306: actor reentrancy
SWIFT-12 — Answer
Short answer: A shared task slot can be replaced while an older task is waiting. If the older task then clears that slot without checking ownership, it removes the newer task's record. Give each refresh an identity and allow cleanup only when the stored identity still belongs to that refresh.
Detailed explanation:
Illustrative replacement fragment inside the actor's token method; inFlight now stores a generation/task tuple and nextGeneration is actor-owned.
nextGeneration += 1
let generation = nextGeneration
let task = Task { try await refresh() }
inFlight = (generation: generation, task: task)
defer {
if inFlight?.generation == generation { inFlight = nil }
}
return try await task.valueExisting callers join inFlight.task; invalidation advances identity and clears the slot. This fragment fixes slot cleanup, leaving the documented result-freshness policy explicit.
A's deferred cleanup clears the shared slot even if it now contains B. Assign each created task a monotonically increasing generation and store (generation, task). Cleanup may clear the slot only if its generation still matches. Invalidation should advance the generation and detach or cancel the old slot according to policy.
Slot identity and result freshness are separate: callers awaiting A may still receive A's result unless the method checks invalidation before returning it. State whether invalidation makes existing callers fail, retry, or accept their original snapshot. One caller's cancellation should not automatically destroy work still needed by other callers; reference counts or another explicit owner may be required. Exercise A-start → invalidate → B-start → A-finish → C-start, and confirm C joins B. SE-0306: interleaving execution
SWIFT-13 — Answer
Short answer: No. Awaiting a detached task reads its result, but does not turn it into a structured child or automatically propagate caller cancellation to it. For one operation, call the async function directly; use structured children for related concurrent work, or explicitly manage an independent task's cancellation.
Detailed explanation:
For a single operation, call the service in the existing task. This illustrative function assumes download cooperates with cancellation.
func load() async throws -> String {
try Task.checkCancellation()
let value = try await download()
try Task.checkCancellation()
return value
}Awaiting a detached task's value does not make it a structured child. Caller cancellation is not automatically propagated to that task, and dropping its handle does not stop it. A direct try await download() retains the current task's cancellation context and is the simplest design for one operation. async let or a task group creates structured children when parallel work is needed.
Detached work needs a deliberate owner, sendable captures, error handling, and an explicit cancellation policy. If bridging to an unstructured worker is necessary, connect cancellation with a handler and ensure the worker's operation cooperates. Awaiting a cancelled worker can still take time; cancellation is not forced thread termination. SE-0304: unstructured and detached tasks
SWIFT-14 — Answer
Short answer: No. Under strict concurrency checking, an unprotected mutable class cannot satisfy checked Sendable conformance. Sendable marks values safe to cross concurrency boundaries; it does not add synchronization, and making a reference constant does not freeze the object.
Detailed explanation:
A normal final class with a mutable stored property does not satisfy checked Sendable conformance without suitable isolation. A let class reference prevents replacement of the reference, while its mutable object state remains mutable.
struct UserSnapshot: Sendable {
let displayName: String
}
actor UserDraftStore {
private var displayName = ""
func rename(to name: String) { displayName = name }
func snapshot() -> UserSnapshot {
UserSnapshot(displayName: displayName)
}
}Sendable concerns safe transfer/sharing across concurrency domains; it does not guarantee business transaction atomicity, freshness, request ordering, or deterministic execution. Value types still require all stored contents to meet the relevant safety requirements. Choose snapshots for independent values and actors for shared mutable ownership. SE-0302: Sendable
SWIFT-15 — Answer
Short answer: No. With Swift 6.2's NonisolatedNonsendingByDefault feature enabled, a nonisolated async function normally stays on the caller's actor, so synchronous CPU work can still delay the UI. Use an explicit concurrent execution boundary when needed, and check the project's actual compiler and isolation settings.
Detailed explanation:
With NonisolatedNonsendingByDefault enabled, this nonisolated async helper stays on the caller's actor by default. Called from MainActor, its synchronous CPU loop can therefore block UI progress. With that feature disabled, historical nonisolated async execution switches away from the actor. async alone does not mean background CPU execution.
For an explicit Swift 6.2+ boundary:
@concurrent
func checksum(_ bytes: [UInt8]) async -> UInt64 {
bytes.reduce(0) { ($0 &* 31) &+ UInt64($1) }
}Use this to replace the helper. It selects concurrent execution away from the caller's actor, not a dedicated thread. Language mode controls language checking; default actor isolation affects inferred declaration isolation; the upcoming feature changes nonisolated async semantics. Record these settings when reproducing a diagnostic. Profile frame hitches and CPU time with a representative input. SE-0461, SE-0466
SWIFT-16 — Answer
Short answer: In Swift 6.4, a defer body in an async context may await cleanup before the enclosing scope finishes exiting. Cleanup blocks still run in reverse registration order. This does not guarantee that cleanup succeeds or finishes promptly, so define how it handles cancellation, failures, and time limits.
Detailed explanation:
Swift 6.4+ illustrative ordering: the later buffer cleanup finishes before the earlier session cleanup. These dependencies must implement the chosen bounded cancellation/error policy.
func uploadWithCleanup() async throws {
defer { await closeSession() }
defer { await flushBufferedBytes() }
try Task.checkCancellation()
try await uploadPayload()
}closeSession, flushBufferedBytes, and uploadPayload are application dependencies; the snippet demonstrates scope-exit order, not an infallible cleanup guarantee.
Swift 6.4 was released on September 15, 2026; 6.4.1 followed on October 13. Its async defer support is released functionality, not a preview claim. The function awaits close() during scope exit before returning or propagating an error. Multiple defers remain last-in, first-out. The enclosing context must support async work; synchronous cleanup rules still apply in a synchronous function, and pre-6.4 compilers do not accept this extension. Swift 6.4 release, 6.4.1 announcement, SE-0493
Cancellation still cooperates with the cleanup implementation. Swift 6.4's withTaskCancellationShield can protect a deliberately bounded essential cleanup operation from enclosing task cancellation. It does not make a failing service infallible, prevent process termination, or justify unbounded cleanup that delays exit indefinitely. Define timeout/error policy and observe failures rather than silently using try? for critical cleanup. Cancellation shields in the release notes
SWIFT-17 — Answer
Short answer: A structured task group cannot finish its scope while its child tasks are still running. After accepting a result, request cancellation of the remaining children, but remember that they must cooperate before the scope can exit. Also decide whether the operation needs the first completion or the first successful result.
Detailed explanation:
Illustrative first-completion policy: cancellation is requested on every exit, including error and empty-input paths.
func firstResponse(
_ requests: [@Sendable () async throws -> String]
) async throws -> String? {
try await withThrowingTaskGroup(of: String.self) { group in
for request in requests { group.addTask { try await request() } }
defer { group.cancelAll() }
return try await group.next()
}
}A normal task-group scope waits for all children; returning one result does not automatically cancel the others. Add defer { group.cancelAll() } after creating the children and before next() so normal and throwing exits request cancellation. The scope still waits for children to finish, so operations must cooperate; cancellation cannot force an arbitrary blocked API to return.
The shown policy returns or throws the first completed result, which may be an error. “First success” needs a different policy that collects failures and continues until success or exhaustion. State what happens for an empty input and for all failures. Use controlled request completions and a cancellation probe; do not assert a precise latency from arbitrary sleeps. SE-0304: task-group scope and cancellation
SWIFT-18 — Answer
Short answer: When a view owns an Observable model, store that model in State so SwiftUI preserves its identity across ordinary view updates. Observation tracks which properties are read, but does not create persistent ownership by itself. A child can borrow the model and use Bindable when it needs editable property bindings.
Detailed explanation:
A plain stored reference can be replaced when the view value is reconstructed. Observation tracks reads of model properties but does not by itself establish SwiftUI-owned persistent storage.
struct ProfileEditor: View {
@State private var draft = ProfileDraft()
var body: some View {
@Bindable var editableDraft = draft
TextField("Name", text: $editableDraft.name)
}
}The owner keeps its @Observable instance in @State. A child can receive the instance as a normal property to read observed values; @Bindable supplies bindings when needed. In the older ObservableObject model, the owner typically uses @StateObject, while an injected observer uses @ObservedObject. A change in view identity can reset owned state even with the correct wrapper. Test parent updates separately from intentional identity changes. Apple's Observation migration guide
SWIFT-19 — Answer
Short answer: An array position identifies a location, not a particular item. When the list changes order, SwiftUI can attach a row's existing state to the wrong item. Use an ID that stays with the item across insertion and reordering; generating a new UUID on every read also breaks that stability.
Detailed explanation:
Array indices identify positions, so inserting or moving elements can associate an existing row's local state with a different domain item. Use a stable ID stored with each item, independent of position and editable display text.
struct NameItem: Identifiable {
let id: UUID
var name: String
}
// Inside NamesView, with items: [NameItem]:
List(items) { item in
EditableRow(name: item.name)
}Generate IDs once when creating domain items or use server IDs. var id: UUID { UUID() } changes on every read and destroys stable identity. Toggle one row, insert an item before it, then reorder; assert that the same item remains expanded. If expansion must outlive row removal, own it in a parent/store keyed by the item ID. Demystify SwiftUI: identity and lifetime
SWIFT-20 — Answer
Short answer: A binding should immediately read and update the same local source of truth, so the control reflects the user's choice. Saving asynchronously inside the setter can leave the control stale and let older saves overwrite newer intent. Let an owned model operation handle saving, errors, and which completion is still current.
Detailed explanation:
The getter does not reflect the toggle until the asynchronous save completes; repeated taps can race, and an old completion can overwrite a newer choice. A binding should synchronously update the chosen local source of truth. Have a model handle persistence through an explicit operation with owned task/error state.
// Illustrative model-backed control:
Toggle("Notifications", isOn: Binding(
get: { model.notificationsEnabled },
set: { model.setNotificationsEnabled($0) }
))For optimistic updates, the method updates local state immediately, assigns an operation generation, and publishes save/failure state only for the current operation. Choose rollback, retry, or an unsaved indicator. Client cancellation does not undo a server write: use serialized saves, server versions, or another explicit consistency contract. Test rapid true → false input with reversed completion order and a failed save. SwiftUI Binding
SWIFT-21 — Answer
Short answer: Use small route values, such as an item ID and destination kind, with one owner for the navigation path. A restored route should resolve current data and authorization before showing its screen. Persisting view instances or mutable objects makes restoration harder to validate and maintain.
Detailed explanation:
Use small route values and one path owner. This illustrative skeleton assumes the destination views are supplied by the application:
enum Route: Hashable, Codable {
case product(id: String)
case checkout(cartID: String)
}
@State private var path: [Route] = []
// Inside the root view body:
NavigationStack(path: $path) {
ProductListView()
.navigationDestination(for: Route.self) { route in
switch route {
case .product(let id):
ProductDetailView(productID: id)
case .checkout(let cartID):
CheckoutView(cartID: cartID)
}
}
}Persist validated route IDs rather than view instances, secrets, or mutable object graphs. Resolve current data and authorization before showing a restored destination; handle deleted items and expired sessions. A deep link should produce one intentional path transition. Competing owners can overwrite pushes or restores. Test cold-start restoration, back navigation, unavailable IDs, and repeated links. Apple NavigationStack documentation
SWIFT-22 — Answer
Short answer: Two independent flags can request incompatible sheets at the same time or request an editor without its item. One optional route represents either no sheet or exactly one valid destination with its required data. The route's owner can then define dismissal and replacement behavior explicitly.
Detailed explanation:
Two booleans admit both sheets being requested at once, including editor-without-document states. One optional route encodes one presentation and its required data.
enum SheetRoute: Identifiable {
case editor(documentID: String)
case help
var id: String {
switch self {
case .editor(let id): return "editor:\(id)"
case .help: return "help"
}
}
}
@State private var sheet: SheetRoute?
// Attach to the presentation owner:
.sheet(item: $sheet) { route in
switch route {
case .editor(let id): DocumentEditor(documentID: id)
case .help: HelpView()
}
}The owner updates the route; dismissal updates its binding. Use interactive-dismissal controls and a discard confirmation when product requirements demand preserving unsaved work. Decide whether a new route replaces, queues, or is rejected while editing. Validate a document before requesting its editor. Apple sheet(item:) documentation)
SWIFT-23 — Answer
Short answer: If both fields use the same focus value, setting that value does not identify which field should receive focus. Give each field its own value, such as email or password, so programmatic movement is unambiguous. Delayed validation should not steal focus from a newer user interaction.
Detailed explanation:
The same focus value bound to different controls is ambiguous for programmatic focus. Use distinct values:
enum Field: Hashable { case email, password }
@FocusState private var focusedField: Field?
// Inside the form:
TextField("Email", text: $email)
.focused($focusedField, equals: .email)
.submitLabel(.next)
.onSubmit { focusedField = .password }
SecureField("Password", text: $password)
.focused($focusedField, equals: .password)
.submitLabel(.go)
.onSubmit { validateAndSubmit() }Validation should focus a relevant invalid field only when the form is still active and the response belongs to the current submission. Record the submitted values/generation and user focus changes; do not steal focus from a newer interaction. Clear focus deliberately with nil. Test keyboard submission, empty fields, and a delayed old validation response. Apple FocusState: avoid ambiguous focus bindings
SWIFT-24 — Answer
Short answer: No. Changing a task's ID requests cancellation, but an old operation may still complete because cancellation is cooperative. Capture the request input, publish only the current uncancelled request's result, and handle cancellation separately from a user-visible failure.
Detailed explanation:
Illustrative MainActor model-method fragment: generation, results, and the service belong to the model; publication follows a cancellation and identity check without another suspension.
generation += 1
let requestGeneration = generation
let requestedQuery = query
do {
let items = try await service.results(for: requestedQuery)
try Task.checkCancellation()
guard generation == requestGeneration else { return }
results = items
} catch {
guard !Task.isCancelled, generation == requestGeneration else { return }
errorMessage = "Search failed"
}Changing the ID cancels and restarts the view task; disappearing also triggers cancellation. Cancellation is cooperative, so an older operation can still return a value. Capture the input before awaiting, check cancellation before publishing, and use model-owned request generations when multiple callers/retries can overlap. The acceptance guard and publication must share one MainActor segment.
Handle CancellationError without displaying a failure. Services may use other cancellation errors, so also inspect task cancellation before publishing errors. Clear loading/error state only for the active generation, including in cleanup. A view task is tied to its view lifetime; a nested unstructured task needs its own ownership policy. Test a service that intentionally completes after cancellation. Apple View.task documentation)
SWIFT-25 — Answer
Short answer: A Button tells accessibility tools and input systems that the element is an action, while a tap gesture on text provides less built-in control behavior. Pair it with readable text, flexible sizing, and a clear accessible name. Then check activation, focus, and loading or disabled feedback with the relevant assistive technologies.
Detailed explanation:
Use a Button so the action participates in control semantics. Prefer a semantic text style and a flexible layout with an adequate hit region:
Button(action: submitPayment) {
Text("Pay now")
.font(.headline)
.frame(maxWidth: .infinity, minHeight: 44)
.padding(.horizontal)
}
.buttonStyle(.borderedProminent)
.disabled(isSubmitting)This illustrative control needs surrounding product state. Preserve a clear accessible name, announce meaningful loading/result changes, prevent accidental duplicate payment requests, and retain an idempotency contract in the service. Verify large text without clipping, longer translations, focus order, VoiceOver activation, external keyboard, and reduced motion. A minimum height helps touch targets; it does not by itself prove accessibility. Apple SwiftUI accessibility guidance
SWIFT-26 — Answer
Short answer: SwiftUI may read a computed property repeatedly, and the getter does not automatically cache its result. Starting a refresh there can create repeated side effects and overlapping tasks during rendering. Put asynchronous work in an explicitly owned operation, and prepare expensive derived values when their inputs change.
Detailed explanation:
Illustrative view fragment: a model prepares visibleRecords when input changes; rendering only reads that projection and stable record IDs.
var body: some View {
List(model.visibleRecords) { record in
Text(record.name)
}
.task(id: query) {
await model.refreshAndProject(query: query)
}
}The model operation owns cancellation, freshness, errors, and any measured expensive transformation. The getter no longer starts work or generates identity.
SwiftUI can evaluate view descriptions repeatedly. A getter can run each time it is read and does not automatically memoize sorting/filtering. Starting refresh inside that getter introduces uncontrolled side effects, overlapping tasks, and potentially update loops. Duplicate names also make id: \.self unsuitable for stable list identity.
Keep rendering descriptive. Put refresh in a deliberately owned .task/model operation and cancel or invalidate stale work. Compute large derived projections when their inputs change, using stable item IDs, clear ownership, and a bounded cache only when measurements justify it. If work moves across an actor boundary, pass safe snapshots and verify freshness before publishing. Profile recomputation counts and frame hitches, then test rapidly changing query/data with controlled completions. Demystify SwiftUI performance
SWIFT-27 — Answer
Short answer: A checked continuation must receive exactly one terminal result; it does not automatically ignore duplicate callbacks. Coordinate callback completion and cancellation through one synchronized state transition, so only one can resume the continuation. If the SDK cannot cancel, the adapter may stop waiting while still ignoring its later result.
Detailed explanation:
A checked continuation must be resumed exactly once; it diagnoses misuse rather than deduplicating callbacks or automatically implementing cancellation. Put the continuation's terminal transition behind synchronization and resume outside the lock. Cancellation is another contender for that same terminal transition.
For a receipt screen using a non-cancellable legacy SDK, this complete example returns cancellation to the waiter and ignores a late callback. It does not claim to stop the SDK's underlying work. Synchronization.Mutex requires an SDK/deployment target supporting that API, such as iOS 18+.
import Foundation
import Synchronization
enum ReceiptFailure: Error { case unavailable }
struct LegacyReceipts: Sendable {
func load(_ completion: @escaping @Sendable
(Result<String, ReceiptFailure>) -> Void) {
DispatchQueue.global().async {
completion(.success("receipt-42"))
completion(.success("duplicate callback"))
}
}
}
private enum ReceiptWait: Sendable {
case waiting
case suspended(CheckedContinuation<String, any Error>)
case finished
}
func receipt(from sdk: LegacyReceipts) async throws -> String {
let state = Mutex(ReceiptWait.waiting)
let result = try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation {
(continuation: CheckedContinuation<String, any Error>) in
let shouldStart = state.withLock { state in
guard case .waiting = state else { return false }
state = .suspended(continuation)
return true
}
guard shouldStart else {
continuation.resume(throwing: CancellationError())
return
}
sdk.load { result in
let waiter = state.withLock { state in
guard case .suspended(let waiter) = state else {
return nil as CheckedContinuation<String, any Error>?
}
state = .finished
return waiter
}
waiter?.resume(with: result)
}
}
} onCancel: {
let waiter = state.withLock { state -> CheckedContinuation<String, any Error>? in
defer { state = .finished }
if case .suspended(let waiter) = state { return waiter }
return nil
}
waiter?.resume(throwing: CancellationError())
}
try Task.checkCancellation()
return result
}The lock is held only for a synchronous state transition; never across a suspension or while invoking foreign SDK code. Cancellation before registration marks the state finished; registration then resumes its own continuation with cancellation. Cancellation after registration takes the stored continuation. A callback that already won can still be followed by cancellation, so the final check protects publication.
Verify: use an injected callback source to deliver success twice, failure then success, cancellation before registration, and cancellation before a late success. Assert one observed completion and no continuation misuse. The shown duplicate callback is safe to exercise through this adapter; do not run an unguarded double-resume example. Prefer a native async SDK API when available; the extra state machine is the cost of repairing a legacy contract. SE-0300: continuation contracts, SE-0433: synchronous Mutex protection
SWIFT-28 — Answer
Short answer: No. AsyncStream’s yield does not wait for a slow reader. Its bounded buffers discard some values when full; when every event matters, use a delivery contract that can slow the producer instead.
Detailed explanation:
AsyncStream.Continuation.yield does not suspend the producer, so a bounded buffer limits queued elements by dropping values rather than applying backpressure. For a live chart, .bufferingNewest(1) preserves the latest pending reading; .bufferingOldest(1) preserves the oldest pending reading. Neither is suitable when every event must be processed.
This simulated sensor feed has an explicit producer handle. Its consumer stops it when leaving, including through break; stream termination also requests cancellation. The synchronous stop() method cancels work without blocking for its completion.
struct SensorFeed: Sendable {
let readings: AsyncStream<Int>
private let producer: Task<Void, Never>
static func start() -> SensorFeed {
let pair = AsyncStream<Int>.makeStream(
bufferingPolicy: .bufferingNewest(1)
)
let producer = Task {
defer { pair.continuation.finish() }
do {
for reading in 1...100 {
try Task.checkCancellation()
pair.continuation.yield(reading)
try await Task.sleep(for: .milliseconds(10))
}
} catch is CancellationError {
return
} catch {
assertionFailure("Unexpected simulation error: \(error)")
}
}
pair.continuation.onTermination = { _ in producer.cancel() }
return SensorFeed(readings: pair.stream, producer: producer)
}
func stop() { producer.cancel() }
}
func readFirstSensorValue() async -> Int? {
let feed = SensorFeed.start()
defer { feed.stop() }
for await reading in feed.readings {
return reading
}
return nil
}
func verifyNewestBuffer() async -> Bool {
let pair = AsyncStream<Int>.makeStream(
bufferingPolicy: .bufferingNewest(1)
)
pair.continuation.yield(1)
pair.continuation.yield(2)
pair.continuation.yield(3)
pair.continuation.finish()
var iterator = pair.stream.makeAsyncIterator()
return await iterator.next() == 3
}Do not assume that retaining a stream and breaking one loop immediately stops its upstream resource. An explicit feature/session owner makes that boundary clear. Real delegates, timers, or hardware adapters must stop the actual resource and handle any required actor hop in their termination path. If teardown must finish before returning, provide a separate async stop-and-join API.
Verify: verifyNewestBuffer() must return true without timing assumptions. Replace the policy with .bufferingOldest(1) and expect 1. Add a producer cancellation probe and verify both consumer cancellation and early return request stop. For payments or audit events, use a lossless channel with an actual backpressure contract or durable storage instead of dropping values. SE-0314: buffering, yield, and termination
SWIFT-29 — Answer
Short answer: When an error leaves the enclosing scope, unfinished async-let children are cancelled and awaited before that scope finishes exiting. The error is first observed when its child's result is awaited. Cancellation is cooperative, so a sibling doing unchecked CPU work can still delay the parent from returning the error.
Detailed explanation:
async let creates structured child tasks. An error is observed when that child's value is awaited; once an error causes the enclosing scope to exit, unfinished children are cancelled and awaited before exit completes. Cancellation is cooperative, so a sibling performing unchecked CPU work can still delay the thrown result.
A profile screen needs account details and a derived avatar signature. This example bounds each CPU segment, checks cancellation, and yields between segments. The fake request represents a failure; replace it with a cancellable networking dependency in an application.
enum ProfileFailure: Error { case signedOut }
struct ProfileScreenData: Sendable {
let displayName: String
let avatarSignature: UInt64
}
func accountName() async throws -> String {
try await Task.sleep(for: .milliseconds(5))
throw ProfileFailure.signedOut
}
@concurrent
func avatarSignature(_ bytes: [UInt8]) async throws -> UInt64 {
var signature: UInt64 = 0
for start in stride(from: 0, to: bytes.count, by: 1_024) {
try Task.checkCancellation()
let end = min(start + 1_024, bytes.count)
for byte in bytes[start..<end] {
signature = (signature &* 31) &+ UInt64(byte)
}
await Task.yield()
}
try Task.checkCancellation()
return signature
}
func loadProfile(bytes: [UInt8]) async throws -> ProfileScreenData {
async let name = accountName()
async let signature = avatarSignature(bytes)
let loadedName = try await name
let loadedSignature = try await signature
try Task.checkCancellation()
return ProfileScreenData(
displayName: loadedName,
avatarSignature: loadedSignature
)
}Await order is observable: if you await a slow child first, a fast failure in a different child can remain unobserved until you await it. Task.yield() offers other tasks an opportunity to run; it does not promise fairness, a specific thread, or cancellation by itself. The explicit checks throw on cancellation. Here @concurrent is an explicit Swift 6.2+ execution boundary, separate from the cancellation lesson.
Verify: use controllable fake operations to fail the account request after the avatar child starts. Observe that the avatar child sees cancellation before the parent finishes throwing. Reverse await order and explain the difference. Do not infer ordering from the sample's short sleep. Prefer async let for a fixed number of dependent results; use a task group when completion order or a dynamic task count is required. SE-0317: child lifetime and cancellation
SWIFT-30 — Answer
Short answer: Cancelling or timing out a request does not prove the server stopped processing it. Retrying the same logical payment with a new operation ID can create another charge. Preserve one operation ID and payload across permitted retries, stop retrying on cancellation, and rely on durable server-side deduplication and reconciliation.
Detailed explanation:
Cancellation or a timeout does not prove the server rolled back a mutation. Retrying with a fresh operation ID can charge again; retrying cancellation can continue work the user asked to stop. Reuse one ID and payload for one logical payment, retry only defined transient failures, and rely on server-side atomic deduplication for correctness.
This complete fake server commits the payment before losing the first response. A retry with the same key returns the existing receipt. Its dictionary models the server contract; production deduplication must be durable, atomically enforced, scoped to the correct customer/operation, and validate that a reused key carries the same request.
import Foundation
enum PaymentFailure: Error { case responseLost, invalidKeyReuse }
struct PaymentReceipt: Sendable, Equatable {
let id: UUID
let cents: Int
}
actor PaymentServer {
private var committed: [UUID: PaymentReceipt] = [:]
func charge(key: UUID, cents: Int) throws -> PaymentReceipt {
if let receipt = committed[key] {
guard receipt.cents == cents else {
throw PaymentFailure.invalidKeyReuse
}
return receipt
}
let receipt = PaymentReceipt(id: UUID(), cents: cents)
committed[key] = receipt
throw PaymentFailure.responseLost
}
func chargeCount() -> Int { committed.count }
}
func pay(server: PaymentServer, operationID: UUID,
cents: Int) async throws -> PaymentReceipt {
precondition(cents > 0)
for attempt in 0..<3 {
try Task.checkCancellation()
do {
let receipt = try await server.charge(
key: operationID, cents: cents
)
try Task.checkCancellation()
return receipt
} catch PaymentFailure.responseLost where attempt < 2 {
try Task.checkCancellation()
try await Task.sleep(for: .milliseconds(100 * (attempt + 1)))
}
}
preconditionFailure("The final attempt either returned or threw")
}
func verifyPaymentRetry() async throws -> Bool {
let server = PaymentServer()
let receipt = try await pay(
server: server, operationID: UUID(), cents: 2_500
)
let count = await server.chargeCount()
return receipt.cents == 2_500 && count == 1
}Cancellation after commit can deliberately produce no receipt at the caller even though a charge exists. Persist the logical operation ID before submission and reconcile its status after uncertain outcomes; do not tell the user that cancellation means “not charged.” A header named Idempotency-Key has no magical client-side guarantee unless the service implements its contract.
Verify: the fake loses its first response, yet verifyPaymentRetry() returns true and one charge exists. Reuse the ID with different cents and expect rejection. Cancel during backoff and verify no later attempt starts. Production retry policy should classify transport/status errors, respect server retry guidance, and use bounded jittered backoff; the fixed backoff here keeps the teaching example inspectable. RFC 9110 §9.2.2: retrying idempotent operations, AWS: idempotent API contracts and ambiguous retries
SWIFT-31 — Answer
Short answer: Usually no: if an application service owns the shared download, one screen should not cancel work that another screen still needs. The cancelled screen should reject the result for its own UI, while the service's owner controls shutdown. Sharing work and deciding who may cancel it are separate policies.
Detailed explanation:
The application-scoped catalog service owns the shared operation, so a screen cancelling its own wait must not cancel work still needed by another screen. Check caller cancellation before returning the shared result; give shutdown authority to the service's lifecycle owner. This policy allows a cancelled waiter to remain suspended until the shared operation completes.
For a catalog loaded once per application session, a retained task is also a cached result. This intentionally omits refresh and invalidation: those require their own generation/result-freshness policy, covered in SWIFT-12.
enum CatalogFailure: Error { case stopped }
struct Catalog: Sendable, Equatable {
let productNames: [String]
}
actor CatalogSession {
private let operation: Task<Catalog, any Error>
private var stopped = false
init(load: @escaping @Sendable () async throws -> Catalog) {
operation = Task { try await load() }
}
func value() async throws -> Catalog {
try Task.checkCancellation()
guard !stopped else { throw CatalogFailure.stopped }
let result = try await operation.value
try Task.checkCancellation()
guard !stopped else { throw CatalogFailure.stopped }
return result
}
func shutdown() {
stopped = true
operation.cancel()
}
}
func makeCatalogSession() -> CatalogSession {
CatalogSession {
try await Task.sleep(for: .milliseconds(50))
try Task.checkCancellation()
return Catalog(productNames: ["Notebook", "Pencil"])
}
}
@MainActor
final class CatalogScreenModel {
private(set) var productNames: [String] = []
func load(from session: CatalogSession) async throws {
let catalog = try await session.value()
try Task.checkCancellation()
productNames = catalog.productNames
}
}Task {} is unstructured here: merely awaiting its value does not propagate each waiter's cancellation into it. The service deliberately uses that independent lifetime and retains the handle. shutdown() requests cancellation and prevents later successful publication, but it does not force an uncooperative loader to finish. The application owner must call it when the session ends; dropping a handle is not a substitute.
Verify: start two callers using a manually controlled loader, cancel A, then complete the loader. A must throw cancellation, B must receive the catalog, and the loader must start once. Call shutdown before completion and verify a late success is rejected. If A must leave immediately, add a separately synchronized waiter-registration mechanism; if work should stop when the last waiter leaves, implement reference-counted ownership instead. SE-0304: unstructured tasks and cancellation
SWIFT-32 — Answer
Short answer: No. Copying a struct copies its stored class references, so the copies can still point to the same mutable object. For an edit form that supports cancellation, use independent value data or a deliberately defined snapshot, then commit changes explicitly instead of editing the shared saved model.
Detailed explanation:
The prompt prints Izmir: copying the struct copies its class reference, so both structs still point to the same AddressBox. A let binding prevents replacing that reference but does not freeze its referent. For a cancellable edit form, prefer a value-only draft and commit it explicitly.
This self-contained example separates the persisted value from the edit buffer. Mutating the edit buffer changes its copied ShippingAddress, so cancelling edits leaves the saved address alone.
struct ShippingAddress: Equatable, Sendable {
var city: String
var postalCode: String
}
struct AddressEditor: Sendable {
private(set) var saved: ShippingAddress
var draft: ShippingAddress
init(saved: ShippingAddress) {
self.saved = saved
self.draft = saved
}
mutating func save() {
saved = draft
}
mutating func cancel() {
draft = saved
}
}
func verifyAddressEditing() -> Bool {
let initial = ShippingAddress(city: "Ankara", postalCode: "06000")
var editor = AddressEditor(saved: initial)
editor.draft.city = "Izmir"
guard editor.saved.city == "Ankara" else { return false }
editor.cancel()
guard editor.draft == initial else { return false }
editor.draft.city = "Bursa"
editor.save()
return editor.saved.city == "Bursa" && initial.city == "Ankara"
}This is a value-isolation problem even on one thread; there is no need for concurrency to reproduce it. Nesting a mutable class inside a struct also does not make the class safe to share across actor boundaries. A checked Sendable conformance must account for the stored members and their isolation or immutability.
Verify: verifyAddressEditing() returns true; add a second editor from the same saved value and confirm independent edits. If reference identity is a real domain requirement, retain a shared actor/model and use explicit immutable snapshots for editing. Manual deep copies require a policy for every nested reference, identity, and cycle, so replacing a reference with a value is often simpler for small form data. Swift language guide: structures and classes, SE-0302: Sendable stored members
SWIFT-33 — Answer
Short answer: No, async property syntax does not create a cache; each access can run the getter again. If several uses need the same response, load one successful snapshot and reuse that value. A repository-wide cache needs additional rules for freshness, failures, invalidation, and concurrent callers.
Detailed explanation:
An async computed getter runs its getter body on each access; neither async nor property syntax creates a cache. If two reads must share one response, load an immutable snapshot explicitly and reuse that local value. A method such as loadLatestReceipt() often advertises remote work more clearly than a property.
In this purchase confirmation example, the server actor counts requests so the behavior is directly observable. renderReceiptTwice() performs two getter accesses, then shows the explicit one-load alternative. Cancellation propagates through the current task; no detached work is needed.
struct Receipt: Sendable, Equatable {
let number: String
}
actor ReceiptServer {
private var requestCount = 0
func fetchLatest() async throws -> Receipt {
try Task.checkCancellation()
requestCount += 1
let requestNumber = requestCount
try await Task.sleep(for: .milliseconds(1))
return Receipt(number: "R-\(requestNumber)")
}
func count() -> Int { requestCount }
}
struct ReceiptRepository: Sendable {
let server: ReceiptServer
var latestReceipt: Receipt {
get async throws {
try await server.fetchLatest()
}
}
func loadLatestReceipt() async throws -> Receipt {
try await server.fetchLatest()
}
}
func renderReceiptTwice() async throws -> Bool {
let server = ReceiptServer()
let repository = ReceiptRepository(server: server)
_ = try await repository.latestReceipt
_ = try await repository.latestReceipt
let snapshot = try await repository.loadLatestReceipt()
try Task.checkCancellation()
let header = snapshot.number
let footer = snapshot.number
let requests = await server.count()
return requests == 3 && header == footer
}The local snapshot caches one successful result only for this caller's scope; a failed load throws and stores nothing. It does not deduplicate simultaneous requests from other callers. A repository-wide cache additionally needs expiration, invalidation, error policy, and concurrent-load ownership. Do not silently add those policies behind a property because its spelling looks cheap.
Verify: renderReceiptTwice() returns true, with two getter requests plus one explicit load. Cancel during the simulated fetch and verify it throws instead of publishing a snapshot. To test failure deterministically, inject a server that throws and confirm no prior result is silently reused. Use effectful getters when an expensive/failable conceptual property is natural and documented; use methods when loading, refresh, or configuration is part of the action. SE-0310: effectful read-only properties
SWIFT-34 — Answer
Short answer: A task-local value belongs to task context rather than to a thread. Structured children and ordinary Task creation inherit that context, while a detached task starts independently. Pass a specific trace value explicitly when detached work needs it; inheriting context alone does not create structured lifetime or cancellation.
Detailed explanation:
Task-local bindings follow task context rather than a particular thread. Structured children and Task {} inherit the binding; Task.detached {} starts without it. Carry a specific immutable trace value explicitly when independent work really needs that context. Inheritance does not make Task {} structured or automatically link its cancellation lifetime.
A checkout trace should correlate child request logs without becoming a global mutable variable. This complete example compares inherited context, detached context, and deliberate propagation. The handles are retained and awaited so this demonstration does not abandon work.
enum CheckoutTrace {
@TaskLocal static var id: String?
}
func currentTrace() async -> String? {
CheckoutTrace.id
}
struct TraceComparison: Sendable {
let sameTask: String?
let structuredChild: String?
let inheritedTask: String?
let detachedTask: String?
let explicitlyPropagated: String?
}
func compareTraceContexts() async -> TraceComparison {
await CheckoutTrace.$id.withValue("checkout-42") {
let same = CheckoutTrace.id
async let child = currentTrace()
let inherited = Task { CheckoutTrace.id }
let detached = Task.detached { CheckoutTrace.id }
let capturedID = CheckoutTrace.id
let propagated = Task.detached {
CheckoutTrace.$id.withValue(capturedID) {
CheckoutTrace.id
}
}
let childValue = await child
let inheritedValue = await inherited.value
let detachedValue = await detached.value
let propagatedValue = await propagated.value
return TraceComparison(
sameTask: same,
structuredChild: childValue,
inheritedTask: inheritedValue,
detachedTask: detachedValue,
explicitlyPropagated: propagatedValue
)
}
}Expect checkout-42 everywhere except detachedTask, which is nil. The task-local binding ends when its dynamic scope exits; inherited task bindings can still exist in an unstructured task that outlives that scope. Task-local data is useful for diagnostics and scoped dependencies, but it must not replace explicit authorization or contain sensitive payloads that logs could expose.
Verify: assert the five returned values, then assert CheckoutTrace.id == nil outside the binding. Add a nested binding and verify restoration after it exits. Separately cancel the creator of an unstructured task to demonstrate that context inheritance and cancellation propagation are different properties. Prefer explicit parameters when an operation's required input should be visible in its API; task locals reduce plumbing at the cost of implicit context. SE-0311: task-local inheritance and detached tasks
SWIFT-35 — Answer
Short answer: The cell can represent a different product before an old image request completes. A weak reference prevents unwanted retention, but does not prove that the result still belongs to the current configuration. Cancel previous work, reset displayed content, and accept a result only if its configuration identity still matches.
Detailed explanation:
A cell instance outlives any one product configuration, so a late callback can update the wrong product even on MainActor. Cancel the previous request on every configuration and on reuse, reset content during configuration, and publish only when a per-configuration token still matches. Weak capture prevents unintended ownership; it does not establish freshness.
In a catalog, rapidly scrolling from a coat to a shoe can reuse the same cell. This complete cell type uses small, already thumbnail-sized responses; image caching and off-main image preparation are separate production concerns.
import UIKit
@MainActor
final class ProductPhotoCell: UITableViewCell {
private var imageTask: Task<Void, Never>?
private var configurationID: UUID?
func configure(name: String, photoURL: URL) {
imageTask?.cancel()
let token = UUID()
configurationID = token
var content = defaultContentConfiguration()
content.text = name
content.image = UIImage(systemName: "photo")
contentConfiguration = content
imageTask = Task { [weak self] in
defer {
if self?.configurationID == token {
self?.imageTask = nil
}
}
do {
let (data, response) = try await URLSession.shared.data(from: photoURL)
try Task.checkCancellation()
guard let response = response as? HTTPURLResponse,
(200..<300).contains(response.statusCode),
let image = UIImage(data: data) else {
throw URLError(.cannotDecodeContentData)
}
guard let self, self.configurationID == token else { return }
var content = self.defaultContentConfiguration()
content.text = name
content.image = image
self.contentConfiguration = content
} catch {
guard !Task.isCancelled,
let self, self.configurationID == token else { return }
var content = self.defaultContentConfiguration()
content.text = name
content.secondaryText = "Image unavailable"
content.image = UIImage(systemName: "photo")
self.contentConfiguration = content
}
}
}
override func prepareForReuse() {
super.prepareForReuse()
imageTask?.cancel()
imageTask = nil
configurationID = nil
}
}Cancellation reduces wasted work; the token remains important when work ignores cancellation or the same URL is requested again. The task does not retain the cell across the network suspension. Reset all displayed content in configure, including placeholder and error text. Reconfiguration can happen without prepareForReuse, so cleanup there alone is insufficient. Apple: prepareForReuse
Verify: Use a controllable loader in a test target: configure A, configure B, finish B, then finish A despite cancellation. Assert that B's name and image remain; repeat with the same URL and with a failed A. A shared image pipeline can deduplicate requests across cells, but then canceling one subscriber must not cancel work still needed by another.
SWIFT-36 — Answer
Short answer: No, a view-owned task can run again when the view returns or its identity changes. Use one owner for the loading operation, then explicitly decide when successful data should be reused or refreshed. Directly awaiting the operation preserves the view task's cancellation relationship; a nested Task has a separate lifetime.
Detailed explanation:
Use one .task to own screen-scoped asynchronous work; it can run again when that view returns or changes identity. “Load once after success” is an application policy, not a guarantee of .task. Directly await the operation instead of launching a nested unstructured task whose cancellation the view does not own.
For a profile preview, keep successfully loaded text while the same screen identity remains alive, allow a canceled or failed load to retry, and show an explicit refresh button for a new fetch. This complete example uses an injected loader so a preview or test can control completion. It requires iOS 15 or later.
import SwiftUI
@MainActor
struct ProfileSummary: View {
let load: @MainActor () async throws -> String
@State private var summary: String?
@State private var errorMessage: String?
@State private var refreshID = UUID()
var body: some View {
VStack(spacing: 12) {
if let summary {
Text(summary)
} else if let errorMessage {
Text(errorMessage)
} else {
ProgressView("Loading profile")
}
Button("Refresh") {
summary = nil
errorMessage = nil
refreshID = UUID()
}
}
.task(id: refreshID) {
let requestID = refreshID
guard summary == nil else { return }
do {
let value = try await load()
try Task.checkCancellation()
guard refreshID == requestID else { return }
summary = value
errorMessage = nil
} catch {
guard !Task.isCancelled, refreshID == requestID else { return }
errorMessage = "Could not load profile. Try Refresh."
}
}
}
}Do not attach a second onAppear request to this view. The Refresh action changes the request identity immediately, so the freshness guard rejects an older completion even before SwiftUI delivers cancellation. State survives ordinary body reevaluations, but removal or an intentional identity change can discard it. For a cache that must survive navigation, let a longer-lived model own the data and its freshness policy. A view task does not guarantee that synchronous CPU work runs away from MainActor. Apple: view task lifetime Apple: appearance events
Verify: Inject a loader that increments a counter and suspends. Appear once, navigate away before completion, and assert cancellation is observed and no error is shown. Return and complete the retry; trigger an unrelated parent update and assert no new successful-load request. Then press Refresh and expect exactly one new fetch. Reuse versus refresh-on-appearance is a product decision; neither policy implies a permanent process-wide singleton.
SWIFT-37 — Answer
Short answer: State initialization supplies the initial value when SwiftUI creates that view's state storage. Reconstructing the view value does not replace storage that belongs to the same identity. Switching documents therefore needs an intentional identity change or a parent-owned draft keyed to the document, with a policy for unsaved edits.
Detailed explanation:
State(initialValue:) seeds state storage when SwiftUI creates a view identity; rebuilding the view value does not overwrite existing storage. An editor for a different document needs an explicit identity boundary or a parent-owned draft keyed by document ID. Resetting on every parent update destroys unsaved typing.
For a two-note editor, .id(note.id) below intentionally starts a fresh draft when the selected note changes. Saving updates the canonical note while unrelated parent updates keep the in-progress draft. This complete example uses local in-memory notes; a production editor must confirm or preserve unsaved changes before switching documents.
import SwiftUI
struct EditableNote: Identifiable {
let id: String
var text: String
}
@MainActor
struct NoteDraftEditor: View {
let note: EditableNote
let save: (EditableNote) -> Void
@State private var draft: String
init(note: EditableNote, save: @escaping (EditableNote) -> Void) {
self.note = note
self.save = save
_draft = State(initialValue: note.text)
}
var body: some View {
VStack {
TextField("Note text", text: $draft)
Button("Save") {
save(EditableNote(id: note.id, text: draft))
}
}
}
}
@MainActor
struct NotesWorkspace: View {
@State private var notes = [
EditableNote(id: "work", text: "Release checklist"),
EditableNote(id: "home", text: "Shopping list")
]
@State private var selectedID = "work"
var body: some View {
VStack {
Picker("Document", selection: $selectedID) {
ForEach(notes) { note in
Text(note.id).tag(note.id)
}
}
if let note = notes.first(where: { $0.id == selectedID }) {
NoteDraftEditor(note: note) { updated in
if let index = notes.firstIndex(where: { $0.id == updated.id }) {
notes[index] = updated
}
}
.id(note.id)
}
}
}
}The identity includes only the document ID, not its current text or a fresh UUID. A remote update to the same document therefore needs an explicit conflict policy rather than silently resetting the draft. .id resets other child state too, including focus; store drafts in a parent dictionary if users should switch away and return to unsaved work. Apple: Demystify SwiftUI, identity and lifetime
Verify: Type an unsaved change, cause an unrelated parent redraw, and confirm the draft remains. Switch documents and confirm the correct new draft appears. Switch back and confirm the chosen discard/preserve policy. Then simulate an external edit to the same ID and exercise the explicit conflict handling rather than assuming initialization runs again.
SWIFT-38 — Answer
Short answer: Apply the current SwiftUI state to the UIKit view during updateUIView, and report user edits back through delegate callbacks. Copying old UIKit text into the binding during a SwiftUI update reverses that ownership and can overwrite newer state. Keep the coordinator connected to the current binding and avoid unnecessary text replacement.
Detailed explanation:
updateUIView should apply current SwiftUI state to UIKit; delegate callbacks should report user changes back to the binding. Writing the old UIKit text into the binding during updateUIView reverses ownership and can publish state during a render update. Keep the coordinator's binding refreshed and avoid assigning identical text, which can disturb selection or composition.
This complete iOS wrapper bridges a multiline notes field. It defers external text replacement while an input method is composing marked text; the application must decide how external edits should merge with that composition.
import SwiftUI
import UIKit
@MainActor
struct NotesTextView: UIViewRepresentable {
@Binding var text: String
func makeCoordinator() -> Coordinator {
Coordinator(text: $text)
}
func makeUIView(context: Context) -> UITextView {
let view = UITextView()
view.delegate = context.coordinator
view.font = UIFont.preferredFont(forTextStyle: .body)
view.adjustsFontForContentSizeCategory = true
return view
}
func updateUIView(_ view: UITextView, context: Context) {
context.coordinator.text = $text
guard view.markedTextRange == nil, view.text != text else { return }
context.coordinator.isApplyingState = true
view.text = text
context.coordinator.isApplyingState = false
}
static func dismantleUIView(_ view: UITextView, coordinator: Coordinator) {
view.delegate = nil
}
final class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
var isApplyingState = false
init(text: Binding<String>) {
self.text = text
}
func textViewDidChange(_ textView: UITextView) {
guard !isApplyingState else { return }
let updated = textView.text ?? ""
guard text.wrappedValue != updated else { return }
text.wrappedValue = updated
}
}
}Assigning UITextView.text programmatically does not itself simulate a user's delegate event; do not claim every setter automatically loops. The guard also makes the intended contract explicit for a bridge extended with other callbacks. Moving every mutation into DispatchQueue.main.async can instead queue stale writes that overwrite newer input. Preserve ordering and apply an explicit merge policy when remote edits arrive. Apple: UIViewRepresentable and coordinators
Verify: Type, update the parent with a different binding target, paste text, and use a composing keyboard. Assert that user edits reach the current binding once, parent updates do not revert to the old UIKit value, and the cursor does not jump after each keystroke. Native TextEditor needs less bridging code; use a representable when UIKit-specific editing behavior is required.
SWIFT-39 — Answer
Short answer: No, debounce waits for a quiet input interval and duplicate removal skips repeated inputs; neither replaces an existing request subscription. Use switchToLatest when each accepted query should replace the previous request, and separately guard publication against outdated input. Recover errors inside each request so future searches can continue.
Detailed explanation:
Debouncing waits for a quiet interval and duplicate removal skips repeated inputs; neither cancels an existing request. Map each accepted input to a request publisher and use switchToLatest to replace the previous subscription. Also reject outputs for text no longer visible, because an old response can arrive before the new text passes the debounce interval.
This complete model definition injects an application-supplied publisher API. Its input method and downstream delivery run on the main queue, and MainActor.assumeIsolated makes that delivery precondition explicit. Each inner request converts its failure into a value, preserving the outer stream for future searches.
import Combine
import Foundation
@MainActor
protocol ProductSearching {
func search(_ query: String) -> AnyPublisher<[String], Error>
}
@MainActor
final class ProductSearchModel: ObservableObject {
@Published private(set) var results: [String] = []
@Published private(set) var errorMessage: String?
private var currentQuery = ""
private let input = PassthroughSubject<String, Never>()
private var subscription: AnyCancellable?
private struct Output {
let query: String
let result: Result<[String], Error>
}
init(api: any ProductSearching) {
subscription = input
.removeDuplicates()
.debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
.map { query -> AnyPublisher<Output, Never> in
guard !query.isEmpty else {
return Just(Output(query: query, result: .success([])))
.eraseToAnyPublisher()
}
return api.search(query)
.map { Output(query: query, result: .success($0)) }
.catch { Just(Output(query: query, result: .failure($0))) }
.eraseToAnyPublisher()
}
.switchToLatest()
.receive(on: DispatchQueue.main)
.sink { [weak self] output in
MainActor.assumeIsolated {
guard let self, output.query == self.currentQuery else { return }
switch output.result {
case .success(let values):
self.results = values
self.errorMessage = nil
case .failure:
self.errorMessage = "Search failed. Change the query to retry."
}
}
}
}
func setQuery(_ text: String) {
currentQuery = text.trimmingCharacters(in: .whitespacesAndNewlines)
if currentQuery.isEmpty {
results = []
errorMessage = nil
}
input.send(currentQuery)
}
func stop() {
subscription?.cancel()
subscription = nil
}
}The query check means “matches the visible normalized text”; an A → B → A sequence can accept an older A result during debounce. Add an input revision if each edit must invalidate every prior request. This model is stopped permanently by stop; construct or reconnect it to resume. A repeated identical query is suppressed, so a separate retry trigger is needed for a dedicated Retry button. Retaining the subscription keeps it active; the weak sink prevents a model-subscription ownership cycle. Apple: debounce Apple: removeDuplicates Apple: switchToLatest
Verify: With a controlled scheduler and request publishers, send A then B; emit A both before and after B passes debounce, then emit B. Assert only visible-query output publishes and the old subscription receives cancellation. Make B fail, then send C and confirm C still runs. Use an async/await implementation when it makes task ownership clearer; do not mix cancellation styles without defining which layer owns the request.
SWIFT-40 — Answer
Short answer: An opaque some View result still has one underlying concrete type for that declaration. ViewBuilder can combine different branches into one composite type, allowing conditional views without erasing their identity to AnyView. An ordinary function returning unrelated types from separate branches does not gain that transformation automatically.
Detailed explanation:
An opaque some View return has one concrete underlying type for that declaration. @ViewBuilder transforms conditional branches into a single composite view type, so a sync badge can contain different branch views without erasing them to AnyView. Ordinary unrelated return types do not satisfy that constraint.
For an upload toolbar, keep the state model explicit and let a builder create its display. This complete example has no network side effects in the builder.
import SwiftUI
enum UploadState {
case uploading
case complete
case failed(String)
}
@MainActor
struct UploadStatusPreview: View {
@State private var state: UploadState = .uploading
var body: some View {
VStack(spacing: 12) {
badge(for: state)
Button("Simulate success") { state = .complete }
Button("Simulate failure") { state = .failed("Offline") }
}
}
@ViewBuilder
private func badge(for state: UploadState) -> some View {
switch state {
case .uploading:
ProgressView("Uploading")
case .complete:
Label("Uploaded", systemImage: "checkmark.circle")
.foregroundStyle(.green)
case .failed(let message):
VStack(alignment: .leading) {
Label("Upload failed", systemImage: "exclamationmark.triangle")
Text(message)
}
}
}
}The builder's resulting concrete type includes its alternatives; runtime state selects a branch. any View is an existential container and is not a universal replacement for a concrete View body, while AnyView is SwiftUI's specific view-erasure wrapper. Erasure can serve genuinely heterogeneous runtime storage or an API boundary, but it hides structure and can affect state identity or optimization opportunities. It is not required merely because an if or switch has different view types. Swift: opaque and boxed types Apple: ViewBuilder
Verify: Put the example into an iOS view target and cycle all three states, including Dynamic Type and VoiceOver labels. Separately remove @ViewBuilder and add ordinary return statements for unrelated branches; confirm the compiler rejects the inconsistent underlying return type. Do not execute invalid prompt code as part of a production screen.
SWIFT-41 — Answer
Short answer: AppStorage is suitable for small, nonsensitive preferences stored in supported UserDefaults representations, such as a theme selection. It does not automatically persist every Codable model. Authentication secrets need an appropriate secure storage boundary, such as Keychain, while preference decoding should tolerate values from other app versions.
Detailed explanation:
AppStorage persists supported UserDefaults representations, not every arbitrary Codable object automatically. It is appropriate for a small nonsensitive preference such as theme. Store authentication secrets in Keychain through a separately scoped credential service; ordinary defaults do not provide that secret-storage contract.
For a reader, persist stable string identifiers instead of localized display names or enum positions. A raw-string backing value makes unknown future values explicit and lets the UI fall back to system appearance without crashing. This complete example permits an isolated defaults suite in previews and tests.
import SwiftUI
enum ReaderTheme: String, CaseIterable, Identifiable {
case system, light, dark
var id: String { rawValue }
var title: String {
switch self {
case .system: "System"
case .light: "Light"
case .dark: "Dark"
}
}
var colorScheme: ColorScheme? {
switch self {
case .system: nil
case .light: .light
case .dark: .dark
}
}
}
@MainActor
struct ReaderPreferences: View {
@AppStorage private var storedTheme: String
init(defaults: UserDefaults = .standard) {
_storedTheme = AppStorage(
wrappedValue: ReaderTheme.system.rawValue,
"reader.theme.v1",
store: defaults
)
}
private var theme: ReaderTheme {
ReaderTheme(rawValue: storedTheme) ?? .system
}
var body: some View {
Picker("Theme", selection: Binding(
get: { theme },
set: { storedTheme = $0.rawValue }
)) {
ForEach(ReaderTheme.allCases) { option in
Text(option.title).tag(option)
}
}
.preferredColorScheme(theme.colorScheme)
}
}The fallback does not silently overwrite an unrecognized stored string; choosing a supported option writes its stable value. Do not rename stored raw values without a migration. An enum with supported raw representation can also use an AppStorage enum initializer directly; the explicit backing string here exposes the fallback policy. Larger structured preferences can use deliberate Codable serialization and versioning, while relational or high-volume data belongs in a database. Apple: UserDefaults representations and sensitive data Apple: RawRepresentable preference initialization Apple: Keychain services
Verify: Use a uniquely named UserDefaults suite, open the view, change theme, and recreate the view with the same suite. Seed reader.theme.v1 with "future-theme" and verify system appearance plus a valid Picker selection. Test missing values and a migration from an older key. Clean up only that test suite; never clear the user's standard defaults to test persistence.
SWIFT-42 — Answer
Short answer: A diffable snapshot tracks which items exist and where they are arranged; it does not automatically observe every field in your separate model store. Keep a stable item ID, update the stored content, and explicitly reconfigure the changed existing item. Making display text part of identity creates unnecessary removal and insertion instead.
Detailed explanation:
A diffable snapshot tracks item identity and arrangement; it does not automatically detect every changed field in your model store. Keep stable product IDs, update the store, and explicitly reconfigure existing changed IDs. Making mutable display fields part of identity turns an edit into removal plus insertion and can discard selection or cell state.
This complete table controller uses iOS 15's snapshot reconfiguration. Its display method must receive unique product IDs and run on MainActor. The cell provider always reads the current model and assigns every displayed field.
import UIKit
struct CatalogProduct: Equatable {
let id: UUID
var name: String
var priceText: String
}
@MainActor
final class CatalogTableController: UITableViewController {
private enum Section { case main }
private var productsByID: [UUID: CatalogProduct] = [:]
private var source: UITableViewDiffableDataSource<Section, UUID>?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Product")
source = UITableViewDiffableDataSource<Section, UUID>(tableView: tableView) {
[weak self] tableView, indexPath, productID in
let cell = tableView.dequeueReusableCell(
withIdentifier: "Product", for: indexPath
)
var content = cell.defaultContentConfiguration()
if let product = self?.productsByID[productID] {
content.text = product.name
content.secondaryText = product.priceText
}
cell.contentConfiguration = content
return cell
}
}
func display(_ products: [CatalogProduct]) {
loadViewIfNeeded()
guard let source else { return }
let ids = products.map(\.id)
guard Set(ids).count == ids.count else {
assertionFailure("Catalog product IDs must be unique")
return
}
let existing = Set(source.snapshot().itemIdentifiers)
let changed = products.filter {
existing.contains($0.id) && productsByID[$0.id] != $0
}.map(\.id)
productsByID = Dictionary(uniqueKeysWithValues: products.map { ($0.id, $0) })
var snapshot = NSDiffableDataSourceSnapshot<Section, UUID>()
snapshot.appendSections([.main])
snapshot.appendItems(ids, toSection: .main)
snapshot.reconfigureItems(changed)
source.apply(snapshot, animatingDifferences: true)
}
}The changed-ID list excludes newly inserted IDs, which receive initial configuration normally. A reconfiguration retains the existing cell; use reload when a different cell type is required. Reconfiguration does not call prepareForReuse, so configuration itself must reset placeholders and cancel configuration-specific work where relevant. Apple: updating diffable data sources Apple: snapshot reconfigureItems
Verify: Display two products, select one, then change only its price under the same ID. Assert the price changes and selection remains. Then insert, reorder, and delete products, confirm the ID sequence, and send duplicate IDs to verify the explicit input failure path. Full reload is simpler for tiny static lists, but it sacrifices the precise updates and state continuity diffable identity can provide.
SWIFT-43 — Answer
Short answer: Published sends an update before writing the new value into the stored property. A synchronous subscriber can therefore receive the new value while a direct property read still returns the old one. Calculate from the value delivered to the subscriber rather than assuming that rereading the property gives the same snapshot.
Detailed explanation:
@Published immediately supplies its current value to a demanding subscriber, then publishes changes before the stored property changes. A synchronous sink therefore receives the proposed new value while a property read can still see the old one. Calculate from the emitted value; scheduling delivery later does not make several independently published properties an atomic snapshot.
Real scenario: a cart subtotal
The following complete model records both values to make the ordering visible. The quantity and subscription are confined to MainActor; there is no scheduler hop between publication and this sink.
import Combine
@MainActor
final class CartQuantityProbe: ObservableObject {
struct Sample: Equatable {
let emitted: Int
let storedDuringCallback: Int
}
@Published var quantity = 1
private(set) var subtotalCents = 250
private(set) var samples: [Sample] = []
private var subscription: AnyCancellable?
init(unitPriceCents: Int = 250) {
subscription = $quantity.sink { [weak self] newQuantity in
guard let self else { return }
samples.append(Sample(
emitted: newQuantity,
storedDuringCallback: quantity
))
subtotalCents = unitPriceCents * newQuantity
}
}
}
@MainActor
func verifyPublishedOrdering() {
let cart = CartQuantityProbe()
assert(cart.samples == [.init(emitted: 1, storedDuringCallback: 1)])
cart.quantity = 3
assert(cart.samples.last == .init(emitted: 3, storedDuringCallback: 1))
assert(cart.quantity == 3)
assert(cart.subtotalCents == 750)
}The first emission is not a user edit. Use dropFirst() only when skipping that initial state is an intentional product rule; a new subscriber should often render the initial state. ObservableObject.objectWillChange also announces an impending change, rather than supplying an after-the-write snapshot. Apple: Published Apple: ObservableObject
Verify: Predict the samples for assignments 3, then 5, before invoking the demonstration in a local test. Change the sink to reread quantity for the subtotal and identify which assertion would fail. A delayed callback might read a much newer value after several edits, so it is not a reliable repair.
Tradeoff: Use a computed subtotal when it is cheap and needed only while reading the model. If multiple fields must change together, publish a single immutable CartState value containing those fields. combineLatest combines latest emissions but does not create a transaction across separate setters.
SWIFT-44 — Answer
Short answer: A SwiftUI binding gives a control two-way access to a value owned elsewhere. A Published property's publisher sends a stream of values to Combine subscribers instead of supplying editable storage access. In the ObservableObject model, StateObject usually establishes view-owned model lifetime, while ObservedObject observes an injected instance.
Detailed explanation:
With a SwiftUI observable-object wrapper, $model.name is a writable Binding<String> used by controls; model.$name is the model's Published<String>.Publisher used by Combine. A parent uses @StateObject to own the model for its view identity, while an injected child uses @ObservedObject. Neither projection turns one API into the other.
Real scenario: an owned profile editor and an injected field
This is the ObservableObject/Combine approach, which remains relevant when maintaining Combine-based screens. Every edit updates the model through a binding; the publisher derives a character count without owning a second copy of the name.
import Combine
import SwiftUI
@MainActor
final class ProfileNameModel: ObservableObject {
@Published var name = ""
@Published private(set) var characterCount = 0
init() {
let names: Published<String>.Publisher = $name
names
.map(\.count)
.assign(to: &$characterCount)
}
}
@MainActor
struct ProfileNameScreen: View {
@StateObject private var model = ProfileNameModel()
var body: some View {
Form {
ProfileNameField(model: model)
Text("Characters: \(model.characterCount)")
Button("Reset") { model.name = "" }
}
}
}
@MainActor
struct ProfileNameField: View {
@ObservedObject var model: ProfileNameModel
var body: some View {
let editing: Binding<String> = $model.name
TextField("Display name", text: editing)
.textInputAutocapitalization(.words)
}
}The parent retains one model for a stable screen identity; the child observes the instance passed by its parent. Constructing ProfileNameField(model: ProfileNameModel()) during every parent body evaluation supplies a new instance, so previously edited text can disappear. The assign(to: &$characterCount) subscription is owned by the published property's lifetime. Apple: StateObject Apple: ObservedObject Apple: assign(to:)
Verify: Enter a name, trigger an unrelated parent redraw, and confirm the name remains. Reset from the parent and confirm the child's text and character count update. Compare the compiler types of the explicitly typed names and editing variables.
Tradeoff: For a new iOS 17+ screen, an Observation @Observable model commonly uses @State for ownership and @Bindable when bindings are needed. Observation does not automatically provide a Published.Publisher for each property; use a Combine model when those streams are part of the existing architecture. Apple: Migrating from ObservableObject to Observable
SWIFT-45 — Answer
Short answer: Use PassthroughSubject for a transient event, such as a button tap, and CurrentValueSubject when new subscribers need the current state. A late subscriber misses earlier transient events but can receive the active state subject's current value. Once either subject completes, it does not restart as a new stream.
Detailed explanation:
Use PassthroughSubject for a transient tap and CurrentValueSubject for a current status. A late demanding subscriber misses earlier taps but receives the current status while its subject is active. Completion is terminal: neither subject can be restarted with another send, and a subscriber attaching after completion receives completion rather than a replayed status value.
Real scenario: dashboard events and connection state
Keep subject mutation private so consumers can subscribe without inventing connection states or closing the stream. The following owner serializes its own operations on MainActor; downstream code must still respect the delivery contract.
import Combine
enum DashboardConnection: Equatable {
case connecting
case connected
case disconnected
}
@MainActor
final class DashboardSignals {
private let refreshSubject = PassthroughSubject<Void, Never>()
private let connectionSubject =
CurrentValueSubject<DashboardConnection, Never>(.connecting)
var refreshes: AnyPublisher<Void, Never> {
refreshSubject.eraseToAnyPublisher()
}
var connection: AnyPublisher<DashboardConnection, Never> {
connectionSubject.eraseToAnyPublisher()
}
func refreshTapped() {
refreshSubject.send(())
}
func connectionChanged(to value: DashboardConnection) {
connectionSubject.send(value)
}
func close() {
refreshSubject.send(completion: .finished)
connectionSubject.send(completion: .finished)
}
}
@MainActor
func inspectLateDashboardSubscriptions() -> Set<AnyCancellable> {
let signals = DashboardSignals()
signals.refreshTapped()
signals.connectionChanged(to: .connected)
var tokens = Set<AnyCancellable>()
signals.refreshes
.sink { print("A new Refresh tap") }
.store(in: &tokens)
signals.connection
.sink { print("Current status:", $0) }
.store(in: &tokens)
signals.close()
signals.connection
.sink(
receiveCompletion: { print("Late completion:", $0) },
receiveValue: { print("Unexpected after completion:", $0) }
)
.store(in: &tokens)
return tokens
}In this demonstration, the first Refresh has no subscriber and is lost. The active status subscription receives .connected; the subscription created after close() receives only .finished. Never means the stream cannot fail with an error, not that it cannot finish. A passthrough subject can also drop values when a subscriber has no demand. sink requests unlimited demand. Apple: PassthroughSubject Apple: CurrentValueSubject Apple: Subscriber completion
Verify: Attach subscribers before and after a tap, a status change, and completion. Record each received value and completion separately. Attempt another connectionChanged after close() and confirm it does not reopen the publisher.
Tradeoff: A current-value subject retains only its latest state; it is not an event history or durable queue. Use a stored event log when missed events must be replayed. For a temporary disconnected state, publish .disconnected and keep the stream open; finish only when the signal owner's lifecycle truly ends.
SWIFT-46 — Answer
Short answer: The owner can retain the subscription while the subscription's callback retains the owner, forming a strong reference cycle. Keeping the cancellation token is necessary for continued observation, but the callback still needs a suitable ownership policy. A weak capture or explicit lifecycle cleanup can break the cycle without immediately discarding the subscription.
Detailed explanation:
Retaining AnyCancellable keeps observation alive, but an owner → token → sink → owner strong cycle can keep the owner alive forever. A weak sink breaks that back-reference. Dropping the token cancels observation; it does not solve a cycle that prevents the token being dropped. Explicitly stop subscriptions at the feature's intended observation boundary.
Real scenario: a banner observing long-lived status updates
The caller supplies the update publisher, such as the connection stream above. Delivery is scheduled onto the main queue before the callback accesses actor-isolated state; assumeIsolated checks this existing delivery guarantee and does not schedule work itself.
import Combine
import Foundation
@MainActor
final class ConnectionBannerModel: ObservableObject {
@Published private(set) var text = "Waiting"
private var subscription: AnyCancellable?
init(updates: AnyPublisher<String, Never>) {
subscription = updates
.receive(on: DispatchQueue.main)
.sink { [weak self] value in
MainActor.assumeIsolated {
self?.text = value
}
}
}
func stopObserving() {
subscription?.cancel()
subscription = nil
}
}
@MainActor
final class LifetimeBoundBannerModel: ObservableObject {
@Published private(set) var text = "Waiting"
init(updates: AnyPublisher<String, Never>) {
updates
.receive(on: DispatchQueue.main)
.assign(to: &$text)
}
}The weak sink permits the first model to deinitialize even if the publisher never completes. Clearing its token also gives an explicit stop point while the model remains alive. AnyCancellable cancels when deinitialized. A strong sink would close the ownership cycle; merely adding deinit { subscription?.cancel() } cannot fix a cycle that prevents deinit from running. Apple: AnyCancellable
| Subscriber choice | Ownership and cancellation |
|---|---|
sink { [weak self] ... } with a stored token | Does not retain the owner through that capture; the owner can explicitly cancel. |
assign(to: \.text, on: self) with a token stored on self | The assign subscriber retains its target until completion, creating a cycle for a long-lived source. |
assign(to: &$text) | The published property manages subscription lifetime; there is no returned token for a separate early stop. |
The second model intentionally observes for its whole lifetime. Keep its upstream free of closures that capture that model strongly; the assignment overload cannot remove unrelated ownership cycles. Apple: assign(to:on:) Apple: assign(to:)
Verify: Give the first model a subject-backed publisher, retain only a weak probe after releasing the model, and check that the probe becomes nil. Separately call stopObserving() while retaining the model, then send another value and confirm no update occurs. Account for any value already delivered before cancellation.
Tradeoff: Stopping on every view disappearance can be wrong for a model shared with another screen. Put cancellation in the layer that owns this observation, and reconnect explicitly when observation should resume; calling stopObserving here does not automatically recreate the subscription.
SWIFT-47 — Answer
Short answer: subscribe(on:) chooses where subscribing, requesting values, and cancelling run. receive(on:) chooses where later operators receive values and completion; it does not control where all upstream work happens. Deliver expensive processing to an appropriate worker, and keep UI updates within the main actor’s rules.
Detailed explanation:
subscribe(on:) schedules upstream subscription, demand, and cancellation operations; it does not dictate every asynchronous callback's executor. receive(on:) changes delivery for downstream values and completion. Put decoding after a worker delivery boundary, then deliver UI results on the main queue and explicitly respect MainActor isolation.
Real scenario: decoding a forecast without doing the decode on the UI queue
This model accepts a caller-supplied HTTPS endpoint returning an object such as {"celsius":21.5}. It includes the response validation and every type used by the pipeline. Network transport chooses its own callback execution; the first receive(on:) explicitly places subsequent decoding on worker.
import Combine
import Foundation
struct ForecastPayload: Decodable, Sendable {
let celsius: Double
}
@MainActor
final class ForecastScreenModel: ObservableObject {
@Published private(set) var celsius: Double?
@Published private(set) var errorMessage: String?
private var subscription: AnyCancellable?
init(endpoint: URL, session: URLSession = .shared) {
let worker = DispatchQueue(label: "forecast.decode", qos: .userInitiated)
subscription = session.dataTaskPublisher(for: endpoint)
.subscribe(on: worker)
.tryMap { @Sendable output -> Data in
guard let response = output.response as? HTTPURLResponse,
(200..<300).contains(response.statusCode) else {
throw URLError(.badServerResponse)
}
return output.data
}
.receive(on: worker)
.decode(type: ForecastPayload.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { [weak self] completion in
MainActor.assumeIsolated {
if case .failure = completion {
self?.errorMessage = "Forecast could not be loaded."
}
}
},
receiveValue: { [weak self] forecast in
MainActor.assumeIsolated {
self?.celsius = forecast.celsius
self?.errorMessage = nil
}
}
)
}
func cancel() {
subscription?.cancel()
subscription = nil
}
}receive(on: DispatchQueue.main) establishes a runtime delivery contract, while the synchronous MainActor.assumeIsolated block enforces actor access under that contract. It traps if the assumed executor is wrong; it is not an alternative scheduling mechanism. The @Sendable response transform avoids inheriting the initializer's actor isolation for a callback that can run off the main actor. A Task { @MainActor in ... } would instead introduce a new asynchronous task and require an explicit lifetime and ordering policy. Apple: receive(on:options:) Apple: subscribe(on:options:) Apple: MainActor.assumeIsolated
Verify: Use an injected URLSession with a test URLProtocol to return valid JSON, malformed JSON, and a non-success status. Inspect the decode queue in a debugger and assert UI state is accessed on MainActor. Cancel before completion and check the transport observes cancellation; cancellation does not undo a response already delivered.
Tradeoff: Keep cheap response checks simple; move genuinely expensive processing behind the worker boundary. An async/await request can express actor hops more directly, but does not automatically make a synchronous decode cheap or move it off the caller's actor. A scheduler operator is useful only when its position matches the work being moved.
SWIFT-48 — Answer
Short answer: CombineLatest produces a pair of the latest field values whenever either changes, after both have supplied an initial value. Zip waits to pair matching positions from each stream, so one field can change without producing a new pair. Validate the values delivered by the operator rather than rereading potentially older stored properties.
Detailed explanation:
Use combineLatest for form state: once both publishers have produced a value, an edit to either field emits the latest pair. zip pairs the first value from each source, then the second from each, and waits for missing partners. Validate the emitted tuple instead of rereading properties that may still be in @Published's pre-write callback.
Real scenario: password confirmation
Both published fields provide initial values, so the Save button starts with a known invalid state. The length check below is an illustrative UI rule, not a complete password policy; the server must enforce the application's actual rules.
import Combine
import SwiftUI
@MainActor
final class PasswordConfirmationModel: ObservableObject {
@Published var password = ""
@Published var confirmation = ""
@Published private(set) var canSave = false
init() {
Publishers.CombineLatest($password, $confirmation)
.map { password, confirmation in
password.count >= 12 && password == confirmation
}
.removeDuplicates()
.assign(to: &$canSave)
}
}
@MainActor
struct PasswordConfirmationForm: View {
@StateObject private var model = PasswordConfirmationModel()
let save: @MainActor (String) -> Void
var body: some View {
Form {
SecureField("New password", text: $model.password)
.textContentType(.newPassword)
SecureField("Confirm password", text: $model.confirmation)
.textContentType(.newPassword)
Button("Save") { save(model.password) }
.disabled(!model.canSave)
}
}
}With password correct horse and confirmation correct horse, canSave becomes true. Editing only the password to correct horses immediately makes it false. A zip pipeline has already consumed the matching pair and would wait for another confirmation emission before validating the new password. Apple: combineLatest Apple: zip
Verify: Check the initial false state, a matching pair, two consecutive edits to one field, and a later confirmation edit. Repeat with zip and record emitted pairs to expose the waiting partner. If using passthrough inputs instead, explicitly supply initial values with prepend or stored state; otherwise no tuple exists until both inputs emit.
Tradeoff: Use zip when the nth elements belong together, such as paired readings with an explicit ordering contract. combineLatest is appropriate for independent current state but can emit intermediate pairs when two setters run consecutively. Publish one aggregate form value when both fields must change atomically, and revalidate on submission rather than treating a disabled button as a security boundary.
SWIFT-49 — Answer
Short answer: Future starts its fulfillment closure when the Future is created and retains its single result. Deferred waits for a subscriber before creating its inner publisher, so creating a fresh Future there can give each subscriber its own attempt. Deferring creation does not automatically make the underlying callback operation cancellable.
Detailed explanation:
Future runs its attempt-to-fulfill closure when the future is constructed and retains its single result for subscribers. Deferred waits for a subscription before constructing its inner publisher, so wrapping a newly created Future gives each subscriber a separate attempt. Neither wrapper automatically cancels an underlying callback operation when downstream cancels.
Real scenario: separate export jobs instead of one reused job identity
The UUID generator stands in for the start of an export job. This complete demonstration compares construction and subscription counts without starting a network request or writing a file. Its function is intentionally synchronous so the lifecycle distinction is visible without a scheduler.
import Combine
import Foundation
func compareExportPublisherConstruction() -> Set<AnyCancellable> {
let eager = Future<UUID, Never> { promise in
print("Constructed one shared export attempt")
promise(.success(UUID()))
}
let independent = Deferred {
Future<UUID, Never> { promise in
print("Constructed a new attempt for this subscriber")
promise(.success(UUID()))
}
}
var tokens = Set<AnyCancellable>()
eager
.sink { print("Eager subscriber A:", $0) }
.store(in: &tokens)
eager
.sink { print("Eager subscriber B:", $0) }
.store(in: &tokens)
independent
.sink { print("Deferred subscriber A:", $0) }
.store(in: &tokens)
independent
.sink { print("Deferred subscriber B:", $0) }
.store(in: &tokens)
return tokens
}The eager attempt starts before its first sink; both eager subscribers see the same generated UUID. The deferred closure runs once for each subscription, constructing two different future instances. By contrast, Deferred { eager } merely delays access to the already created future and still shares its attempt. Retrying an already failed Future resubscribes to that retained failure; use a deferred factory when a retry must construct fresh work. Apple: Future Apple: Deferred
Verify: Predict how many construction messages appear before and after each subscription. Add a third subscription to each publisher. When adapting a real callback API, inject a cancellation-recording fake and verify that canceling the Combine subscription calls the API's cancellation handle; this demonstration itself has no long-running work to cancel.
Tradeoff: Starting one export for two UI observers may be exactly the desired behavior; independent subscriptions must not accidentally create duplicate side effects. For cancellable network work, prefer a publisher such as URLSession.DataTaskPublisher with a defined transport cancellation contract. A custom callback bridge needs a race-safe subscription implementation that owns the underlying operation, demand, cancellation, and terminal delivery; Deferred alone provides none of those guarantees. Apple: DataTaskPublisher
SWIFT-50 — Answer
Short answer: Recover inside each request publisher so a failed submission becomes one result while the outer tap stream remains active. Catching outside the flattened request stream can replace that entire stream with a finite replacement and then finish it. Any retries should be bounded and preserve the identity of the same logical submission.
Detailed explanation:
Recover inside each request publisher so failure becomes one submission result and the outer tap stream stays subscribed. A catch outside the flattened stream replaces that entire stream; a finite Just then finishes it. Retry before converting failure into a value, create fresh request work for each attempt, and reuse one idempotency key for retries of the same submission.
Real scenario: a draft form that can submit again after a temporary outage
The injected client contract below is explicit: constructing a request publisher is thread-safe, each request emits one receipt and finishes or fails, its only failure means a retryable temporary transport problem, and the server deduplicates requests with the same key. Business validation errors belong in the client's response model rather than this retryable failure type. A real implementation must uphold that contract.
import Combine
import Foundation
struct DraftSubmission: Sendable {
let idempotencyKey: UUID
let title: String
}
struct DraftReceipt: Sendable {
let reference: String
}
enum TemporarySubmissionFailure: Error {
case temporarilyUnavailable
}
protocol DraftSubmissionClient: Sendable {
func submit(_ draft: DraftSubmission)
-> AnyPublisher<DraftReceipt, TemporarySubmissionFailure>
}
enum DraftSubmissionState: Equatable, Sendable {
case idle
case submitting
case saved(String)
case failed(String)
}
@MainActor
final class DraftSubmissionModel: ObservableObject {
@Published private(set) var state: DraftSubmissionState = .idle
private let taps = PassthroughSubject<DraftSubmission, Never>()
private var subscription: AnyCancellable?
private var pending: DraftSubmission?
init(client: any DraftSubmissionClient) {
subscription = taps
.flatMap(maxPublishers: .max(1)) { @Sendable draft in
Deferred { @Sendable in client.submit(draft) }
.retry(1)
.map { @Sendable in DraftSubmissionState.saved($0.reference) }
.catch { @Sendable _ in
Just(DraftSubmissionState.failed(
"Outcome unresolved. Retry the same submission."
))
}
}
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
MainActor.assumeIsolated {
guard let self else { return }
if case .saved = state {
self.pending = nil
}
self.state = state
}
}
}
func submit(title: String) {
let normalized = title.trimmingCharacters(in: .whitespacesAndNewlines)
guard subscription != nil, !normalized.isEmpty,
state != .submitting else { return }
let draft: DraftSubmission
if let pending {
guard pending.title == normalized else {
state = .failed("Resolve the earlier submission before changing it.")
return
}
draft = pending
} else {
draft = DraftSubmission(idempotencyKey: UUID(), title: normalized)
pending = draft
}
state = .submitting
taps.send(draft)
}
func stop() {
subscription?.cancel()
subscription = nil
state = .idle
}
}retry(1) allows one extra subscription, so at most two attempts occur per tap. Deferred calls the client again for that retry while the captured draft.idempotencyKey remains unchanged. Catch runs after the retry budget is exhausted and finishes only the inner request with a failure value. The outer PassthroughSubject remains open for a new tap. The model retains the pending payload and key after failure: retrying the unchanged title reuses both, and changing the title is rejected while that outcome is unresolved. Only a successful receipt clears the pending submission; after confirmation, another tap starts a new logical write. Apple: retry Apple: catch
The synchronous submit method sets .submitting before sending, so later taps while busy are deliberately ignored. flatMap(maxPublishers: .max(1)) limits active inner subscriptions; it is not a durable tap queue. The UI should disable its Submit button while this state is active. The client must make progress or fail; production requests also need a timeout policy. Apple: flatMap
Verify: Inject a client that fails the first attempt and succeeds on the second; confirm two calls share a key. Exhaust both attempts, then submit the same title again and confirm the key is still unchanged. Attempt a different title while unresolved and confirm no client call starts. Deliver a successful receipt, submit a new title, and confirm this new logical write receives a new key. Hold a request open, tap twice, and confirm only the initial submission starts. Check that changing catch to an outer catch { Just(...) } makes the first exhausted failure terminate later observation.
Tradeoff: Automatic retries are appropriate only when the failure and request semantics allow them. A timeout does not prove a write was rejected. This example conservatively blocks different writes until the pending write receives a successful receipt. Production code can additionally reconcile with a server status endpoint and permit replacement only after a conclusive outcome. Persist the pending key and full payload before the initial request, restore them on restart, and honor the server's deduplication retention period; an in-memory field alone cannot protect across crashes or discarded models. stop() permanently ends this instance's observation without clearing its pending data. Reconnection must preserve that data and reconcile the outcome, since transport cancellation does not undo a server write. Add bounded backoff and explicit retry classification for real services, rather than using unbounded retry to conceal outages.
SWIFT-51 — Answer
Short answer: No, await marks a possible suspension point rather than starting another child task. Two ordinary awaited calls execute in sequence, while separate async-let declarations can overlap independent operations. Keep a sequential dependency when the second operation needs the first result, and do not assume either form guarantees a background thread.
Detailed explanation:
await marks a possible suspension; it does not create a child task or make adjacent calls overlap. Two ordinary awaited calls remain sequential. Use separate async let declarations for independent results that should be in flight together, then await both before returning. Neither syntax guarantees parallel CPU execution, a particular thread, or an exact speedup.
A home screen can load a profile label and unread count independently. These complete definitions include a cancellable fake dependency and both orchestration choices; the delays illustrate independent waits rather than a performance benchmark.
import Foundation
struct DashboardSnapshot: Sendable {
let displayName: String
let unreadCount: Int
}
protocol DashboardLoading: Sendable {
func displayName() async throws -> String
func unreadCount() async throws -> Int
}
struct PreviewDashboardLoader: DashboardLoading {
func displayName() async throws -> String {
try await Task.sleep(for: .milliseconds(200))
return "Aylin"
}
func unreadCount() async throws -> Int {
try await Task.sleep(for: .milliseconds(300))
return 7
}
}
func sequentialDashboard(
using loader: some DashboardLoading
) async throws -> DashboardSnapshot {
try Task.checkCancellation()
let name = try await loader.displayName()
let unread = try await loader.unreadCount()
try Task.checkCancellation()
return DashboardSnapshot(displayName: name, unreadCount: unread)
}
func concurrentDashboard(
using loader: some DashboardLoading
) async throws -> DashboardSnapshot {
try Task.checkCancellation()
async let name = loader.displayName()
async let unread = loader.unreadCount()
let snapshot = try await DashboardSnapshot(
displayName: name, unreadCount: unread
)
try Task.checkCancellation()
return snapshot
}The second request in the sequential function cannot begin until the first call returns. In the concurrent version, both child operations can make progress while the parent awaits their values. An implementation may return without suspending, or serialize internal work on an actor; async is an API effect rather than a promise of background execution. If the unread request needs an account ID returned by the first request, preserve that dependency and await it first. Do not put two awaited calls inside one tuple-valued async let initializer and assume that creates two children. Swift: async let semantics, Apple: suspension and UI concurrency
Verify: Inject a controlled loader that records request starts and waits for test-controlled releases. In the sequential version, assert that the unread request has not started before the name is released. In the concurrent version, wait for both starts before releasing either. Fail one child and cancel the caller; verify propagation and that the parent cannot outlive unfinished structured children. Compare fixed-operation async let with a dynamic task group rather than starting unbounded work for every screen.
SWIFT-52 — Answer
Short answer: Creating a throwing Task returns a handle; its error is observed by awaiting the handle's result, not automatically thrown out of the button action. Give the operation an owner that retains the handle, prevents duplicate starts, handles failure visibly, and requests cancellation when its lifecycle ends.
Detailed explanation:
Creating a throwing Task returns a handle; its stored failure is observed through try await handle.value, not automatically thrown by the synchronous button action. Alternatively, catch errors inside an owned Task<Void, Never>. Set loading state before scheduling, reject duplicate starts, retain the handle, and explicitly cancel work when the screen's operation ends.
This complete SwiftUI export example uses the second design. A fake service returns an export name after a cancellable delay; replace it with a scoped file/export service. The screen has one task owner, and a per-operation ID prevents cleanup from an old task from clearing a newer task.
import SwiftUI
import Observation
import Foundation
protocol ReportExporting: Sendable {
func exportReport() async throws -> String
}
struct PreviewReportExporter: ReportExporting {
func exportReport() async throws -> String {
try await Task.sleep(for: .seconds(1))
return "sales-report.csv"
}
}
@MainActor
@Observable
final class ReportExportModel {
private(set) var isExporting = false
private(set) var message: String?
private var task: Task<Void, Never>?
private var operationID: UUID?
private let exporter: any ReportExporting
init(exporter: any ReportExporting) {
self.exporter = exporter
}
func start() {
guard !isExporting else { return }
let id = UUID()
operationID = id
isExporting = true
message = nil
let exporter = exporter
task = Task { [weak self] in
defer {
if self?.operationID == id {
self?.isExporting = false
self?.task = nil
self?.operationID = nil
}
}
do {
let name = try await exporter.exportReport()
try Task.checkCancellation()
guard let self, self.operationID == id else { return }
self.message = "Export ready: \(name)"
} catch {
guard let self, self.operationID == id else { return }
if Task.isCancelled || error is CancellationError {
self.message = "Export cancelled"
} else {
self.message = "Export failed. Please try again."
}
}
}
}
func cancel() {
guard isExporting else { return }
task?.cancel()
operationID = nil
task = nil
isExporting = false
message = "Export cancelled"
}
}
@MainActor
struct ReportExportScreen: View {
@State private var model = ReportExportModel(
exporter: PreviewReportExporter()
)
var body: some View {
VStack(spacing: 12) {
Button("Export report") { model.start() }
.disabled(model.isExporting)
if model.isExporting {
ProgressView("Exporting")
Button("Cancel export") { model.cancel() }
}
if let message = model.message { Text(message) }
}
.onDisappear { model.cancel() }
}
}The weak capture avoids retaining the model throughout the service wait. cancel() invalidates publication synchronously, but an uncooperative exporter can still finish underlying work; cancellation does not delete a file already written. Prevent duplicates at the service boundary too if that side effect needs stronger guarantees. This task is unstructured even though it inherits MainActor; view disappearance does not cancel it without the explicit call. Apple: Task handles and cancellation, Swift: unstructured task lifetime
Verify: Use a controlled exporter: tap twice before completion and assert one start; fail it and verify visible retry feedback; cancel A, start B, then finish A despite cancellation and verify B's loading state remains. Complete B and verify its result. If another async operation must consume a throwing task's result, retain its Task<String, any Error> and use try await handle.value; simply discarding that handle neither reports its failure nor stops it. Prefer a direct async call or a view-owned .task when the caller already has the appropriate async lifetime.
SWIFT-53 — Answer
Short answer: Start only as many children as the concurrency limit permits, then start one replacement when a child finishes. Attach each result to its original input position so completion order does not change output order. The limit bounds active operations, while cancellation, partial failure, and total collection size still need separate policies.
Detailed explanation:
Start only the first four children, consume one completion, and start at most one replacement for that freed slot. Return each result with its input index and reorder once at the end. Failure propagates when a child result is consumed; group exit waits for children and requests cancellation on failure. A concurrency limit bounds active operations, not total input or output memory.
For a catalog page, this complete helper bounds service pressure while preserving the requested product order. Invalid concurrency is an explicit error. It never shares a mutable results array with child tasks; the parent alone accumulates completions.
import Foundation
enum CatalogBatchFailure: Error { case invalidConcurrency }
func orderedCatalogTitles(
for productIDs: [String],
maxConcurrent: Int = 4,
fetch: @escaping @Sendable (String) async throws -> String
) async throws -> [String] {
guard maxConcurrent > 0 else {
throw CatalogBatchFailure.invalidConcurrency
}
try Task.checkCancellation()
return try await withThrowingTaskGroup(of: (Int, String).self) { group in
defer { group.cancelAll() }
var nextIndex = 0
var completed: [(Int, String)] = []
completed.reserveCapacity(productIDs.count)
for index in 0..<min(maxConcurrent, productIDs.count) {
let id = productIDs[index]
group.addTask {
try Task.checkCancellation()
return (index, try await fetch(id))
}
nextIndex += 1
}
while let result = try await group.next() {
try Task.checkCancellation()
completed.append(result)
if nextIndex < productIDs.count {
let index = nextIndex
let id = productIDs[index]
nextIndex += 1
group.addTask {
try Task.checkCancellation()
return (index, try await fetch(id))
}
}
}
try Task.checkCancellation()
return completed.sorted { $0.0 < $1.0 }.map { $0.1 }
}
}
struct PreviewCatalogTitles: Sendable {
func title(for id: String) async throws -> String {
try await Task.sleep(for: .milliseconds(10))
return "Product \(id)"
}
}
func loadCatalogPage() async throws -> [String] {
let service = PreviewCatalogTitles()
return try await orderedCatalogTitles(
for: ["coat", "shoe", "bag", "hat", "scarf"],
maxConcurrent: 4
) { id in
try await service.title(for: id)
}
}Task groups deliver completed children in completion order, so index association is essential when the UI requires input order. This all-or-error API intentionally discards partial results on failure. A best-effort page instead needs an explicit per-ID Result model and a policy for cancelled/unstarted IDs. Cancellation remains cooperative; the scope can wait for an uncooperative dependency. Apple: task-group behavior, Swift: task-group lifetime and errors
Verify: Give a controlled fake service an active-operation counter and manual completion gates. Hold the first four; assert a fifth has not started. Complete one, assert exactly one replacement starts, and finish requests in reverse order; the returned array must still match input order and peak activity must be at most four. Test empty input, zero concurrency, one failure, and cancellation before the next replacement. For an enormous catalog, also page the input and stream/store results: the shown input and accumulated results remain O(n), with an O(n log n) final sort.
SWIFT-54 — Answer
Short answer: The refresh indicator follows the lifetime of the refreshable async handler. Starting a separate Task lets that handler return while the actual load continues, so await the model operation directly. Use one request-identity rule across all load paths so old results or cleanup cannot overwrite a newer refresh.
Detailed explanation:
refreshable keeps its indicator visible for the async handler's lifetime. A nested Task lets that handler return before loading finishes. Await the model directly, and give all load paths one generation guard: only the latest-started operation may publish rows, errors, or loading cleanup. Cancellation should not replace useful data with an error.
This complete feed uses the same operation for initial load and pull-to-refresh. Its policy preserves existing rows on failure. A newer operation takes ownership immediately; older work may finish, but its result and cleanup are ignored.
import SwiftUI
import Observation
import Foundation
struct NewsRow: Identifiable, Sendable {
let id: String
let title: String
}
protocol NewsLoading: Sendable {
func latest() async throws -> [NewsRow]
}
struct PreviewNewsLoader: NewsLoading {
func latest() async throws -> [NewsRow] {
try await Task.sleep(for: .milliseconds(500))
return [NewsRow(id: "release", title: "Release checklist updated")]
}
}
@MainActor
@Observable
final class NewsFeedModel {
private(set) var rows: [NewsRow] = []
private(set) var isLoading = false
private(set) var errorMessage: String?
private var generation: UUID?
private let loader: any NewsLoading
init(loader: any NewsLoading) { self.loader = loader }
func reload() async {
guard !Task.isCancelled else { return }
let id = UUID()
generation = id
isLoading = true
errorMessage = nil
defer {
if generation == id { isLoading = false }
}
do {
let loaded = try await loader.latest()
try Task.checkCancellation()
guard generation == id else { return }
rows = loaded
} catch {
guard generation == id, !Task.isCancelled,
!(error is CancellationError) else { return }
errorMessage = "Could not refresh. Existing news is still available."
}
}
}
@MainActor
struct NewsFeedScreen: View {
@State private var model = NewsFeedModel(loader: PreviewNewsLoader())
var body: some View {
VStack {
if let errorMessage = model.errorMessage { Text(errorMessage) }
List(model.rows) { row in Text(row.title) }
.overlay {
if model.isLoading && model.rows.isEmpty {
ProgressView("Loading news")
}
}
.refreshable { await model.reload() }
}
.task { await model.reload() }
}
}The system refresh indicator follows the refresh call, while isLoading describes the model's latest request. Their lifetimes can differ if another caller starts a newer load. This design does not secretly cancel earlier requests or deduplicate network work; add a separate service policy if reducing overlap matters. Unlike a nested Task, the direct call stays inside its caller's cancellation context. Apple: refreshable handler and indicator lifetime, Apple: view task lifetime
Verify: Hold an initial load, start refresh, then complete refresh successfully and fail the old load. The new rows and lack of an old error must remain. Reverse the order and assert that old cleanup cannot hide the newer loading state. Keep the refresh pending and inspect the spinner; release or fail it and verify the indicator ends. Cancel before publication and confirm rows remain unchanged. Decide explicitly whether subsequent appearances should reload or reuse successful data; that policy is separate from fixing refresh completion.
SWIFT-55 — Answer
Short answer: Create one draft in the flow's owner and pass that same model through the environment. A child can use Bindable to form editable bindings without creating another draft, while validation is derived from the current fields. Previews and tests must supply the required environment model too.
Detailed explanation:
Create the draft once in its flow owner, inject that instance with .environment(draft), and read it with @Environment(Draft.self). A local @Bindable supplies writable projections for fields; it does not create another draft. Derive validity from current fields instead of synchronizing a second boolean. Required environment injection must also exist in previews and tests.
In a checkout shipping form, city and postal code are edited in one child while a summary reads the same model. This complete iOS 17+ example uses a deliberately small local rule: city must be nonempty and postal code must be five ASCII digits. Real international addresses need country-specific validation rather than this illustrative rule.
import SwiftUI
import Observation
import Foundation
struct ShippingFormSnapshot: Equatable {
let city: String
let postalCode: String
}
@MainActor
@Observable
final class ShippingFormDraft {
var city = ""
var postalCode = ""
private(set) var saved: ShippingFormSnapshot?
var normalizedCity: String {
city.trimmingCharacters(in: .whitespacesAndNewlines)
}
var normalizedPostalCode: String {
postalCode.trimmingCharacters(in: .whitespacesAndNewlines)
}
var validationMessage: String? {
guard !normalizedCity.isEmpty else { return "Enter a city." }
let digits = Array(normalizedPostalCode.utf8)
guard digits.count == 5,
digits.allSatisfy({ (48...57).contains($0) }) else {
return "Enter a five-digit postal code."
}
return nil
}
func saveLocally() {
guard validationMessage == nil else { return }
saved = ShippingFormSnapshot(
city: normalizedCity, postalCode: normalizedPostalCode
)
}
}
@MainActor
struct ShippingSetup: View {
@State private var draft = ShippingFormDraft()
var body: some View {
VStack {
ShippingFields()
ShippingSummary()
}
.environment(draft)
}
}
@MainActor
struct ShippingFields: View {
@Environment(ShippingFormDraft.self) private var draft
var body: some View {
@Bindable var editable = draft
Form {
TextField("City", text: $editable.city)
TextField("Postal code", text: $editable.postalCode)
.keyboardType(.numberPad)
Button("Save shipping address") { draft.saveLocally() }
.disabled(draft.validationMessage != nil)
}
}
}
@MainActor
struct ShippingSummary: View {
@Environment(ShippingFormDraft.self) private var draft
var body: some View {
VStack {
Text(draft.validationMessage ?? "Address is ready to save.")
if let saved = draft.saved {
Text("Saved: \(saved.city), \(saved.postalCode)")
}
}
}
}SwiftUI tracks the observable properties read while computing these views, including fields accessed by the computed validation. The computed property has no side effects and is cheap; it is not a cached server validation. The numeric keyboard is an input aid, so pasted or programmatic text still needs validation. No Combine publisher or onChange synchronization is required for this local derived state. Apple: Bindable and environment projection, Apple: Observation data flow
Verify: Construct ShippingSetup() in a preview, or explicitly inject ShippingFormDraft() when previewing an individual child. Omitting the required nonoptional environment model is a configuration error, not a fallback draft. Edit both fields and confirm the summary updates immediately; test whitespace, pasted nondigits, and valid input. Saving creates a value snapshot; later unsaved edits do not mutate it. For remote saving, add an async operation with owned loading/error/cancellation state rather than starting network work inside validationMessage.
SWIFT-56 — Answer
Short answer: No, adapting a publisher to async iteration does not promise replay or unlimited buffering. A hot source may emit before subscription or while the consumer cannot accept another value. Choose an explicit delivery policy, such as keeping the latest pending progress value, and use a lossless contract when no event may be dropped.
Detailed explanation:
.values adapts a publisher to asynchronous iteration; it is not a promise of unlimited buffering or replay. A hot subject can emit before subscription or while there is no outstanding demand, so a busy consumer must not assume every event is retained. For progress, explicitly keep the latest pending value; for required events, choose a lossless protocol instead.
This complete bridge subscribes synchronously during initialization and requests unlimited demand through sink. Its stream stores at most one pending progress value. It deliberately accepts only a nonfailing publisher; a throwing source needs an explicit error-to-stream completion design, not silent error removal. The adapter owns only its subscription, not a shared download producer.
import Combine
import Foundation
@MainActor
final class LatestProgressBridge {
let values: AsyncStream<Int>
private let continuation: AsyncStream<Int>.Continuation
private var subscription: AnyCancellable?
init(upstream: AnyPublisher<Int, Never>) {
let pair = AsyncStream<Int>.makeStream(
bufferingPolicy: .bufferingNewest(1)
)
values = pair.stream
continuation = pair.continuation
subscription = upstream.sink(
receiveCompletion: { @Sendable _ in pair.continuation.finish() },
receiveValue: { @Sendable value in pair.continuation.yield(value) }
)
continuation.onTermination = { [weak self] _ in
Task { @MainActor [weak self] in self?.stop() }
}
}
func stop() {
subscription?.cancel()
subscription = nil
continuation.finish()
}
}
@MainActor
func displayProgress(
from publisher: AnyPublisher<Int, Never>,
update: @MainActor (Int) -> Void
) async {
let bridge = LatestProgressBridge(upstream: publisher)
defer { bridge.stop() }
for await progress in bridge.values {
guard !Task.isCancelled else { return }
update(progress)
if progress >= 100 { return }
}
}
@MainActor
func verifyBufferedProgressBurst() async -> [Int] {
let subject = PassthroughSubject<Int, Never>()
let bridge = LatestProgressBridge(upstream: subject.eraseToAnyPublisher())
defer { bridge.stop() }
subject.send(10)
subject.send(20)
subject.send(30)
subject.send(completion: .finished)
var received: [Int] = []
for await value in bridge.values { received.append(value) }
return received
}The controlled burst returns [30]: no consumer was awaiting during emission, and the adapter intentionally replaced older pending values. Producer delivery can occur off MainActor because these sink closures only yield/finish a thread-safe continuation; the UI consumer and subscription owner remain MainActor-isolated. Termination requests cleanup through an actor hop, while the consumer's defer stops its subscription directly on every exit. A source that emits before this adapter subscribes cannot be repaired retroactively. Apple: publisher values, Apple: PassthroughSubject drops and demand, Apple: subscriber demand and sink, Swift: stream buffering and termination
Verify: Assert the burst result without sleeps. Start consuming before sending another controlled sequence, then cancel or return early and observe upstream subscription cancellation. A bounded Combine buffer before .values can suit some pipelines, but its overflow policy must still be explicit. For payment/audit events, use acknowledgements, durable storage/replay, or a true producer-backpressure contract; a larger dropping buffer only postpones loss, and an unbounded buffer can exhaust memory.
SWIFT-57 — Answer
Short answer: Timer events can be delayed or skipped, so counting them is not a reliable measure of elapsed time. Recalculate the displayed remaining time from the expiry date whenever the display refreshes or the app becomes active. The timer updates presentation; the server remains responsible for deciding whether the challenge has expired.
Detailed explanation:
Timer events are opportunities to refresh the display, not an accurate count of elapsed seconds. Retain a stable publisher and compute remaining time from an expiry date on each event. .onReceive handles publisher output synchronously; a view-owned .task can instead await a cancellable sleep loop. Neither mechanism keeps background execution alive or decides server-side expiry.
For a verification-code screen, the parent supplies a fixed expiry date from its challenge data. This complete view keeps its autoconnecting publisher in SwiftUI state so unrelated body reconstruction does not replace that publisher. An active-scene transition refreshes the displayed time immediately.
import SwiftUI
import Combine
import Foundation
@MainActor
struct CodeExpiryPublisherView: View {
let expiresAt: Date
@Environment(\.scenePhase) private var scenePhase
@State private var now = Date()
@State private var ticks = Timer.publish(
every: 1, on: .main, in: .common
).autoconnect()
private var remainingSeconds: Int {
Int(min(3_600, max(0, ceil(expiresAt.timeIntervalSince(now)))))
}
var body: some View {
Text("Code expires in \(remainingSeconds) seconds")
.onReceive(ticks) { now = $0 }
.onChange(of: scenePhase) { _, phase in
if phase == .active { now = Date() }
}
.onChange(of: expiresAt) { _, _ in now = Date() }
}
}The one-hour cap is this screen's display policy for a short-lived challenge, not a server validity rule. A delayed timer event may skip several second labels, and recomputing from the date catches up correctly. Timer.TimerPublisher is connectable; autoconnect() connects through its subscriptions. SwiftUI owns the .onReceive subscription, but a view still retained in a hierarchy is not guaranteed to stop merely because it is visually covered. Give application-scoped timers an explicit connection owner when that lifecycle matters. Apple: timer publishers and autoconnect, Apple: onReceive
Here is a complete alternative with the same date-based display policy. The task belongs to this view identity and expiry ID, and exits on expiry or cancellation; it does not spawn an unstructured nested task.
import SwiftUI
import Foundation
@MainActor
struct CodeExpiryTaskView: View {
let expiresAt: Date
@Environment(\.scenePhase) private var scenePhase
@State private var now = Date()
private var remainingSeconds: Int {
Int(min(3_600, max(0, ceil(expiresAt.timeIntervalSince(now)))))
}
var body: some View {
Text("Code expires in \(remainingSeconds) seconds")
.task(id: expiresAt) {
do {
while !Task.isCancelled {
now = Date()
guard now < expiresAt else { return }
try await Task.sleep(for: .seconds(1))
}
} catch is CancellationError {
return
} catch {
assertionFailure("Unexpected sleep error: \(error)")
}
}
.onChange(of: scenePhase) { _, phase in
if phase == .active { now = Date() }
}
}
}Verify: Supply an expiry ten seconds ahead, delay delivery or suspend the app, then reactivate and compare the displayed value with the supplied date rather than the number of ticks. Remove the task view and inspect cancellation, then change its expiry and confirm task restart. Test already-expired dates. Date follows wall-clock adjustments; a local elapsed-duration timer should use an appropriate monotonic clock. Authentication still asks the server whether a code is valid, so manipulating a client clock cannot extend the challenge. A TimelineView is another option when the only need is scheduled display recomputation.
SWIFT-58 — Answer
Short answer: No, creating a Task schedules separate work and returns a handle, so the next line does not wait for that UI update. Awaiting MainActor.run does wait for its synchronous body to finish. Keep related UI state changes under one owner, and check cancellation and request identity after asynchronous service work.
Detailed explanation:
Task { @MainActor in ... } schedules a new unstructured task and returns its handle; the next line does not wait for that update. await MainActor.run returns only after its synchronous body finishes on MainActor. Keep related UI mutations together, check cancellation, and guard request identity after suspension. An entirely MainActor-isolated orchestration method often needs fewer explicit hops.
This complete checkout example makes a deliberately non-UI preparation boundary explicit with @concurrent (Swift 6.2+). The UI owner assigns a request ID before service work starts and accepts a destination only for the current request. The fake service is cancellable and supplies all required types.
import Observation
import Foundation
struct CheckoutDestination: Equatable, Sendable {
let reservationID: String
}
protocol CheckoutPreparing: Sendable {
func prepare(cartID: String) async throws -> CheckoutDestination
}
struct PreviewCheckoutPreparer: CheckoutPreparing {
func prepare(cartID: String) async throws -> CheckoutDestination {
try await Task.sleep(for: .milliseconds(300))
return CheckoutDestination(reservationID: "reservation-\(cartID)")
}
}
@MainActor
@Observable
final class CheckoutNavigation {
private(set) var isLoading = false
private(set) var destination: CheckoutDestination?
private(set) var errorMessage: String?
private var currentRequest: UUID?
func begin() -> UUID {
let id = UUID()
currentRequest = id
isLoading = true
destination = nil
errorMessage = nil
return id
}
func succeed(_ route: CheckoutDestination, request: UUID) {
guard currentRequest == request else { return }
destination = route
finish(request: request)
}
func fail(request: UUID) {
guard currentRequest == request else { return }
errorMessage = "Could not prepare checkout. Please try again."
finish(request: request)
}
func finish(request: UUID) {
guard currentRequest == request else { return }
currentRequest = nil
isLoading = false
}
}
@concurrent
func prepareCheckout(
cartID: String,
service: any CheckoutPreparing,
navigation: CheckoutNavigation
) async {
guard !Task.isCancelled else { return }
let request = await MainActor.run { navigation.begin() }
do {
try Task.checkCancellation()
let route = try await service.prepare(cartID: cartID)
try Task.checkCancellation()
await MainActor.run {
guard !Task.isCancelled else {
navigation.finish(request: request)
return
}
navigation.succeed(route, request: request)
}
} catch {
let wasCancelled = Task.isCancelled || error is CancellationError
await MainActor.run {
if wasCancelled || Task.isCancelled {
navigation.finish(request: request)
} else {
navigation.fail(request: request)
}
}
}
}After awaiting prepareCheckout, its caller knows the selected terminal UI transition has completed, although another request may have superseded it. The synchronous MainActor.run body cannot itself await; make a model method async when UI orchestration needs suspension. Actor isolation serializes each segment, not the whole network operation, so request identity still matters. Apple: MainActor.run, Swift: unstructured tasks versus structured calls, Swift: explicit concurrent execution
Verify: Start A then B with controlled service completions, finish B, and finish or fail A afterward. B's destination must remain, and A must not clear B's loading state. Cancel before publication and verify loading ends without a new destination or failure message. Compare with a synchronous MainActor function that creates Task { @MainActor in ... } and immediately reads state: creating the task is not an awaited sequencing guarantee. For a screen model, prefer @MainActor func prepare(...) async with direct state assignments unless a non-UI orchestration boundary actually requires MainActor.run.
