Top 30 Swift Interview Questions and Answers [2026]
October 9, 2026
15 min read
TL;DR: Swift interviews in 2026 test value semantics, protocols and generics, and above all data-race safety: actors, Sendable and where an async function runs. Candidates should know that Swift 6.4 is the current release (September 15, 2026, shipped in Xcode 27) and that Swift 6.2 changed the default for nonisolated async functions behind an opt-in feature flag.
Swift 6.4 shipped on September 15, 2026 with a way to shield cleanup code from task cancellation, await inside defer, and a 1.0 release of the Subprocess package.
Most of the language questions interviewers ask have not moved: optionals, copy-on-write, ARC and protocol dispatch. The concurrency questions have, because the Swift 6 language mode turns data-race warnings into compile errors.
Key takeaways
1The Swift 6 compiler supports four language modes (6, 5, 4.2 and 4), and existing projects stay in their old mode until someone changes the setting.
2Swift 6.3 (March 2026) shipped the first official Swift SDK for Android.
3Typed throws arrived in Swift 6.0, so throws(ParseError) is valid Swift today.
4Since Swift 6.4, Swift Package Manager builds with Swift Build by default on Linux, macOS and Windows.
Language Basics
1. What is an optional, and what are the ways to unwrap one?
An optional is an enum with two cases, .none and .some(Wrapped). String? is shorthand for Optional<String>, and the compiler will not let you use it as a String until you handle the nil case.
if let name and guard let name bind the value when it exists. The shorthand without = name works since Swift 5.7.
name?.count chains: the whole expression becomes optional and stops at the first nil.
name ?? "Guest" supplies a default.
name! force-unwraps and traps on nil. It belongs only where a nil would be a programmer error.
A good follow-up: guard let keeps the unwrapped value in scope for the rest of the function, which is why it is the usual choice for early exits.
2. What is the difference between a struct, an enum, a class and an actor?
Structs and enums are value types: assigning one copies it, so two variables never share state. Classes and actors are reference types: assignment copies a reference to one shared instance.
Only classes support inheritance. Actors add serialized access: only one task touches an actor's mutable state at a time, and outside callers must await.
The Swift book's chapter on structures and classes advises preferring structures because they are easier to reason about, and using classes when you need identity, inheritance or Objective-C interop.
3. How does copy-on-write work for arrays and strings?
Array, Dictionary, Set and String are structs that hold a reference to heap storage. Copying the struct copies only that reference. The storage is duplicated the first time one copy is mutated while the buffer is shared.
var a = [1, 2, 3]
var b = a // no copy yet: both point at one buffer
b.append(4) // b gets its own buffer here
Your own structs do not get this for free. To build it, wrap a class in a struct and call isKnownUniquelyReferenced(&storage) before mutating, copying the storage only when it returns false.
4. How does ARC work, and how do you break a retain cycle?
Automatic Reference Counting keeps a count of strong references to each class instance and frees the instance when the count reaches zero.
It is deterministic: deinit runs as soon as the last strong reference goes away, with no garbage collector pause.
Two objects that hold strong references to each other never reach zero. Break the cycle by making one side weak or unowned. A weak reference is optional and becomes nil when the object is freed.
An unowned one is non-optional and traps if used after the object is gone. Use unowned only when the referenced object is guaranteed to outlive the reference, such as a child pointing back at the parent that owns it.
5. What is a capture list, and when do you need [weak self]?
A capture list, the brackets before a closure's parameters, controls how the closure captures values. [weak self] stops an escaping closure from keeping self alive.
loader.onFinish = { [weak self] result in
guard let self else { return }
self.render(result)
}
You need it when self stores the closure, directly or through an object it owns, which forms a cycle. You do not need it for non-escaping closures such as the one passed to map, or for a short-lived Task whose lifetime you control.
A strong answer also mentions that [x] captures the current value of x, while a plain reference captures the variable itself.
6. How do enums with associated values and pattern matching replace class hierarchies?
An enum case can carry data, and a switch over it must be exhaustive. That makes an enum the natural model for a closed set of states:
enum LoadState {
case idle
case loading(progress: Double)
case loaded([Item])
case failed(Error)
}
switch state {
case .loading(let p) where p > 0.5: showAlmostDone()
case .loaded(let items): show(items)
case .failed(let error): show(error)
case .idle, .loading: break
}
Adding a case breaks every switch that does not handle it. That is the point: the compiler finds every place to update. Mark an enum indirect when a case refers to the enum itself, as in a tree.
7. How do throws, Result and rethrows fit together?
A throws function propagates errors to a caller that must use try. Result<Success, Failure> stores the outcome as a value, which is useful when you must hold it, pass it through a non-throwing API or report it later.
rethrows marks a higher-order function that throws only if its closure argument throws, which is why map needs no try with a non-throwing closure. defer blocks run on every exit path, including a thrown error, which makes them the place for cleanup.
Protocols and Generics
8. Why can a method in a protocol extension behave differently from the one you wrote?
Requirements declared in the protocol are dispatched dynamically through the witness table. Methods that exist only in a protocol extension are dispatched statically, based on the type the compiler sees.
The fix is to declare bye() in the protocol. Candidates who have hit this bug in production tend to explain it quickly.
9. What is the difference between some and any?
some Shape is an opaque type: one specific concrete type that the compiler knows and the caller does not. any Shape is an existential: a box that can hold any conforming type and can change at run time.
some keeps static dispatch and full type information, which is why SwiftUI's body returns some View. any costs a box and dynamic dispatch but allows heterogeneous collections such as [any Shape].
The rule most teams follow: write some by default and any only when the concrete type must vary.
some Shape
One concrete type, fixed at compile time
Static dispatch, no box
The default for parameters and return types
any Shape
Any conforming type, chosen at run time
Existential box and dynamic dispatch
Needed for mixed collections like [any Shape]
10. What are associated types and primary associated types?
An associated type is a placeholder a protocol leaves for each conforming type to fill, such as Element in Collection.
A primary associated type is listed in angle brackets on the protocol, protocol Collection<Element>, so callers can constrain it without a where clause:
func total(_ values: some Collection<Int>) -> Int {
values.reduce(0, +)
}
The same syntax works with any: any Collection<Int>.
11. What is conditional conformance?
A generic type conforms to a protocol only when its type arguments do. Array is Equatable only when its Element is:
extension Stack: Equatable where Element: Equatable {}
Generic types stay general but gain what their contents allow. It is how the standard library makes [Int] hashable but [() -> Void] not.
12. When would you write a property wrapper, and when a macro?
A property wrapper moves the storage logic of one property into a reusable type: clamping, trimming, reading from UserDefaults. It runs at run time and can only see that one property.
A macro (Swift 5.9 and later) runs at compile time and generates code from the syntax you annotate. @Observable is a macro because it rewrites every stored property of a class, which a property wrapper cannot do.
Macros cost build time and are harder to debug, so a wrapper or a plain function stays the first choice when it can do the job.
13. What is a result builder?
A result builder turns a sequence of statements into a single value by calling static buildBlock, buildOptional, buildEither and related methods.
SwiftUI's @ViewBuilder is one: each view in a body becomes an argument to buildBlock, and an if becomes buildEither.
They suit domain-specific languages for HTML, regexes or test data. A strong candidate knows that each statement inside a builder must produce a value of a type the builder accepts, which explains many confusing SwiftUI compiler errors.
Concurrency
14. How do you wrap a completion-handler API in async/await?
Use a checked continuation and resume it exactly once:
func loadUser(id: String) async throws -> User {
try await withCheckedThrowingContinuation { continuation in
api.fetchUser(id: id) { result in
continuation.resume(with: result)
}
}
}
Resuming twice is a crash, and never resuming leaks the suspended task. The checked variant reports both mistakes at run time; withUnsafeContinuation skips the checks.
For Objective-C methods with a completion handler, Swift already imports an async version automatically.
15. What is structured concurrency, and how do async let, TaskGroup and Task differ?
Structured concurrency means child tasks cannot outlive the scope that created them. When the scope exits, it waits for or cancels its children, and errors propagate up.
async let: a fixed number of child tasks, such as loading a profile and its settings in parallel.
withThrowingTaskGroup: a dynamic number of children, such as one download per URL.
Task { }: unstructured. It inherits the caller's actor isolation and priority but is not canceled when the caller's scope ends.
Task.detached { }: unstructured and inherits nothing. Rarely the right choice.
16. How does task cancellation work?
Cancellation is cooperative. Canceling a task sets a flag. The task stops only when its code checks the flag with try Task.checkCancellation() or Task.isCancelled, or calls an API that checks it.
Task.sleep and URLSession's async methods do, and throw CancellationError.
Canceling a parent cancels all its child tasks. A long CPU loop that never checks the flag keeps running after cancellation, which is the bug interviewers look for.
17. What is actor reentrancy, and why does it cause bugs?
An actor runs one task at a time, but only between suspension points. At every await inside an actor method, other calls can run and change the actor's state.
actor ImageCache {
var cache: [URL: Image] = [:]
func image(for url: URL) async throws -> Image {
if let hit = cache[url] { return hit }
let image = try await download(url) // other calls run here
cache[url] = image // may overwrite a newer value
return image
}
}
Two callers asking for the same URL both download it. The usual fix stores the in-flight Task in the dictionary so the second caller awaits the first download. The lesson: re-check state after every await.
18. What does Sendable mean?
Sendable marks a type that is safe to pass between concurrency domains. Value types whose members are all Sendable qualify, and non-public ones are inferred automatically. Actors are always Sendable.
A class qualifies if it is final and its stored properties are immutable and Sendable. A class that guards its own state with a lock can be marked @unchecked Sendable.
@unchecked Sendable tells the compiler to trust you. A candidate who reaches for it first, instead of a lock-protected design or an actor, will spread data races the checker can no longer see.
19. What does @MainActor do?
@MainActor isolates a function, property or whole type to the main actor, whose executor is the main thread. UIKit and SwiftUI views are main-actor types, so calling them from another context requires await.
It replaces DispatchQueue.main.async with a compile-time check: code that touches the UI off the main thread no longer compiles in the Swift 6 language mode.
MainActor.assumeIsolated exists for legacy callbacks that are known to arrive on the main thread but are not annotated.
20. How do you bridge a delegate or callback stream into async code?
Use AsyncStream (or AsyncThrowingStream) and consume it with for await:
let (stream, continuation) = AsyncStream.makeStream(of: Location.self)
manager.onUpdate = { continuation.yield($0) }
continuation.onTermination = { _ in manager.stop() }
for await location in stream { update(location) }
Know the buffering policy. The default buffers without limit, while .bufferingNewest(1) keeps only the latest value, which suits sensor data. onTermination is where you stop the underlying source when the consumer cancels.
Performance and Testing
21. What are noncopyable types?
A type marked ~Copyable (Swift 5.9, SE-0390) cannot be copied: every value has exactly one owner, and ownership moves on assignment.
That lets a struct model a unique resource such as a file descriptor, with a deinit that closes it, and no reference counting.
Parameters say what they do with ownership: borrowing reads without taking it, consuming takes it, and inout mutates in place. Swift 6.4 extends this family with UniqueBox and UniqueArray.
22. How does Swift Testing differ from XCTest?
Swift Testing ships with Swift 6 and later. It marks tests with @Test instead of the test name prefix. It checks with the #expect and #require macros instead of the XCTAssert family. It runs tests in parallel by default.
Parameterized tests like this one replace hand-written loops, and each argument reports as its own result. XCTest is still needed for UI tests and performance tests.
23. What makes Swift code slow, and how do you find it?
Measure first, with the Time Profiler and Allocations instruments in a release build. Debug builds skip optimization and can be many times slower, so timing them misleads.
The usual causes:
Unexpected copies of large values.
Heavy reference counting from classes in tight loops.
Existential boxing from any where a generic would do.
Dynamic dispatch through non-final classes.
final and private let the compiler devirtualize calls; whole-module optimization, on by default in release builds, lets it see across files.
24. How do you decode JSON whose keys do not match your properties?
For snake_case keys, set decoder.keyDecodingStrategy = .convertFromSnakeCase. For anything else, declare a nested CodingKeys enum that maps each property to its key.
When the shape itself differs, such as a nested object you want flattened, implement init(from:) by hand.
struct User: Decodable {
let id: Int
let name: String
enum CodingKeys: String, CodingKey {
case id = "user_id"
case name = "display_name"
}
}
A missing key throws unless the property is optional, and decodeIfPresent is the explicit way to allow it.
What Changed Recently
Sep 17, 2024
Swift 6.0: Swift 6 language mode, typed throws, Swift Testing
Mar 31, 2025
Swift 6.1: @objc @implementation, trailing commas in more places
Sep 15, 2025
Swift 6.2: approachable concurrency, InlineArray, Span
Mar 24, 2026
Swift 6.3: module selectors, @c, Android SDK
Sep 15, 2026
Swift 6.4: cancellation shields, async defer, Subprocess 1.0
25. What does the Swift 6 language mode change?
It turns complete data-race checking into errors. Code that shares mutable state across concurrency domains without Sendable types, actors or isolation annotations stops compiling. The compiler version and the language mode are separate.
The Swift 6 migration guide says the mode is opt-in and set per target. A Swift 6.4 compiler still builds Swift 5 mode code.
The sensible migration path is to enable complete checking as warnings in Swift 5 mode, fix them module by module, then switch each module to Swift 6 mode. Swift 6.0 also added region-based isolation (SE-0414).
It lets the compiler accept passing a non-Sendable value to another task when it can prove the caller no longer uses it.
Compiler version is not language mode. Xcode 27 ships the Swift 6.4 compiler, but a target still builds in Swift 5 mode until its Swift Language Version setting, or swiftLanguageModes in a package manifest, says 6.
26. What are typed throws?
Since Swift 6.0 (SE-0413), a function can declare the exact error type it throws:
enum ParseError: Error { case empty, badDigit(Character) }
func parse(_ s: String) throws(ParseError) -> Int {
guard !s.isEmpty else { throw .empty }
...
}
do { _ = try parse(input) }
catch { print(error) } // error is ParseError, not any Error
The catch block gets a concrete type, with no casting. The proposal itself advises plain throws for most code, because a public API that commits to one error type cannot add new failure kinds later.
Typed throws fit internal code and embedded targets that cannot afford existential boxing.
27. What did Swift 6.2's approachable concurrency change?
Main actor by default (SE-0466): a module can opt in to treating all its code as @MainActor unless marked otherwise. It suits app targets and scripts, where most code touches the UI anyway.
Async functions run on the caller's actor (SE-0461): with the NonisolatedNonsendingByDefault feature on, a nonisolated async function no longer hops to the global executor. It runs where it was called, so passing it a non-Sendable value is no longer an error.
@concurrent: the explicit way to say a function should run off the actor, on the concurrent thread pool.
An interviewer can ask where a given function runs and see whether the candidate asks which flags the module has enabled. That question is the right answer, because the same source behaves differently with and without the feature.
28. What are InlineArray and Span?
Both arrived in Swift 6.2. InlineArray (SE-0453) is a fixed-size array stored inline, on the stack or inside its containing type, with no heap allocation. [40 of Sprite] is shorthand for InlineArray<40, Sprite>.
Span (SE-0447) is a safe view of contiguous memory. The compiler guarantees at compile time that a span cannot outlive the memory it points to, which removes the use-after-free risk of UnsafeBufferPointer with no run-time cost.
Swift 6.4 extends this: Span now bridges directly to C++20's std::span.
Module selectors: ModuleA::getValue() picks an API when two imported modules declare the same name.
@c: exposes a Swift function or enum to C through the generated header, or with @implementation, implements a function a C header already declares.
Performance attributes for library authors: @specialize, @inline(always) and @export(implementation).
The first official Swift SDK for Android, with Swift Java for calling Swift from Kotlin and Java.
30. What does Swift 6.4 add for cleanup code?
Two features that work together, from the Swift 6.4 release post. A defer block can now contain await (SE-0493), and withTaskCancellationShield (SE-0504) runs a closure that the enclosing task's cancellation does not reach.
Before 6.4, cleanup that needed to await had to be duplicated on every exit path, and a canceled task could skip it.
The same release makes Swift Build the default build system in Swift Package Manager and ships Subprocess 1.0, a cross-platform async API for running other programs.
Signs of a Strong Answer
They re-check actor state after every await without being prompted, and can show the in-flight Task fix for duplicate work.
They ask which language mode and feature flags a module uses before saying where an async function runs.
They treat @unchecked Sendable and nonisolated(unsafe) as debts to justify, not fixes.
They can explain the protocol-extension dispatch trap in question 8 from memory.
They default to some and structs, and can say what they would lose by switching to any or a class.
They profile a release build before changing code for speed.