SwiftUI
SwiftUI is Apple's declarative UI framework: views as values, modifiers, state-owning property wrappers, navigation stacks and animation. Interviews test reasoning in state changes, not view objects.
on this pageshowhide
explore
- Views and Composition17 questions
- Declarative Rendering Model5 questions
- Identity and Lifetime6 questions
- Reusable Components and Styles6 questions
- Visual Content18 questions
- Text Rendering and Fonts6 questions
- Images and Symbols6 questions
- Shapes, Drawing and Effects6 questions
- Lists and Scrolling11 questions
- Sections, Rows and Editing5 questions
- Lazy Stacks and Paging6 questions
- Modifiers and Layout Negotiation32 questions
- Ordering and Propagation4 questions
- Size Proposals and Frames6 questions
- Stacks and Alignment5 questions
- Grids and Adaptive Arrangement5 questions
- Geometry and Preferences6 questions
- Flow and Radial Containers6 questions
- Sources of Truth30 questions
- View-Owned Values and Bindings5 questions
- Observation-Based Models5 questions
- Object Ownership Wrappers5 questions
- Environment Values and Injection5 questions
- Defaults and Scene Restoration5 questions
- Architecture and View Models5 questions
- Navigation Containers and Modals22 questions
- Animating State Changes16 questions
- Implicit and Explicit Triggers6 questions
- Insertion and Hero Effects5 questions
- Keyframes and Custom Interpolation5 questions
- User Input and Controls22 questions
- Form Elements and Pickers6 questions
- Keyboard Entry and Focus5 questions
- Gestures5 questions
- Drag, Drop and Sharing6 questions
- Accessible, Localized Interfaces11 questions
- VoiceOver and Dynamic Type6 questions
- Strings and Locale Formatting5 questions
- Lifecycle and Previews16 questions
- Apps, Scenes and Windows6 questions
- Appearance and Async Work5 questions
- Mock Data and Canvas5 questions
- Testability and Profiling12 questions
- Unit and Snapshot Checks6 questions
- Redraw Cost and Diagnosis6 questions
questions
207 · 11 sectionsIn SwiftUI, why is a view a lightweight struct whose body SwiftUI reads repeatedly, rather than a long-lived object you update?
basics
~20 sA SwiftUI view is a value describing what to show for its current inputs. SwiftUI reads its body whenever an update needs it and redraws only the affected parts, so view structs are recreated often and must stay cheap.
In SwiftUI, a view struct is recreated on every parent update, so why does its @State value survive, and what makes it start over?
basics
~20 sSwiftUI keeps @State storage outside the view struct and ties it to the view's identity, not the struct instance. A recreated struct reuses that storage; removing the view or changing its identity discards it, so the next view starts fresh.
How do you build a reusable SwiftUI container view, such as a card, that takes caller-supplied content through a @ViewBuilder parameter?
basics
~10 sMake the container generic over Content: View, mark its initializer's closure parameter @ViewBuilder, call the closure and store the result, then place that content inside the container's own layout and decoration in body.
In SwiftUI, what does some View on body promise, and how can if/else or switch inside body return different view types?
basics
~20 sThe some View type promises one concrete view type that the compiler infers and hides. Because body is a view builder, if/else and switch branches fold into a single conditional type, so each branch may hold a different view.
In a SwiftUI chat thread built with ForEach, why do message rows lose their expanded state, and how should each row be identified?
basics
~20 sForEach ties each row's identity, and so its @State, to the element's ID. Index IDs, id: .self on mutable values, fresh UUIDs per fetch and duplicate IDs all break that; conform messages to Identifiable with a stable, unique server ID.
In SwiftUI, how does an SF Symbol from Image(systemName:) differ from an asset-catalog Image(_:) in how it sizes and takes colour?
basics
~20 sAn SF Symbol behaves like a text glyph: font(:) and imageScale(:) size it and foregroundStyle colours it. A bitmap asset draws at its natural point size in its own colours until you make it resizable() or template-rendered.
In SwiftUI, how do you draw a custom shape, such as a fitness app's speed gauge arc, by conforming to the Shape protocol?
basics
~10 sConform a struct to Shape and implement path(in:), building a Path from the CGRect SwiftUI passes in. The shape is itself a view: frame sizes it, and fill or stroke styles it.
In SwiftUI, why does Text render **Pending** in bold from a string literal but show the asterisks when it comes from a String variable?
basics
~20 sA string literal passed to Text becomes a LocalizedStringKey, and SwiftUI parses inline Markdown in it. A String variable goes through Text's plain-string initializer, which shows the characters as they are; parse runtime Markdown with AttributedString(markdown:).
In SwiftUI, why should a transaction row use font(.headline) or another text style rather than .system(size: 17), and how do custom fonts keep scaling?
basics
~20 sA text style such as .headline resolves to a size that follows the user's Dynamic Type setting, while .system(size: 17) stays at 17 points. Custom fonts scale through Font.custom(_:size:), like body or like the style named in relativeTo:.
In SwiftUI, how do you show a placeholder, the loaded recipe photo and an error state with AsyncImage, and where do image modifiers go?
basics
~20 sUse AsyncImage's phase initialiser: its closure receives AsyncImagePhase, and you return a placeholder for .empty, the image for .success and an error view for .failure. Image modifiers such as resizable() go on the Image inside the closure.
In SwiftUI, how do you show a mail inbox grouped by day in a List with Section headers, and let people swipe to delete a message?
basics
~20 sBuild the List from a ForEach over the days, wrap each day's ForEach of messages in a Section with a header, and attach onDelete(perform:) to that inner ForEach; SwiftUI adds swipe to delete and hands you the row offsets.
In SwiftUI, how do List selection, EditButton and the editMode environment value work together so iPhone users can multi-select inbox messages?
basics
~20 sBind List(selection:) to a Set of the rows' ID type; on an iPhone, tap multi-selection works only in edit mode, which EditButton toggles through the editMode environment value that your own views can read or own.
In a SwiftUI List, how do swipeActions differ from onDelete, and why does swipe to delete vanish once you add an Archive swipe action?
basics
~10 sonDelete gives every row one built-in Delete; swipeActions(edge:allowsFullSwipe:content:) lets you supply your own buttons per edge. Once a row has swipe actions, SwiftUI stops synthesizing the Delete, so you add a destructive Button yourself.
In SwiftUI, what changes when you replace a VStack with a LazyVStack inside a ScrollView, and when should you keep the VStack?
basics
~20 sA VStack inside a ScrollView creates and lays out every child at once; a LazyVStack creates rows only as they are about to render. Keep the VStack for modest content: Apple advises switching only when profiling shows a gain.
In a SwiftUI timeline built with a LazyVStack, how do you load older posts as the user nears the bottom without duplicate loads?
basics
~20 sTrigger the load from a row the LazyVStack creates only near the end, usually the last post's onAppear, and make the model's load idempotent with isLoading and hasMore guards. Append each page so existing rows keep their identity.
In SwiftUI, how do you adapt a screen's layout for iPad by reading horizontalSizeClass and verticalSizeClass from the environment?
basics
~20 sSwiftUI publishes horizontal and vertical size classes as environment values, each compact or regular; read them with @Environment, branch the layout on them, and expect them to change at runtime with rotation, Split View and Slide Over.
In SwiftUI, why does `.padding().background(.yellow)` look different from `.background(.yellow).padding()` on the same Text?
basics
~20 sEach SwiftUI modifier wraps the view built so far, so background(_:) paints only the bounds of what it wraps: after padding it fills the padded area, before padding it hugs the text and the padding stays clear.
In SwiftUI, what is the difference between frame(width:height:) and frame(maxWidth: .infinity), and when do you use each?
basics
~20 sframe(width:height:) makes a fixed-size frame that reports exactly those dimensions whatever its child picks. frame(maxWidth: .infinity) makes a flexible frame that grows to the width its parent offers, so a background or button can span the row.
In SwiftUI, what does the alignment parameter of HStack, VStack and ZStack control, and how does a Spacer change a stack's layout?
basics
~20 sA stack's alignment positions its children on the cross axis: VStack takes a HorizontalAlignment, HStack a VerticalAlignment, ZStack a two-axis Alignment, all defaulting to center. A Spacer expands along the stack's main axis, pushing siblings apart.
Why does wrapping a view in SwiftUI's GeometryReader often break the surrounding layout, and how do you measure without that side effect?
basics
~20 sGeometryReader reports a flexible size, so it takes all the space its parent offers and ignores its content's size. Wrapped around a view it bloats or squeezes the layout; put it in .background or .overlay so it adopts the measured view's size instead.
In SwiftUI, how does @AppStorage persist a setting such as a reader's font size, and which value types can it store?
basics
~20 s@AppStorage binds a view property to a UserDefaults key: it reads the stored value or the declared default, writes on assignment and updates the view on change. It stores Bool, Int, Double, String, URL, Data, Date (iOS 18) and String- or Int-backed enums.
In SwiftUI, how do you read a system environment value such as colorScheme or dismiss with @Environment, and where does that value come from?
basics
~20 sDeclare a property such as @Environment(.colorScheme) var colorScheme, naming a key path into EnvironmentValues. The value is inherited from the view's ancestors; SwiftUI fills many values from system settings and updates views that read them when they change.
In SwiftUI, how does a child view edit a value its parent owns in @State, and what does the $ prefix give you?
basics
~20 sThe child declares a @Binding property and the parent passes $value, the state's projectedValue, which is a Binding: a read-write reference to the parent's storage with no storage of its own, so the child's writes update the parent's state.
In SwiftUI, why does a view use @State for a value it changes, instead of a plain var stored property on the view struct?
basics
~20 sA SwiftUI view is a short-lived struct whose body cannot mutate it. @State keeps the value in storage SwiftUI manages outside the struct, so writes survive the struct being recreated and update the views that read the value.
In SwiftUI, what does marking a model class with the @Observable macro give you, and when do you add @ObservationIgnored to a property?
basics
~20 sThe @Observable macro from Apple's Observation framework makes a class's stored var properties observable with no @Published, so a SwiftUI view that reads one redraws when it changes. @ObservationIgnored opts out a property that no view displays.
In SwiftUI, how do you make a view fade or slide in and out when it is shown or hidden with transition(_:)?
basics
~10 sShow the view inside an if, attach transition(.opacity) or transition(.move(edge: .top)) to it, and toggle the Boolean inside withAnimation. SwiftUI then animates the view in on insertion and out on removal.
In SwiftUI, why does transition(_:) play only on insertion or removal, and how do you make a toast slide in but fade out?
basics
~20 sA transition describes how a view enters or leaves the hierarchy, so a view that only changes values never uses it. Insert the toast with an if in an animated change and give it .asymmetric(insertion: .move(edge: .top), removal: .opacity).
In SwiftUI, what is the difference between animation(_:value:) and withAnimation, and which views animate with each?
basics
~10 sanimation(_:value:) is a modifier that animates one view's subtree only when a watched Equatable value changes; withAnimation wraps a state mutation so every view whose rendering that mutation changes animates.
A SwiftUI custom ProgressRing Shape with a stored progress property jumps to its new value even inside withAnimation; why, and how do you fix it?
basics
~20 sShape conforms to Animatable, but without an animatableData implementation it falls back to EmptyAnimatableData, so SwiftUI has nothing to interpolate and draws the end state. Expose progress through animatableData, or build the ring from Circle().trim(from:to:).
In SwiftUI, how do you make a loading indicator cycle through several looks with phaseAnimator, and what does adding a trigger change?
basics
~20 sApply phaseAnimator(_:content:animation:) (iOS 17) with a sequence of Equatable phases; SwiftUI animates each phase into the next and loops while the view is shown. With a trigger, it waits on the first phase and runs one pass per change.
In SwiftUI, how do you bind a Toggle and a Picker over an enum to a settings screen's state?
basics
~20 sBind a Toggle to a Bool with Toggle("Title", isOn: $flag) and a Picker to an enum with Picker("Title", selection: $choice); give every row a tag of that enum type, which ForEach over an Identifiable enum does for you.
In SwiftUI, how do you respond to taps with onTapGesture, and when should a Button replace the tap gesture?
basics
~20 sAttach onTapGesture(count:perform:) to a view to run code on a tap, or on a double tap with count: 2. When the view behaves like a button, use Button instead: it brings the standard button behaviour and accessibility users expect.
In SwiftUI, how do you configure TextField and SecureField for a checkout sign-in's email and password so the keyboard and AutoFill fit each field?
basics
~10 sBind a TextField and a SecureField to String state, then describe each field: keyboardType(.emailAddress), textContentType(.username), textInputAutocapitalization(.never) and autocorrectionDisabled() on the email, and textContentType(.password) on the SecureField so AutoFill can help.
In SwiftUI, how does putting controls inside a Form with Sections change how they look on iOS, and how do you override that?
basics
~20 sForm applies platform styling to the controls inside it: on iOS it is a grouped list where each Toggle, Picker, DatePicker and Button becomes a row. Override per control or subtree with pickerStyle, toggleStyle, datePickerStyle, formStyle and controlSize.
In SwiftUI, how do you keep a sign-up Form's Create button disabled until the form is valid, and show inline validation messages?
basics
~20 sCompute validity from the form's state in a computed property, apply .disabled(!isValid) to the Create button only, and show each message conditionally next to its control or in its Section footer, once the user has entered something.
In SwiftUI, how do you make an icon-only play button readable by VoiceOver, and what does SwiftUI already infer from Text, Image and Button?
basics
~20 sSwiftUI reads a Text's string, gives a Button its label content plus the button trait, and skips Image(decorative:). An icon-only button needs a spoken name: give it a title and hide it with .labelStyle(.iconOnly), or add .accessibilityLabel("Play").
In SwiftUI, why does Text("Welcome back") show a translation while Text(hotelName) with a String variable does not, and what does Text(verbatim:) do?
basics
~20 sA string literal passed to Text becomes a LocalizedStringKey and is looked up in the app's strings; a String variable selects the StringProtocol initializer and is shown as written. Text(verbatim:) shows a literal without any lookup.
In SwiftUI, how does accessibilityElement(children:) with .combine, .contain or .ignore change what VoiceOver reads for a music track row?
basics
~10 saccessibilityElement(children:) turns a container into one element: .combine merges the children's labels into it, .contain keeps them as separate children inside a group, and .ignore hides them so you must supply the label yourself.
In SwiftUI, how do @ScaledMetric and the dynamicTypeSize environment value keep a now-playing header usable at the largest accessibility text sizes?
basics
~20 sText in text styles scales with Dynamic Type; fixed numbers do not. @ScaledMetric scales a number, such as an artwork size, along a text style's curve, and reading dynamicTypeSize lets a layout stack vertically when isAccessibilitySize is true.
In SwiftUI, how does Text("\(nights) nights") become a String Catalog key, and how does the catalog supply Arabic's plural forms?
basics
~20 sInterpolating an Int into a Text literal produces the key "%lld nights". The String Catalog stores plural variations for that key per language, and the number picks the category: one and other in English and German, six categories in Arabic.
In SwiftUI, when do onAppear and onDisappear run, and why can onAppear fire more than once for one screen?
basics
~20 sonAppear runs its closure before a view appears on screen and onDisappear after it leaves; both follow appearance, not the view struct's init, so a screen shown again after navigation, a tab switch or scrolling can fire onAppear again.
In SwiftUI, what does an @main App type declare, and how does a WindowGroup turn its content into windows?
basics
~20 sA type conforming to App and marked @main is the app's single entry point, and its body returns scenes. A WindowGroup's content is a template: every window it creates gets its own view hierarchy and its own @State storage.
How do you keep a SwiftUI view's previews fast and offline when the screen normally loads its feed from a network client?
basics
~20 sA SwiftUI preview runs the view's real code, so a client built inside the view calls the network. Inject the client through init or the environment, give previews a mock with fixtures, and fence that code with #if DEBUG.
In SwiftUI, why is the task modifier usually preferred over onAppear with a Task inside for loading a screen's data?
basics
~20 sThe task modifier starts async work before the view appears and SwiftUI cancels it after the view disappears; a Task created inside onAppear is unstructured, keeps running after the user leaves, and needs a stored handle to cancel.
In SwiftUI, how does the scenePhase environment value differ when read in a view versus in the App, and where do you save edits?
basics
~20 sRead in a view, scenePhase is the phase of the scene containing that view; read in the App, it aggregates every scene. Save a window's edits from its own view when that scene's phase changes; free app-wide resources in the App.
In SwiftUI, why is building a formatter or sorting and filtering a large array inside body a performance problem, and where should that work go?
basics
~20 sSwiftUI can re-run a view's body many times, on the main actor, whenever something it depends on changes, so work inside body repeats on every update. Use format styles, and compute sorted or filtered data once, when its inputs change.
In SwiftUI, why move a login screen's logic from body into an @Observable model, and what can a test check that a preview cannot?
basics
~20 sA SwiftUI body is a description SwiftUI evaluates on its own schedule, and SwiftUI manages @State storage for installed views. Logic in an @Observable model can be created, driven and asserted on in a unit test; a preview only shows a state.
In SwiftUI, how do you unit test an @Observable login view model against a fake auth service, and what should that test assert?
basics
~20 sPut the auth service behind a protocol passed to the @Observable model's init, and give the test a fake returning a canned success or error. Create the model directly, await signIn(), and assert on the state the view renders.
In a SwiftUI stocks dashboard backed by one ObservableObject, a price tick every second re-runs the header, the chart and all 500 rows; why, and how do you narrow it?
basics
~20 sAny @Published change fires objectWillChange, and every view observing that ObservableObject re-runs, read or not. Move to @Observable (iOS 17) with one object per symbol, mutate prices in place, and read each price only in its row.
In SwiftUI, what does accessibilityIdentifier(_:) add to a login screen's Sign In button, and why do UI tests prefer it to the button's label?
basics
~20 saccessibilityIdentifier(_:) attaches a string to the view's accessibility element for tests; users never see or hear it. UI tests prefer it because the label is localized and reworded, while an identifier like login.signIn stays stable.