In short
- Predict the behaviour before you read the explanation, then compare the 2 answers.
- Visual similarity does not make a row's identity stable.
- Bindable supplies bindings. It does not take ownership of the model.
- Task cancellation and result relevance are 2 separate checks.
- Change 1 condition, predict again, and compare the new answer with your first recording.
The editor receives a new title from its parent. The text field keeps showing the old title.
“SwiftUI didn't refresh” is a description of the surprise. It does not identify whether the editor was supposed to accept a new input or preserve a draft the user had already changed.
That distinction makes a useful practice exercise. Before changing a property wrapper, establish who owns the value and which event is allowed to replace it.
This page turns that habit into 8 exercises. They cover state, identity, Observation, ownership, task lifetime, performance, layout and navigation. Each one starts with observable behaviour, asks for a prediction, gives a reasoned explanation, changes 1 condition and asks you to predict again. They are original practice prompts, not a frequency-ranked list of questions from named employers.
The modern Observation examples assume iOS 17 or later. A project supporting older systems may retain a different observation model.
How each exercise works
Each exercise has the same 4 steps.
- Read the setup and write your prediction in 1 or 2 sentences before you read on.
- Read the explanation and compare it with your prediction.
- Apply the changed condition and predict again.
- Run the check in a small host where you can.
1. Does a new input replace a local State value?
Consider an editor that takes its initial text from a parent.
import SwiftUI
struct SeededDraftEditor: View {
@State private var draft: String
init(seed: String) {
_draft = State(initialValue: seed)
}
var body: some View {
TextField("Draft", text: $draft)
}
}Predict before reading on. The parent passes a different seed while this editor keeps its identity. Must the text field replace its existing draft?
No. Treat the seed as an initial value for state owned by this editor, not a continuing assignment to that state. Recreating a view value does not imply that SwiftUI discards the existing state storage associated with the view's identity.[1][2]
The next step depends on the contract. If the parent owns the text throughout editing, pass a binding. If the editor owns a local draft, define when the draft is created, committed and discarded. If selecting a different document should create a new editing session, express that session's identity deliberately.
Change 1 condition. A server refresh delivers a new version of the document the user is editing, and the user has an unsaved edit to it. Should the refresh replace that edit?
Predict again. Write whether the draft changes, and what the editor should show about the external update.
Answer. No, not silently. The draft stays, because the edit is the user's work and the editor owns it. The editor should show that a newer version exists and let the user keep their edit or take the new version. Automatically copying every input change into local state may destroy the very draft you meant to preserve, and never copying it hides the update. That is a reconciliation decision, so say which one your UI makes.
Check. Edit the text, trigger an unrelated parent update, then change the selected document. Record which action should preserve the draft and which should start a new one. Test those expectations separately.
If you want to repeat this loop with feedback, Guided Practice in iOS Interview Training lets you answer realistic prompts, inspect weaknesses, revise your answer and compare attempts.
2. Which property wrapper belongs around an observable model?
Here is an intentionally small owner and editor pair.
import SwiftUI
@available(iOS 17.0, macOS 14.0, *)
@MainActor @Observable
final class ArticleDraft {
var title = "Untitled"
var backgroundCounter = 0
}
@available(iOS 17.0, macOS 14.0, *)
@MainActor
struct ArticleDraftOwner: View {
@State private var draft = ArticleDraft()
var body: some View {
ArticleDraftFields(draft: draft)
}
}
@available(iOS 17.0, macOS 14.0, *)
@MainActor
struct ArticleDraftFields: View {
@Bindable var draft: ArticleDraft
var body: some View {
TextField("Title", text: $draft.title)
}
}Predict before reading on. Which view creates the ArticleDraft, which view only edits it, and what does @Bindable add?
Start with ownership and access. A view can keep an owned observable model in state. A child can receive the model reference and read the properties it needs. A binding projection is useful when a control needs 2-way access to a model property.[3]
Answer. ArticleDraftOwner creates the draft and keeps it alive in @State. ArticleDraftFields only edits it. @Bindable adds the $draft.title binding that TextField needs and nothing else, so it is not a new owner. Observation also does not make arbitrary concurrent mutation safe. Actor isolation is a separate design choice, made explicit in this example with @MainActor.
Change 1 condition. A colleague proposes replacing every StateObject with State across the app, without changing the model type.
Predict again. Is that change safe, and what would you check before making it?
Here is the model that breaks under that change.
@MainActor
final class LegacyDraft: ObservableObject {
@Published var title = "Untitled"
}
@MainActor
struct LegacyDraftOwner: View {
@State private var draft = LegacyDraft()
var body: some View {
Text(draft.title)
}
}Answer. No, not without changing the model. @State does not observe an ObservableObject. The view updates only when the reference itself is replaced, so a change to title never reaches the screen and the view stops updating.[2] An @Observable model can live in @State, and @StateObject stays correct for an ObservableObject. Check the model type, the supported OS versions and who owns the object before touching the wrapper. Apple's migration guidance supports incremental adoption, and it notes that a model using the older system is tracked differently from an @Observable one.[3]
Also note that @State creates its default value every time SwiftUI creates the view, while the storage from the first creation is kept. Keep the initialiser of an owned model cheap.[2]
Check. Identify the creator, the lifetime owner and the editor. Explain each role without relying on the wrapper's name alone.
3. Does any model change invalidate every view that holds it?
Keep the ArticleDraft model from exercise 2. Its backgroundCounter changes.
Predict before reading on. Must the title editor update because it has a reference to the same observable object?
With Observation, SwiftUI tracks observable properties read while evaluating a view's body. The dependency is more specific than simply possessing a reference to the whole model.[4]
Answer. No. If the title editor's body reads only title, a change to backgroundCounter does not invalidate it. An ObservableObject behaves differently, because any published change updates the view.[3] Find the actual reads. A helper or computed property can read observable state during body evaluation too. Passing a reference to a child and reading a display property in the parent establish different dependencies.
Also separate a view update from a visible redraw. A body evaluation is a part of the UI pipeline; it does not establish that every pixel changed or that the update was expensive.
Change 1 condition. A helper builds the whole display string and reads several model fields during body evaluation.
Predict again. Which changes can now matter for this body?
Answer. Every field the helper reads now matters, including the counter, because the body evaluation made those reads. Trace the reads made during evaluation. If an expensive calculation depends on more state than necessary, consider a smaller dependency or a different placement for the work. Verify the cost before introducing a cache with its own invalidation problem.
Check. Change the title and counter independently in a small host, inspect the relevant evaluation behaviour and use a performance trace if the concern is cost. Do not turn a console message into a precise rendering benchmark.
4. Why does a row lose state when the list refreshes?
Scene. Editable rows look the same after a refresh, but their drafts disappear. Each row keeps a note in its own @State.
struct FetchedArticle: Identifiable {
let id = UUID()
let serverID: String
var title: String
}
struct SyncedArticle: Identifiable {
let serverID: String
var title: String
var id: String { serverID }
}
struct NoteRow: View {
let title: String
@State private var note = ""
var body: some View {
VStack(alignment: .leading) {
Text(title)
TextField("Note", text: $note)
}
}
}
struct ArticleList: View {
let articles: [FetchedArticle]
var body: some View {
List(articles) { article in
NoteRow(title: article.title)
}
}
}Predict before reading on. The list is built from FetchedArticle values, and every refresh decodes new values. What identity does SwiftUI see for each row after the refresh, and does it match the item the user edited?
Answer. FetchedArticle assigns a new UUID each time a value is created, so every refresh describes brand new items. SwiftUI drops the old rows with their note state and builds new ones. Feeding the list SyncedArticle values instead takes each row's identity from the server ID, so the same item keeps the same row and the same note. The content's visual similarity does not make its identity stable.[1]
A stable server ID can be appropriate when it identifies the same domain item. Include account or scope where the domain requires it. Avoid using an index when insertions or reordering should preserve state with the item.
Change 1 condition. A colleague proposes adding .id(...) to each row to make the refresh behave.
Predict again. Does the change fix the stale draft, and what else does it reset?
Answer. No. If the value passed to .id(...) is as unstable as the original ID, the rows are reset on every refresh again. If it is a value that changes on purpose, such as a refresh counter, it resets every row at once, and with it focus, running tasks, animations and local state. .id(...) is for deliberately starting a new lifetime, not for repairing an unstable identity. Fix the identity at its source. Applying .id(...) broadly to fix 1 stale field creates more consequences than it removes.
Check. Insert an item above the edited row, reorder the list and refresh the payload for the same ID. The draft should follow the intended item, not an accidental position.
5. Does a task with an id make every asynchronous result current?
Consider this view. The article ID changes while the view is still present.
import SwiftUI
struct ArticleTaskBoundary: View {
let articleID: String
let load: @Sendable (String) async -> Void
var body: some View {
Text(articleID)
.task(id: articleID) {
await load(articleID)
}
}
}Predict before reading on. What should happen to the loading task when articleID changes, and can the older request still change state?
Answer. SwiftUI cancels the running task and starts a new one for the new ID.[5] The older request can still change state if it ignores cancellation, because cancellation is only a request. Use an identity for the work as well as the UI. For the language side of cancellation, see Swift concurrency interview questions.
The injected operation still owns its publication rules. If it updates shared model state, define which request or session may commit a result after suspension. A cancellation request alone is not a complete account-isolation or latest-intent protocol.
Change 1 condition. The work must continue after the screen disappears.
Predict again. Does the view's task still own the work?
Answer. No. SwiftUI can cancel a view's task after the view disappears, so work that must finish needs another owner.[5] Identify its required lifetime. A durable user operation may need persistence and a different execution owner. A view's task is a useful boundary for work needed by that view, not a universal home for background business operations.
Check. Change the ID while the dependency is suspended, then complete the older request. Check which state it can change.
6. Is a frequently evaluated body necessarily the performance bug?
Scene. A counter shows repeated body evaluations while scrolling.
Predict before reading on. Should you immediately add equality wrappers or move all state into a single model?
Answer. No. First establish the user-visible problem. A cheap evaluation can be acceptable; a single expensive operation in the wrong phase can be the dominant cost. Inspect the expensive work, invalidating dependencies, identity changes and the conditions under which the regression occurs.[6]
Keep your comparison stable. Use representative hardware, build conditions, content and cache state. Say whether you are investigating evaluation work, layout, image preparation, memory or a blocked main thread.
Change 1 condition. The proposed fix reduces evaluation count, but scrolling becomes worse.
Predict again. What does the count tell you now?
Answer. It told you where to look and nothing more. The count was a diagnostic signal, not the outcome. Inspect the new cost or dependency introduced by the change. An equality decision can also conceal updates if its assumptions are wrong.
Check. Keep a reproducible scroll and compare the relevant trace and user-facing metric before and after. Avoid claiming a percentage improvement from a preview or a debug print.
7. Why doesn't an infinite-width frame force every child to expand?
Scene. Adding .frame(maxWidth: .infinity) does not produce the layout the candidate expected.
struct SavedBanner: View {
var body: some View {
HStack {
Text("Saved")
.frame(maxWidth: .infinity)
Image(systemName: "checkmark")
}
.padding()
.background(Color.green.opacity(0.2))
}
}Predict before reading on. Which view's size changes, and which view decides the final size?
Answer. The flexible frame takes the width the stack offers after the image has been placed. The Text inside keeps its own size and sits in the middle of that frame, and the image is not stretched at all. Because 1 child is flexible, the stack asks for all the width its parent offers, so the background spans the row. SwiftUI views choose sizes in response to proposals. A frame is part of that negotiation rather than a command that gives every descendant identical geometry.[7] Modifier order matters because it changes the nesting of layout participants.
Change 1 condition. The layout fails at an accessibility text size or in a narrow split view.
Predict again. What should change first, the fixed dimensions or the requirement?
Answer. The requirement. Adding fixed dimensions to this row can clip or crowd the content at a larger text size. Decide whether the layout should wrap, change arrangement, scroll or truncate, and test the content and accessibility consequences. ViewThatFits expresses one answer, which is to offer the horizontal arrangement first and a vertical one when the first does not fit.[8]
struct AdaptiveSavedBanner: View {
var body: some View {
ViewThatFits(in: .horizontal) {
HStack {
Text("Saved to your account")
Image(systemName: "checkmark")
}
VStack {
Image(systemName: "checkmark")
Text("Saved to your account")
}
}
.padding()
}
}A screenshot at 1 device width cannot settle an adaptive-layout question.
Check. Vary width, text size and localisation length independently. State which behaviour the product accepts for each constrained case.
8. What belongs in navigation state?
Scene. A deep link opens an article that is absent from the currently loaded feed. The stack's path holds article IDs.
struct FeedScreen: View {
let feed: [String]
let sessionID: String
@State private var path: [String] = []
var body: some View {
NavigationStack(path: $path) {
List(feed, id: \.self) { id in
NavigationLink(value: id) { Text(id) }
}
.navigationDestination(for: String.self) { id in
ArticleScreen(articleID: id)
}
}
.onChange(of: sessionID) {
path.removeAll()
}
}
func open(articleID: String) {
path = [articleID]
}
}
struct ArticleScreen: View {
let articleID: String
@State private var content: String?
var body: some View {
Text(content ?? "Loading \(articleID)")
.task(id: articleID) {
content = await fetchArticle(id: articleID)
}
}
func fetchArticle(id: String) async -> String? {
"Article \(id)"
}
}Predict before reading on. open(articleID:) is called with an ID that is not in feed. How does the destination obtain its data, and does a visible row need to stay alive for it?
Answer. The destination needs only the ID. Setting path to [articleID] pushes ArticleScreen, which loads its own content, so no row has to exist.[9] Represent the destination with a stable route or identifier and resolve the content through an appropriate data owner. Do not require a visible row to remain alive merely so the destination can keep a reference to its temporary state.
Distinguish route restoration from data freshness. Restoring an article ID does not prove that its content is available, authorised or current. Design loading, unavailable and authentication-required outcomes explicitly.
Change 1 condition. The user signs out while the destination's request is running.
Predict again. Which session may still publish the result, and what happens to the route?
Answer. In this code the onChange closure, which needs iOS 17, clears the path, so ArticleScreen leaves the stack and its task is cancelled. That is not enough on its own. A fetch that ignores cancellation can still return, so the old session must lose the right to publish or populate account-scoped storage. Decide whether the route remains pending for a later sign-in or is dismissed. This is application policy, not a guarantee created by a navigation container.
Check. Open the route without the feed, recreate the relevant owner and switch accounts before a response completes.
Use the exercises as a short code-review interview
Choose 3 exercises. For each, state the behaviour contract, predict the outcome and name the smallest experiment that could reject your explanation. Ask a partner to change 1 condition after the first answer.
Keep the first recording. A useful correction names the boundary you misunderstood. Examples are initial state versus ongoing input, view identity versus value lifetime, and task cancellation versus result relevance.
The full question list is in SwiftUI interview questions. To see why the follow-up is where the round is decided, read the follow-up decides the senior mobile interview.
iOS Interview Training is $99, paid once. You keep the book and companion code, and you get 90 days of Guided Practice, where you answer realistic prompts, inspect weaknesses, revise your answer, handle changed constraints and compare attempts. It is structured practice, not live coaching with a person. You can read the free sample before buying.
Sources
- Apple, Demystify SwiftUI.
- Apple, State.
- Apple, Migrating to Observable.
- Apple, Managing model data.
- Apple, View task with an identity.
- Apple, Demystify SwiftUI performance.
- Apple, ProposedViewSize.
- Apple, ViewThatFits.
- Apple, NavigationStack.
Questions readers ask
© 2026 Mike Salari, Interview Runtime. All rights reserved. Quoting a short excerpt with a link to this page is welcome; republishing the article, in full or in part, is not.



