AceMobileInterview

Interview guides / ios

Top 50 Swift Interview Questions (With Example Answers)

Fifty high-frequency Swift and iOS interview questions with concise example answers. Free prep for mobile engineers.

If you are interviewing for an iOS role, Swift fundamentals still open most loops. Interviewers want clear mental models for memory, concurrency, optionals, protocols, and UI state, not trivia dumps.

This list focuses on questions that show up constantly in phone screens and onsite rounds. Use each answer as a skeleton, then add a short production story from your own apps.

When you want timed projects, debugging zips, and full system design drills, continue in AceMobileInterview.

  1. 1.Walk through the UIViewController lifecycle and where you would load data, configure UI, and clean up observers.

    loadView → viewDidLoad (one-time setup) → viewWillAppear → viewIsAppearing → viewDidAppear → viewWillDisappear → viewDidDisappear → deinit. Load remote data after first appear or via a dedicated loader; remove NotificationCenter/KVO observers in deinit or viewDidDisappear depending on scope; cancel in-flight tasks when the screen disappears if results are no longer needed.

  2. 2.When do you pick delegate patterns vs completion closures?

    Delegates suit multi-method ongoing relationships (tableView). Closures suit one-shot results. Avoid retain cycles: weak delegates, weak self captures.

  3. 3.What does iOS sandboxing restrict?

    Apps can’t freely read other apps’ data; limited filesystem, entitlements for capabilities (iCloud, push, associated domains). Privacy manifests/permissions gate sensitive APIs.

  4. 4.What are common NotificationCenter bugs and how do you avoid them?

    Forgetting to remove observers (pre-block API), posting on wrong threads, overusing global events. Prefer Combine publishers, delegates, or scoped observers; always consider lifecycle.

  5. 5.What is KVO and what replaced it in many Swift codebases?

    KVO observes Obj-C property changes. Prefer Combine, Observation/@Observable, delegates, or closures for Swift-first code. KVO still appears with AVFoundation and legacy APIs.

  6. 6.How does cell reuse work and what bugs does it cause?

    Cells dequeue from a reuse pool; configure every visible field in cellForRow or configure methods. Stale images/text appear if you don’t reset state; cancel image loads on prepareForReuse.

  7. 7.When would you use Result<Success, Failure> instead of throws?

    Result is great for async callbacks and stored outcomes. throws fits synchronous APIs and async/await. You can bridge with get() / mapError depending on call site style.

  8. 8.How do optionals work, and when would you use ?, !, if let, guard let, and ??

    Optionals wrap absence of a value. Prefer if let/guard let for safe unwraps; ?? for defaults; avoid force unwrap (!) except when truly impossible to be nil. Optional chaining (?.) short-circuits safely.

  9. 9.Explain value types vs reference types and how copying behaves.

    Value types (struct/enum) copy on assignment; reference types share one instance. Mutations to a copy don’t affect the original. Copy-on-write optimizes large values like Array/Dictionary/String.

  10. 10.When do you choose a struct over a class in Swift?

    Prefer structs for value semantics, thread-safer copies, and simple data. Use classes for identity, inheritance, Objective-C interop, or shared mutable references. Many modern models are structs; UIKit types remain classes.

  11. 11.What is ATS and when can you exception it?

    ATS enforces HTTPS/TLS best practices. Exceptions via Info.plist for legacy servers are discouraged and scrutinized. Prefer fixing server TLS over broad NSAllowsArbitraryLoads.

  12. 12.Explain Automatic Reference Counting (ARC). When do retain cycles happen, and how do you break them with weak and unowned references?

    ARC tracks strong references and frees objects at zero. Cycles usually appear in closures capturing self, or parent↔child object graphs. Use weak for optional back-references (delegates, closures that may outlive the object) and unowned when the reference is non-optional and guaranteed to outlive the capture. Always capture lists in escaping closures: `[weak self]`.

  13. 13.Compare GCD (DispatchQueue) with async/await and actors. When would you still reach for GCD?

    GCD is queue-based concurrency; Swift Concurrency models tasks, structured cancellation, and actor isolation for data races. Prefer async/await for new code, MainActor for UI, and actors for shared mutable state. GCD still helps for fine-grained QoS tuning, integrating C APIs, or migrating legacy code incrementally.

  14. 14.How do generics and associated types differ in Swift?

    Generics parameterize types/functions (Array<Element>). Associated types parameterize protocols (IteratorProtocol.Element). Use type erasure (any/some) when you need existential flexibility.

  15. 15.Compare throws, Result, and async throws for networking layers.

    Prefer async throws for modern networking. Result suits completion handlers. Map domain errors distinctly from transport errors; avoid catching and swallowing without logging/telemetry.

  16. 16.What problem do Coordinators solve?

    They own navigation flow so view controllers don’t push/present each other directly—improving reuse and testability of routing. Useful in UIKit; SwiftUI often uses NavigationPath/Router instead.

  17. 17.Explain [weak self] vs [unowned self] in escaping closures.

    weak self makes self optional and avoids cycles when lifetime is uncertain. unowned assumes self outlives the closure—crashes if wrong. Prefer weak for UI/async work unless lifetime is guaranteed.

  18. 18.Compare MVC, MVVM, and VIPER for iOS apps.

    MVC is UIKit default but Massive VC risk. MVVM moves logic to ViewModels, testable with bindings. VIPER splits responsibilities heavily—good for large teams, often overkill for small features.

  19. 19.What’s the difference between escaping and non-escaping closures?

    Non-escaping run before the function returns (default). Escaping may outlive the call (async callbacks, stored handlers) and need @escaping; they require care with capture lists to avoid retain cycles.

  20. 20.What can and can’t protocol extensions do? How do they relate to default implementations?

    Extensions can add methods/computed properties with defaults, but can’t add stored properties. Default implementations let conforming types opt into behavior without boilerplate; dispatch is static unless requirements are protocol witnesses.

  21. 21.When is OperationQueue preferable to raw GCD?

    When you need dependencies, cancellation of work units, maxConcurrentOperationCount, or KVO progress. GCD is lighter for simple fire-and-forget; Operations model richer workflows.

  22. 22.When would you still use Combine instead of async/await?

    Combine shines for multi-pipeline reactive graphs, UI bindings, and debouncing many publishers. async/await is clearer for linear request/response. Bridging via publishers/values is common during migration.

  23. 23.Name common UIBackgroundModes and when you’d enable them.

    audio, location, voip, processing, fetch, remote-notification, bluetooth-central, etc. Only enable what you need—App Review checks misuse; prefer BGTaskScheduler for deferred work.

  24. 24.What is AsyncSequence and where would you use it on iOS?

    AsyncSequence yields values over time (notifications, bytes, SSE). for await loops consume them. Useful for streaming APIs, NotificationCenter bridging, and URLSession bytes.

  25. 25.How did UIScene change app lifecycle vs AppDelegate-only apps?

    Scenes support multi-window; scene delegate handles UI lifecycle per window scene. AppDelegate still handles process-level events. State restoration and dual entry points matter.

  26. 26.How do you wrap UIKit views in SwiftUI safely?

    Implement makeUIView/updateUIView; use Coordinator for delegates. Avoid recreating views unnecessarily; sync state carefully to prevent feedback loops.

  27. 27.Compare NavigationStack value-based navigation vs older NavigationView.

    NavigationStack uses typed paths/links for deep links and programmatic pops. NavigationView was less flexible and had split-view quirks. Prefer NavigationStack on modern OS versions.

  28. 28.Explain device token flow and rich notifications briefly.

    App registers, receives device token, sends to backend; backend pushes via APNs. Notification Service Extension for mutable content; Content Extension for custom UI. Handle authorization status carefully.

  29. 29.What Auto Layout practices hurt scroll performance?

    Excessive constraint changes per frame, ambiguous layouts, deep hierarchies, offscreen measurement thrash. Prefer simpler hierarchies, intrinsic sizes, and self-sizing carefully profiled with Instruments.

  30. 30.Why use compositional layout over flow layout?

    Compositional layout composes sections/groups/items declaratively, supports orthogonal scrolling and complex grids without subclassing flow layout. Better for modern multi-section UIs.

  31. 31.What belongs in Keychain vs UserDefaults?

    Secrets/tokens/credentials → Keychain. Preferences/flags → UserDefaults. Never store auth tokens in UserDefaults. Use accessibility levels and biometric access control appropriately.

  32. 32.How does SwiftData relate to Core Data?

    SwiftData is a Swift-native persistence layer built on Core Data concepts with @Model macros. Good for new apps; understand migration, relationships, and ModelContext threading still matter.

  33. 33.What Codable issues show up in interviews/production?

    Date strategies, unknown keys, snake_case conversion, optional vs required fields, polymorphic payloads. Custom init(from:) / encode(to:) and coding keys fix most gaps.

  34. 34.How do you control HTTP caching on iOS?

    URLCache with memory/disk capacity; Cache-Control/ETag from server; request cachePolicy (.useProtocolCachePolicy, .reloadIgnoringLocalCacheData). Don’t cache sensitive authenticated responses carelessly.

  35. 35.Compare default, ephemeral, and background URLSessionConfiguration.

    default uses disk cookies/cache; ephemeral is in-memory/private; background enables out-of-process downloads/uploads that continue when app suspends. Background needs delegate-based APIs.

  36. 36.How do you structure unit, UI, and snapshot tests on iOS?

    Unit test ViewModels/services with DI; snapshot for UI regressions; UI tests sparingly for critical flows. Prefer deterministic fakes over flaky network. XCTest/Swift Testing + dependency injection are key.

  37. 37.How should an app respond to memory warnings?

    Drop caches, purge image pipelines, release rebuildable resources, and avoid big allocations. In SwiftUI/UIKit, observe warnings and verify with Memory Graph Debugger.

  38. 38.What is protocol-oriented programming and when is it better than class inheritance?

    Define behavior via protocols + extensions, compose capabilities, and prefer generics/PAT constraints. Better than deep class hierarchies for testability and reuse without fragile base classes.

  39. 39.Which Instruments templates do you reach for first?

    Time Profiler for CPU, Allocations/Leaks for memory, os_signpost/Points of Interest for intervals, Core Animation for UI hitching, Network for requests. Always profile on device.

  40. 40.How do Swift enums with associated values improve API design?

    They model mutually exclusive states with payloads (e.g. Result success/failure). Pattern matching via switch is exhaustive, reducing invalid states vs flag+optional field combos.

  41. 41.Difference between custom URL schemes and Universal Links?

    Schemes are simple but spoofable/not uniquely owned. Universal Links use HTTPS + apple-app-site-association for verified domain association and better security/UX.

  42. 42.How does cooperative cancellation work with Task.checkCancellation()?

    Canceling a Task sets isCancelled; work must check periodically or use cancellable APIs. throw CancellationError via checkCancellation(). Parents cancel children in structured concurrency.

  43. 43.Why annotate UI updates with @MainActor? What happens if you don’t?

    UIKit/SwiftUI require main-thread UI access. @MainActor enforces that at compile time with isolation. Skipping it risks crashes/races; use Task { @MainActor in } or MainActor.run for hops.

  44. 44.When do you use @State, @Binding, @StateObject, @ObservedObject, and @EnvironmentObject?

    @State owns simple local view state. @Binding reads/writes parent-owned state. @StateObject creates and owns an ObservableObject for the view’s lifetime. @ObservedObject observes an object owned elsewhere (don’t create it inline). @EnvironmentObject shares dependencies down the tree. Prefer @Observable (Observation framework) in modern apps where available.

  45. 45.Explain some vs any for protocols in Swift.

    some is an opaque type—fixed concrete type known to compiler, better performance. any is an existential—dynamic type, more flexible, potential heap allocation/boxing. Prefer some at API boundaries when possible.

  46. 46.How do background app refresh and processing tasks work?

    Register identifiers, submit BGAppRefreshTaskRequest / BGProcessingTaskRequest, handle expiration handlers, and set task completed. System decides scheduling based on usage/energy.

  47. 47.How do you gate Keychain items with biometrics?

    Access control flags (biometryCurrentSet), LocalAuthentication for prompting, handle lockout/fallback. Don’t confuse app unlock UX with cryptographic access control.

  48. 48.How does the main RunLoop relate to GCD main queue?

    Main RunLoop processes input sources/timers; DispatchQueue.main schedules blocks that eventually run on the main thread. Timers/DisplayLink interact with RunLoop modes; scroll tracking uses tracking mode.

  49. 49.What are PreferenceKeys used for?

    Child-to-parent communication of layout/geometry data (e.g. measuring views). Useful for sticky headers/custom coordination; overuse can cause extra layout passes.

  50. 50.How would you implement SSL pinning and what are the risks?

    Pin public key/certificate in URLSession delegate trust evaluation. Risks: rotation outages if pins aren’t updated. Use backup pins and a safe update strategy.

Keep going with AceMobileInterview

Reading helps. Timed practice locks it in. Jump into the interactive track for algorithms with LeetCode links, studio projects, debugging zips, and mobile system design.

iOS trackAndroid trackMore guides