Swift interview questions and answers for developers
Swift interview questions check whether you understand how Swift manages values and memory: optionals and unwrapping, structs versus classes and copy-on-write, ARC with weak and unowned references, protocols and generics, escaping closures, and modern concurrency with async/await and actors. App roles add SwiftUI state and data flow. Interviewers want the reason behind each rule, for example why a closure needs [weak self], not just the syntax.
By Evin JohnPublished 8 min read
What a Swift interview usually covers
Swift interviews mostly come from iPhone, iPad and Mac app teams, with some server-side Swift. Expect a language screen, a coding round written in Swift (sometimes in a playground, sometimes in a shared editor with no compiler), and a discussion of an app architecture you have worked on. The language questions keep returning to the same three themes: how values are copied, how memory is freed, and how concurrent code stays correct now that the compiler checks data races.
- Language basicsOptionals, structs versus classes, enums, error handling, protocols. Crisp definitions with a one-line example.
- Memory and closuresFind the retain cycle in a view controller, explain weak versus unowned, decide whether a closure escapes.
- Coding in SwiftAlgorithms using Swift collections, or a small model layer with protocols and generics. Idiomatic optional handling counts.
- Concurrency and architectureMove a callback API to async/await, protect shared state with an actor, structure SwiftUI state for a screen.
Optionals and Swift fundamentals
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is an optional, really? | Type system | An enum with two cases, some wrapping a value and none. The compiler forces you to handle the none case before using the value. |
| if let versus guard let? | Control flow | if let binds inside its block. guard let binds for the rest of the scope and must exit on failure, which keeps the happy path unindented. |
| When is force unwrapping acceptable? | Judgment | When a nil would be a programmer error that should crash at once, such as a resource bundled with the app. Elsewhere use optional binding, ?? or optional chaining. |
| What does optional chaining return? | Chaining | An optional of the final result: user?.address?.city is nil if any link is nil. |
| What are enums with associated values for? | Modeling | Cases that carry different data, such as a load state with success items or an error message. Combined with switch, the compiler checks every case is handled. |
| How does Swift handle errors? | Error handling | Functions marked throws, called with try inside do/catch. try? turns an error into nil, try! crashes on error. Result is useful when you store or pass an outcome. |
| What does defer do? | Cleanup | Runs a block when the current scope exits by any path. Several defers run in reverse order. |
| What does lazy var mean? | Initialization | The value is computed on first access and then stored. It must be var, and it is not thread-safe by itself. |
Value types, reference types and copy-on-write
struct PointValue { var x = 0 }
final class PointRef { var x = 0 }
var a = PointValue()
var b = a
b.x = 5
print(a.x, b.x) // 0 5
let c = PointRef()
let d = c
d.x = 5
print(c.x, d.x) // 5 5- Struct or class: how do you choose? Default to a struct for data: copies are independent, which avoids shared mutable state. Choose a class when you need identity, inheritance, deinit, or shared state that several owners must see change.
- Why can `d.x = 5` compile when d is a let? let fixes the reference, not the object it points to. With a struct, let freezes the whole value.
- What does mutating mean? A struct method that changes its own properties must be marked mutating, and it can only be called on a var.
- Does copying an array copy all its elements? Not at once. Array, Dictionary and String use copy-on-write: copies share storage until one is modified. Your own structs do not get this automatically; you can implement it with isKnownUniquelyReferenced.
- Where do structs live: stack or heap? It depends. A struct inside a class, an existential box or an escaping closure capture lives on the heap. Value semantics is about copying behavior, not location.
ARC, retain cycles, weak and unowned
Swift frees class instances with automatic reference counting. Every strong reference adds to the count, and the instance is destroyed when the count reaches zero. Nothing collects cycles, so two objects that hold each other strongly, or an object that stores a closure capturing itself, will never be freed.
final class Downloader {
var onFinish: (() -> Void)?
let name = "report"
func start() {
onFinish = { [weak self] in
guard let self else { return }
print("finished \(self.name)")
}
}
deinit { print("Downloader freed") }
}| Question | What it tests | What a strong answer shows |
|---|---|---|
| weak versus unowned? | Reference kinds | weak is optional and becomes nil when the object goes away. unowned is non-optional and assumes the object outlives the reference; accessing it after deallocation traps. Use unowned only when that lifetime is certain. |
| Does every closure need [weak self]? | Judgment | No. Only closures that are stored and outlive the call, directly or indirectly, by the object they capture. A non-escaping closure or a short-lived animation block does not create a lasting cycle. |
| Where do delegate cycles come from? | Delegation | A view holds its delegate strongly while the delegate owns the view. Declaring the delegate property weak (on a class-bound protocol) breaks it. |
| How do you find a leak in an app? | Tooling | Check that deinit runs when a screen closes, use the memory graph debugger to see who holds the object, and profile with the Leaks and Allocations instruments. |
| What does a capture list capture? | Closures | Values in the list are captured when the closure is created, by the strength you specify. Other variables are captured by reference and read when the closure runs. |
Protocols, generics and dispatch
protocol Greeter { func hello() -> String }
extension Greeter {
func hello() -> String { "hello" }
func bye() -> String { "bye" } // not a requirement
}
struct Formal: Greeter {
func hello() -> String { "good day" }
func bye() -> String { "farewell" }
}
let g: any Greeter = Formal()
print(g.hello()) // good day
print(g.bye()) // bye: chosen by the static type- What is protocol-oriented design? Describing capabilities with small protocols, giving shared behavior through protocol extensions, and composing them on structs and enums instead of building class hierarchies.
- Why does g.bye() print "bye"? bye is not declared in the protocol, so the call is resolved statically from the variable's type, any Greeter, which only knows the extension version. Declare it as a requirement to get dynamic dispatch.
- some versus any?
some Shapeis an opaque type: one concrete type chosen by the implementation and known to the compiler.any Shapeis an existential box that can hold different types at runtime, at some cost in performance and type information. - What is an associated type? A placeholder type inside a protocol, like Element in a collection, filled in by each conforming type.
- How do generic constraints help? A where clause such as
where T: Comparablelets the body use the protocol's methods while staying fully type-safe and specialized. - When does Swift synthesize Equatable, Hashable or Codable? For structs and enums whose stored properties or associated values already conform, when you declare the conformance.
Closures and escaping
final class EventBus {
private var handlers: [() -> Void] = []
func subscribe(_ handler: @escaping () -> Void) {
handlers.append(handler) // stored, so it escapes
}
func perform(_ work: () -> Void) {
work() // runs now, non-escaping by default
}
}- What makes a closure escaping? It can be called after the function returns: stored in a property, put in an array, or passed to async work. Function parameters are non-escaping unless marked.
- Why does the compiler require explicit self in some closures? In escaping closures that capture a class instance, writing self makes the strong capture visible, which is exactly where cycles start.
- What is a trailing closure? Syntax that lets the last closure argument sit outside the parentheses, which SwiftUI relies on heavily.
- What is an autoclosure? A parameter that wraps an expression in a closure automatically, so it is evaluated only if needed, as in assert or the ?? operator.
async/await, actors and Sendable
actor Counter {
private var value = 0
func increment() -> Int {
value += 1
return value
}
}
let counter = Counter()
let n = await counter.increment() // 1| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does await mean for the thread? | Suspension | The function may suspend there and free its thread; it can resume later on a different thread unless it is isolated to an actor such as MainActor. |
| async let versus a task group? | Structured concurrency | async let runs a fixed number of child tasks in parallel. A task group handles a dynamic number, such as downloading every image in a list. |
| Task versus Task.detached? | Unstructured tasks | Task inherits the current actor and priority; detached inherits neither. Prefer structured children, then Task, and use detached rarely. |
| How does cancellation work? | Cooperation | Canceling a task sets a flag on it and its children. Code checks Task.isCancelled or calls Task.checkCancellation, and many system APIs throw when canceled. |
| What is actor reentrancy? | Actor semantics | While an actor method awaits, other calls can run on the actor. State read before the await may have changed after it, so recheck it. |
| What is Sendable? | Data-race safety | A marker that a value is safe to share across concurrency domains: value types of Sendable parts, actors, and carefully synchronized classes. The Swift 6 language mode checks it at compile time. |
| What does @MainActor do? | UI isolation | It isolates a function or type to the main actor, so UI updates happen on the main thread and the compiler enforces it. |
SwiftUI basics for app roles
- Why are SwiftUI views structs? They are cheap descriptions of the UI. SwiftUI recomputes body when state changes and diffs the result; the view value itself is not the thing on screen.
- @State versus @Binding? @State is storage the view owns. @Binding is a reference to state owned elsewhere, passed with the dollar-sign prefix so a child can read and write it.
- @StateObject versus @ObservedObject? StateObject creates and owns an observable object once for the view's lifetime. ObservedObject only watches one passed in; creating it there recreates it on every redraw.
- What does the @Observable macro change? Available from iOS 17, it tracks which properties a view actually reads, so views update only when those change, and plain @State can hold the model.
- Why does view identity matter? SwiftUI keeps state per identity. Changing an id or switching between branches of an if creates a new view and resets its state and animations.
Fictional example
- Testers noticed the app's memory climbing each time they opened and closed a chat screen. I added a print in the view controller's deinit and it never fired. The memory graph debugger showed a timer that refreshed typing indicators: the run loop held the timer, and the timer's closure held the view controller strongly. I captured self weakly in the closure and invalidated the timer when the screen disappeared. deinit started firing, and memory stayed flat across twenty open and close cycles. Since then I check deinit for every new screen as part of review.
Two-week Swift preparation plan
- Days 1 to 3: optionals, enums with associated values, error handling, struct versus class. Write each example in a playground and predict the output.
- Days 4 to 6: ARC. Build a retain cycle three ways (delegate, closure, timer), confirm with deinit, then break each.
- Days 7 and 8: protocols, extensions, some versus any, and the static dispatch puzzle above.
- Days 9 to 11: async/await, async let, task groups, actors and reentrancy. Convert one completion-handler API to async.
- Days 12 to 14: SwiftUI state and identity, then a timed mock: a list screen that loads data with cancellation and shows loading, empty and error states.
Kotlin is Swift's closest cousin on the Android side, with similar null safety and a different concurrency model: see Kotlin interview questions. For ownership taken further, with lifetimes checked at compile time, compare Rust interview questions. The full engineering loop is in software engineer interview questions.
Natively, an AI interview assistant for Mac and Windows, gives you a transcript of each mock Swift interview, which helps when you want to check whether your ARC answer named the actual cycle. In practice it can read a Swift problem from a screenshot, suggest a hint or an approach, and with Pro or the free trial use the résumé and job description you add. Your transcripts and notes are kept so you can go back over them.
Questions people ask
What Swift questions are asked in interviews?
Optionals and unwrapping, structs versus classes, ARC with weak and unowned references, protocols and extensions, generics, escaping closures, error handling, and concurrency with async/await and actors. App roles add SwiftUI state.
How do I explain retain cycles in a Swift interview?
Say that ARC frees an object when its strong count reaches zero and nothing collects cycles. Then name a real cycle, such as a stored closure capturing self, and show the fix: a [weak self] capture list or a weak delegate.
What Swift concurrency questions should I expect?
What await does to the thread, async let versus task groups, cancellation, actors and reentrancy, MainActor for UI work, and what Sendable means for data-race checking in the Swift 6 language mode.
Are Swift interviews only for iOS jobs?
Mostly they come from iPhone, iPad and Mac app teams, but server-side Swift teams ask the same language questions with less SwiftUI and more concurrency.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
