Swift
201 bites tagged Swift — interview questions with model answers, and 60-second explainers.
Purpose and setup of an Objective-C bridging header
The bridging header imports ObjC headers into Swift; Xcode auto-creates it or you add it manually and set the build setting. mixed-language project setup. confusing it with the generated Swift-to-ObjC header.
Package.swift manifest: library vs executable products
The manifest declares name, targets, dependencies, and products; a library is consumed by other code while an executable produces a runnable binary with an entry point. understanding SPM package structure.
Adding a Swift Package dependency in Xcode
Add via File menu, paste the repo URL, choose a version rule like up-to-next-major, link the product to your target. basic SPM workflow knowledge.
Testing async code and completion handlers in XCTest
Create an expectation, fulfill it inside the completion handler, call wait with a timeout, or use async test methods. knowledge of waiting for asynchronous work in tests.
Unit test a ViewModel with a mocked NetworkService
Inject the protocol, supply a mock returning canned data, assert published state transitions. dependency injection and test isolation. hitting the real network or testing the concrete service instead of the ViewModel.
What is an actor and how does it prevent data races
Actors serialize access to mutable state, reachable only via await; compiler blocks unsafe access. Token-refresh actor coalesces concurrent refreshes. Actor isolation as compiler-enforced safety.
How task cancellation works with async/await
Cancellation is a flag, not a kill; check Task.isCancelled or call checkCancellation, URLSession throws CancellationError automatically. Cooperative cancellation in Swift Concurrency.
Add a default header to every URLSession request
Set httpAdditionalHeaders on a URLSessionConfiguration, build the session from it, mention per-request overrides win. Knowing URLSession is configured, not just used. Subclassing URLRequest or mutating every request by hand.
What is @MainActor and why does it matter?
@MainActor is a global actor guaranteeing code runs on the main thread; annotate UI-updating types or methods so post-network state changes are main-thread safe. thread safety for UI updates.
Run two API calls concurrently with async let
Use async let to start two independent fetches that run concurrently, then await both, so total time approaches the slower call rather than the sum. structured concurrency for parallel work.
Map JSON keys to differently named Codable properties
Declare a nested CodingKeys enum mapping userID to the raw value "user_id", or set the decoder's keyDecodingStrategy to convertFromSnakeCase for blanket conversion. Codable key customization.
Fetch and decode JSON with async/await and URLSession
Call URLSession.shared.data(from:) inside an async throws function, check the HTTPURLResponse status, then JSONDecoder().decode([User].self) and let errors propagate via try. modern networking basics.
What is @autoclosure and when is it useful?
@autoclosure wraps an argument expression in a closure so it evaluates lazily only if used, enabling clean APIs like assert and the ?? operator. understanding deferred, lazy evaluation.
Why can't you subscript a Swift String with an Int?
Characters are extended grapheme clusters of variable byte width, so integer offsets are not O(1) or meaningful; String.Index is an opaque position you advance via the collection. understanding Unicode-correct strings.
How does Swift's switch differ from C's switch?
Switches must be exhaustive, there is no implicit fallthrough between cases, and cases can match ranges, tuples, and bind values. understanding Swift's safer control flow.
Writing React Native iOS Modules in Swift
React Native speaks Objective-C on iOS, so Swift needs an Objective-C wrapper to join. Write logic in Swift, expose it via an Objective-C class, and register with RCT_EXPORT_MODULE. Skip the bridging header and the compiler never sees your Swift code.
How do you persist a custom Swift struct to JSON in Documents?
Tests fluency with Codable and FileManager sandbox APIs. Good answer: conform to Codable, encode with JSONEncoder, resolve Documents directory via FileManager URLs, write Data atomically, and reverse with JSONDecoder.
When is UserDefaults right, what are its limits, and native types?
Tests if you treat UserDefaults as a small preference store, not a database. Good answers name native plist types, cite no encryption and small size limits, and name Core Data or Keychain for heavy or sensitive data. Red flag: storing images or passwords.
How would you architect the app root for onboarding vs authenticated flows?
Tests window root swapping and state-driven architecture. Use a coordinator to own the window, swap rootViewController between nav and tab controllers on auth changes, and crossfade. Red flag: onboarding modal over tabs or keeping both hierarchies alive.
Handle a deep link URL in SceneDelegate and navigate to order detail.
Handles willConnectTo and openURLContexts; parses path with URLComponents; validates ID; pushes detail onto nav stack. iOS scene-based deep links. Forgetting warm launches or routing without checking view hierarchy.
Pass data back from a modally presented view controller delegate versus closure
This tests decoupled UIKit communication and memory safety. A strong answer outlines a weak delegate protocol and a closure with weak self, contrasting coupling and retain cycles. Red flag: singletons or direct parent references.
Explain the Coordinator pattern and the navigation problem it solves in MVC
This tests if you see view controllers bloat from absorbing navigation flow. A good answer names 3 problems (delegate bloat, massive view controllers, embedded routing) and says coordinators own creation and routing.
How does the Coordinator pattern decouple navigation, and what are its components?
This tests iOS separation of concerns. Explain that Coordinators extract navigation logic from view controllers for reuse, and describe AppCoordinator tree with child coordinators. A red flag is treating it as a router or ignoring parent-child retention.
Explain MVVM, its improvements over MVC, and Swift data binding techniques.
Tests architectural separation of concerns and pattern comparison skills. Define ViewModel as state transformer, cite MVC's massive view controller, and list Combine or closures for binding. Red flag: calling MVVM as MVC with no testability.
Get Swift bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.