Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 46 ยท Practice and Interview

iOS and SwiftUI Interview Questions

Prepare for an iOS interview: state vs binding, ARC and retain cycles, view identity, concurrency, architecture and UIKit lifecycle, with clear model answers.

An iOS interview is rarely a quiz about syntax. Interviewers want to hear whether you understand why the platform works the way it does: why SwiftUI views are structs, why a closure can leak memory, why a screen redraws, why updating the UI from a background thread is a bug. This lesson collects the questions that come up again and again and gives answers you can say out loud in under a minute, each followed by the detail that earns a "good" instead of an "okay".

Use it actively. Cover the answer, say yours aloud, then compare. Where an idea can be shown in code, a runnable stand-in is provided (SwiftUI itself cannot run on this site, but ARC, value semantics and actors are plain Swift).

What interviewers listen for

Mental models Why it works, not just how.
Trade-offs Every choice costs something.
Failure modes What breaks and how you notice.
Clear speech Short sentences and examples.
1 / 2

SwiftUI fundamentals

1. What does "declarative UI" mean? You describe what the screen looks like for a given state, not the steps to change it. The view is a function of state: UI = f(state). When state changes, SwiftUI calls body again, compares the new description with the old one and updates only what differs. The opposite is imperative UIKit, where you create a label and later mutate its text. See the SwiftUI mental model.

2. Why are SwiftUI views structs? A view is a cheap, immutable description, not a long-lived object on screen. Structs are lightweight, have no identity of their own and are copied freely, so SwiftUI can create and throw away thousands of them per second. The actual rendering objects are managed by the framework. Persistent data lives in property wrappers such as @State, which store their value outside the struct.

3. What is some View? An opaque return type: "this function returns one specific type that conforms to View, and the compiler knows which". It keeps the real, deeply nested type (ModifiedContent<VStack<TupleView<...>>>) out of your signatures while preserving full type information, which is why it is faster than AnyView.

4. Why does modifier order matter? Each modifier returns a new view that wraps the previous one. .padding().background(.red) paints the padded area, .background(.red).padding() paints only the original content. Think of onion layers from the inside out. See view modifiers.

5. How does SwiftUI layout work? Three steps: the parent proposes a size to the child, the child chooses its own size, the parent places the child. A child never gets forced to a size it did not choose, which is why frame is really "a new container with that size around your view". See how SwiftUI layout works.

State and data flow

6. State versus Binding? @State owns a value: SwiftUI stores it for the lifetime of the view's identity and re-renders when it changes. @Binding is a reference to someone else's state: it has no storage, only a getter and setter. A parent passes $name and the child edits it. Rule: exactly one owner, any number of bindings.

7. When is @State private, and why? Always mark it private. State belongs to the view that declares it; if a parent could set it through init, you would have two sources of truth. If a child needs to change a parent's value, pass a binding.

8. @Observable versus ObservableObject? ObservableObject publishes any change through objectWillChange, and every view that observes the object re-evaluates body. @Observable (the Observation framework) tracks which properties each view's body actually reads and invalidates only those views. It also removes @Published and @StateObject/@ObservedObject in favor of @State and plain properties. See @Observable and Observation.

9. @State versus @Environment versus @AppStorage? @State: local, transient, owned by one view. @Environment: values or objects injected from an ancestor, read by any descendant without passing through every init. @AppStorage: a binding backed by UserDefaults, persisted across launches. A decision guide is in choosing the right property wrapper.

10. What is view identity and why do I care? Identity is how SwiftUI decides that "this view after the update is the same one as before". There are two kinds: structural identity (its position in the view tree, for example the true branch of an if) and explicit identity (id(_:) or the id in ForEach). State, animations and onAppear attach to identity. Change the identity and you get new state; keep it stable and you get smooth animations. Using \.self or array indexes as ids on changing data is a classic bug. See view identity and lifecycle.

11. Why does my view re-render too much? Likely causes: reading a large observed object in a parent (so every child redraws), expensive work in body, unstable ids, or AnyView. Fixes: split the view so each part reads only what it needs, move work out of body, use @Observable for fine-grained tracking, make ids stable. Measure with the SwiftUI instrument first (performance and Instruments).

Memory management

12. How does ARC work? Automatic Reference Counting keeps a count of strong references to each class instance. When the count reaches zero the instance is freed (its deinit runs) immediately and deterministically. There is no tracing garbage collector. ARC applies to classes, closures and actors, not to structs and enums, which are values.

13. What is a retain cycle? Two objects (or an object and a closure it stores) hold strong references to each other, so neither count reaches zero and neither is ever freed. The classic form is a closure property that captures self. The fix is a [weak self] (or [unowned self]) capture list, or making a delegate property weak.

Swift A retain cycle you can see (deinit tells the story)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

14. weak versus unowned? Both avoid a strong reference. weak is optional and becomes nil when the object is freed, so it is always safe. unowned is non-optional and assumes the object outlives the reference; accessing it after deallocation crashes. Use weak unless you can prove the lifetime relationship, such as a child that cannot exist without its parent.

15. Do SwiftUI views need [weak self]? Usually not, because views are structs. There is no self object to cycle with. The danger is in the classes around them: view models, services and Combine or notification observers that store closures.

16. Value types versus reference types? Structs and enums are copied on assignment; each copy is independent. Classes are shared by reference: two variables can point to the same instance and mutate each other's view of the world. Swift's collections use copy-on-write, so copies are cheap until one is modified. Prefer structs for models and use classes when you need identity or shared mutable state.

Swift Copying a struct versus sharing a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Concurrency

17. Why must UI updates happen on the main thread? UIKit and SwiftUI are not thread-safe: view state is read and written by the render loop on the main thread. Mutating it from another thread can produce races, inconsistent frames or crashes. In modern code you mark UI-facing types @MainActor, and the compiler enforces it. See concurrency in iOS.

18. async/await versus completion handlers? async functions read like straight-line code, propagate errors with throws, support cancellation and cannot "forget" to call a completion. Completion handlers nest, make error handling and cancellation manual, and can be called twice or never. You can wrap old callback APIs with withCheckedContinuation.

19. What is an actor? A reference type that protects its mutable state by processing one call at a time. Calls from outside are awaited, so data races on that state are impossible by construction. @MainActor is a global actor tied to the main thread. Actors do not prevent logical races: between two awaits, state may have changed.

Swift An actor serializes access to shared state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

20. What does .task do compared with onAppear? .task runs an async closure when the view appears and cancels it automatically when the view disappears (or its id changes). With onAppear you must start and cancel a Task yourself. For loading data on appear, .task is the right default.

21. What is Sendable? A marker that says "values of this type are safe to pass across concurrency domains". Value types made of Sendable parts qualify automatically; classes must be immutable or internally synchronized. Swift 6 language mode turns violations into errors.

Architecture and testing

22. Explain MVVM in SwiftUI. Is it required? The view model holds screen state and logic in display-ready form; the view renders it and forwards actions. It helps when logic is non-trivial or needs tests. It is not required: SwiftUI already binds state to views, so for small screens @State plus a couple of computed properties is enough, and adding a view model per screen can be pure ceremony. Judge by testability and size (MVVM and app architecture).

23. How do you make code testable? Depend on protocols at the edges (network, storage, clock, random), inject them through initializers or the environment, and keep logic out of body in plain types that do not import SwiftUI. Tests then pass fakes and assert on outputs (testing view models and UI).

24. SwiftData versus Core Data? SwiftData is the modern, Swift-native layer (macros like @Model, @Query, built on Core Data's storage). Prefer it for new apps on recent OS versions; Core Data still matters for older deployment targets, existing stores and some advanced features (SwiftData basics, Core Data and CloudKit).

25. Where should secrets be stored? Tokens and passwords belong in the Keychain, never in UserDefaults, plist files or the source code. An API key shipped inside the app can be extracted by anyone, so truly secret keys must live on a server (Keychain and app security).

UIKit and the app lifecycle

26. Describe the UIViewController lifecycle. init then loadView/viewDidLoad (view loaded once, set up here), viewWillAppear (about to show, every time), viewDidAppear (visible), viewWillDisappear, viewDidDisappear, and deinit when released. Layout passes happen in viewWillLayoutSubviews and viewDidLayoutSubviews. In SwiftUI the equivalents are onAppear, onDisappear and .task.

27. How do SwiftUI and UIKit work together? UIViewRepresentable and UIViewControllerRepresentable embed UIKit in SwiftUI (with a Coordinator for delegate callbacks). UIHostingController embeds SwiftUI in UIKit. Real apps mix both for years (UIKit interoperability).

28. What are the app states? Not running, inactive, active, background and suspended. In SwiftUI you observe scenePhase (active, inactive, background) to save data or pause work (the App protocol and scenes).

Behavioral and practical questions

29. "Tell me about a bug you fixed." Pick one with a clear loop: symptom, how you reproduced it, the tool that found the cause (breakpoint, view debugger, Instruments, crash log), the fix, and what you changed so it cannot return (a test, a lint rule, a type that forbids the bad state).

30. "How would you structure a new app?" Start small: models and logic in plain Swift, one observable store per feature area, environment injection for services, navigation as data, tests for the logic. Add modules and layers when pain appears, not before.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A view model stores a closure that calls self.reload(), and the view model owns that closure. What is the likely problem and fix?

    The object holds the closure and the closure holds the object, so neither is freed. [weak self] breaks the cycle.
  2. 2. Which statement about @State and @Binding is correct?

    There must be one owner of a value. A binding is only a getter and setter pointing at it.
  3. 3. What is the advantage of @Observable over ObservableObject?

    Observation tracks property reads inside body, so unrelated changes no longer re-evaluate every observing view.
  4. 4. Why does an actor protect against data races?

    Calls into an actor are serialized, so two tasks can never mutate its state at the same moment.
  5. 5. When is unowned a reasonable choice over weak?

    unowned crashes if used after the object is gone, so it needs a provable lifetime relationship.

Summary

  • Explain SwiftUI as UI = f(state): views are cheap structs; state lives in property wrappers with one owner.
  • Know identity: it decides state lifetime, animations and diffing.
  • ARC frees instances when the strong count hits zero; closures stored on objects are the usual retain cycle, fixed with [weak self].
  • UI work belongs on the main actor; use async/await, .task and actors instead of callbacks and locks.
  • Be ready to discuss trade-offs of MVVM, dependency injection and SwiftData versus Core Data.
  • Practice answers out loud, with a tiny example for each.

Next: iOS and SwiftUI Cheat Sheet