skip to content

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 pageshow

explore

questions

207 · 11 sections

In SwiftUI, why is a view a lightweight struct whose body SwiftUI reads repeatedly, rather than a long-lived object you update?

level: juniorimportance: must knowfreq 80%
basics
~20 s

A 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.

open as a page

In SwiftUI, a view struct is recreated on every parent update, so why does its @State value survive, and what makes it start over?

level: juniorimportance: must knowfreq 66%
basics
~20 s

SwiftUI 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.

open as a page

How do you build a reusable SwiftUI container view, such as a card, that takes caller-supplied content through a @ViewBuilder parameter?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Make 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.

open as a page

In SwiftUI, what does some View on body promise, and how can if/else or switch inside body return different view types?

level: middleimportance: must knowfreq 70%
basics
~20 s

The 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.

open as a page

In a SwiftUI chat thread built with ForEach, why do message rows lose their expanded state, and how should each row be identified?

level: middleimportance: must knowfreq 64%
basics
~20 s

ForEach 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.

open as a page

In SwiftUI, how does an SF Symbol from Image(systemName:) differ from an asset-catalog Image(_:) in how it sizes and takes colour?

level: juniorimportance: must knowfreq 70%
basics
~20 s

An 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.

open as a page

In SwiftUI, how do you draw a custom shape, such as a fitness app's speed gauge arc, by conforming to the Shape protocol?

level: juniorimportance: must knowfreq 65%
basics
~10 s

Conform 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.

open as a page

In SwiftUI, why does Text render **Pending** in bold from a string literal but show the asterisks when it comes from a String variable?

level: juniorimportance: must knowfreq 60%
basics
~20 s

A 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:).

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A 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:.

open as a page

In SwiftUI, how do you show a placeholder, the loaded recipe photo and an error state with AsyncImage, and where do image modifiers go?

level: middleimportance: must knowfreq 64%
basics
~20 s

Use 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.

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Build 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.

open as a page

In SwiftUI, how do List selection, EditButton and the editMode environment value work together so iPhone users can multi-select inbox messages?

level: middleimportance: must knowfreq 66%
basics
~20 s

Bind 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.

open as a page

In a SwiftUI List, how do swipeActions differ from onDelete, and why does swipe to delete vanish once you add an Archive swipe action?

level: middleimportance: must knowfreq 64%
basics
~10 s

onDelete 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.

open as a page

In SwiftUI, what changes when you replace a VStack with a LazyVStack inside a ScrollView, and when should you keep the VStack?

level: middleimportance: must knowfreq 75%
basics
~20 s

A 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.

open as a page

In a SwiftUI timeline built with a LazyVStack, how do you load older posts as the user nears the bottom without duplicate loads?

level: middleimportance: must knowfreq 68%
basics
~20 s

Trigger 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.

open as a page

In SwiftUI, how do you adapt a screen's layout for iPad by reading horizontalSizeClass and verticalSizeClass from the environment?

level: juniorimportance: must knowfreq 60%
basics
~20 s

SwiftUI 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.

open as a page

In SwiftUI, why does `.padding().background(.yellow)` look different from `.background(.yellow).padding()` on the same Text?

level: juniorimportance: must knowfreq 82%
basics
~20 s

Each 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.

open as a page

In SwiftUI, what is the difference between frame(width:height:) and frame(maxWidth: .infinity), and when do you use each?

level: juniorimportance: must knowfreq 72%
basics
~20 s

frame(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.

open as a page

In SwiftUI, what does the alignment parameter of HStack, VStack and ZStack control, and how does a Spacer change a stack's layout?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A 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.

open as a page

Why does wrapping a view in SwiftUI's GeometryReader often break the surrounding layout, and how do you measure without that side effect?

level: middleimportance: must knowfreq 68%
basics
~20 s

GeometryReader 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.

open as a page

In SwiftUI, how does @AppStorage persist a setting such as a reader's font size, and which value types can it store?

level: juniorimportance: must knowfreq 55%
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.

open as a page

In SwiftUI, how do you read a system environment value such as colorScheme or dismiss with @Environment, and where does that value come from?

level: juniorimportance: must knowfreq 68%
basics
~20 s

Declare 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.

open as a page

In SwiftUI, how does a child view edit a value its parent owns in @State, and what does the $ prefix give you?

level: juniorimportance: must knowfreq 80%
basics
~20 s

The 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.

open as a page

In SwiftUI, why does a view use @State for a value it changes, instead of a plain var stored property on the view struct?

level: juniorimportance: must knowfreq 85%
basics
~20 s

A 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.

open as a page

In SwiftUI, what does marking a model class with the @Observable macro give you, and when do you add @ObservationIgnored to a property?

level: juniorimportance: must knowfreq 72%
basics
~20 s

The @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.

open as a page

In SwiftUI, how do you present a sheet from a Boolean state value, and how does the sheet's own view close it?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Attach sheet(isPresented:) to a view and bind it to an @State Bool; setting it to true presents the content closure. Inside the sheet's own view, read @Environment(.dismiss) and call dismiss(), or set the Bool back to false.

open as a page

In SwiftUI, how do you build a tab bar with TabView and the Tab type, and what did Tab replace?

level: juniorimportance: must knowfreq 65%
basics
~20 s

Place one Tab per section inside a TabView: each Tab takes a title, an SF Symbol name and a content closure, and badge(:) adds a count. Tab arrived in iOS 18; earlier code used tabItem(:) and tag(_:) on child views.

open as a page

In SwiftUI, how do you put a compose button and a sort menu into a screen's navigation bar with toolbar and ToolbarItem placements?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Apply .toolbar to the screen's content inside a NavigationStack and wrap each control in a ToolbarItem or ToolbarItemGroup with a placement such as .topBarTrailing, .topBarLeading, .principal or .bottomBar; SwiftUI then lays the items out in the bars.

open as a page

In SwiftUI, how do you build a three-column NavigationSplitView for a mail app where each column's selection drives the next?

level: middleimportance: must knowfreq 55%
basics
~20 s

Use NavigationSplitView's sidebar, content and detail closures; bind the mailbox List and the message List to optional @State selections, and let each later column read the earlier selection, showing a placeholder while it is nil.

open as a page

In SwiftUI, how do you make a view fade or slide in and out when it is shown or hidden with transition(_:)?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Show 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.

open as a page

In SwiftUI, why does transition(_:) play only on insertion or removal, and how do you make a toast slide in but fade out?

level: middleimportance: must knowfreq 62%
basics
~20 s

A 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).

open as a page

In SwiftUI, what is the difference between animation(_:value:) and withAnimation, and which views animate with each?

level: middleimportance: must knowfreq 75%
basics
~10 s

animation(_: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.

open as a page

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?

level: seniorimportance: must knowfreq 50%
basics
~20 s

Shape 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:).

open as a page

In SwiftUI, how do you make a loading indicator cycle through several looks with phaseAnimator, and what does adding a trigger change?

level: juniorimportance: should knowfreq 45%
basics
~20 s

Apply 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.

open as a page

In SwiftUI, how do you bind a Toggle and a Picker over an enum to a settings screen's state?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Bind 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.

open as a page

In SwiftUI, how do you respond to taps with onTapGesture, and when should a Button replace the tap gesture?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Attach 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Bind 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.

open as a page

In SwiftUI, how does putting controls inside a Form with Sections change how they look on iOS, and how do you override that?

level: middleimportance: must knowfreq 62%
basics
~20 s

Form 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.

open as a page

In SwiftUI, how do you keep a sign-up Form's Create button disabled until the form is valid, and show inline validation messages?

level: middleimportance: must knowfreq 68%
basics
~20 s

Compute 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.

open as a page

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?

level: juniorimportance: must knowfreq 78%
basics
~20 s

SwiftUI 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").

open as a page

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?

level: juniorimportance: must knowfreq 76%
basics
~20 s

A 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.

open as a page

In SwiftUI, how does accessibilityElement(children:) with .combine, .contain or .ignore change what VoiceOver reads for a music track row?

level: middleimportance: must knowfreq 62%
basics
~10 s

accessibilityElement(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.

open as a page

In SwiftUI, how do @ScaledMetric and the dynamicTypeSize environment value keep a now-playing header usable at the largest accessibility text sizes?

level: middleimportance: must knowfreq 64%
basics
~20 s

Text 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.

open as a page

In SwiftUI, how does Text("\(nights) nights") become a String Catalog key, and how does the catalog supply Arabic's plural forms?

level: middleimportance: must knowfreq 62%
basics
~20 s

Interpolating 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.

open as a page

In SwiftUI, when do onAppear and onDisappear run, and why can onAppear fire more than once for one screen?

level: juniorimportance: must knowfreq 65%
basics
~20 s

onAppear 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.

open as a page

In SwiftUI, what does an @main App type declare, and how does a WindowGroup turn its content into windows?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A 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.

open as a page

How do you keep a SwiftUI view's previews fast and offline when the screen normally loads its feed from a network client?

level: middleimportance: must knowfreq 50%
basics
~20 s

A 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.

open as a page

In SwiftUI, why is the task modifier usually preferred over onAppear with a Task inside for loading a screen's data?

level: middleimportance: must knowfreq 80%
basics
~20 s

The 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.

open as a page

In SwiftUI, how does the scenePhase environment value differ when read in a view versus in the App, and where do you save edits?

level: middleimportance: must knowfreq 65%
basics
~20 s

Read 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.

open as a page

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?

level: juniorimportance: must knowfreq 65%
basics
~20 s

SwiftUI 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A 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.

open as a page

In SwiftUI, how do you unit test an @Observable login view model against a fake auth service, and what should that test assert?

level: middleimportance: must knowfreq 72%
basics
~20 s

Put 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.

open as a page

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?

level: seniorimportance: must knowfreq 60%
basics
~20 s

Any @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.

open as a page

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?

level: juniorimportance: should knowfreq 50%
basics
~20 s

accessibilityIdentifier(_:) 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.

open as a page