Mastering the framework (SwiftUI or UIKit) is only half the battle. In high-level technical interviews, recruiters need to know if you understand the language underneath. Do you know how Swift manages memory? Do you understand the real difference between struct and class? have you mastered modern concurrency?
Here is the definitive collection of Swift questions, divided by difficulty level. We cover the 165 essential questions.
🟢 Level 1: Basic Concepts and Syntax
These questions are the initial filter. If you fail here, the interview usually ends.
- What is Swift? It is a multi-paradigm, strongly typed, compiled, open-source programming language developed by Apple. It is designed to be safe, fast, and expressive.
- What is the difference between
varandlet?vardeclares mutable variables (their value can change).letdeclares constants (immutable once assigned). - What is Type Inference? The Swift compiler’s ability to deduce the data type of a variable based on its initial value, without needing to write it explicitly.
- What is an
Optionalin Swift? It is a type that represents the possibility of a variable having a value or having nothing (nil). It is defined with?. - What is Type Safety? Swift forces you to be clear about data types. You cannot accidentally assign a
Stringto anIntvariable; the compiler will throw an error. - What is a Tuple? A group of values combined into a single compound value. They can be of different types. Ex:
(404, "Not Found"). - What is a
typealias? It allows you to give an alternative name to an existing type to make the code more readable. Ex:typealias AudioSample = UInt16. - What is the difference between
FloatandDouble?Floatis a 32-bit floating-point number (less precision).Doubleis 64-bit (higher precision and the default in Swift). - What are Generics? Flexible and reusable code that can work with any data type, subject to requirements you define (like
Array<Element>). - What are
AnyandAnyObject?Anycan represent an instance of any type (functions, structs, classes).AnyObjectcan only represent instances of classes.
🔵 Level 2: Collections and Control Flow
- Main difference between
ArrayandSet? AnArrayis ordered and allows duplicates. ASetis unordered and guarantees that every element is unique. - What protocol must
Setelements orDictionarykeys conform to? They must conform toHashable. - What is a Dictionary? An unordered collection of key-value associations.
- What does the
guardstatement do? It is used to transfer control out of a scope if a condition is not met. It is ideal for “early exit” and avoiding the “pyramid of doom” indentation. - Difference between
if letandguard let?if letunwraps the optional only inside its{}block.guard letunwraps the optional for the rest of the current scope, and requires anelse { return/throw }if it fails. - What does it mean that
switchin Swift must be exhaustive? It must cover all possible cases of the evaluated value, or include adefaultcase. - What is the “Range Operator”
...and..<?...is a closed range (includes the end value)...<is a half-open range (excludes the end value). - How do you iterate over a dictionary? Using
for (key, value) in dictionary. - What is
stride? A function to create numeric sequences with specific steps (e.g., from 0 to 10 by 2). - What does
breakdo in a loop? Terminates the execution of the loop immediately. - What does
continuedo in a loop? Skips the current iteration and moves to the next one.
🟠 Level 3: Structs vs Classes
The most asked topic in Swift history.
- What is the fundamental difference between
structandclass?structsare Value Types.classesare Reference Types. - Explain “Value Type”. When you assign or pass a struct, a copy of the data is created. Modifying the copy does not affect the original.
- Explain “Reference Type”. When you assign or pass a class, a reference (pointer) to the same instance in memory is passed. Modifying one affects all references.
- What do Classes have that Structs don’t? Inheritance, deinitializers (
deinit), identity (===), and reference counting (ARC). - What do Structs have that Classes don’t? Automatic
memberwise initand they are lighter in memory (Stack vs Heap). - When should you use a Struct? By default. Use it for simple data models, values that behave like primitive data, and when you don’t need shared identity.
- What does the
mutatingkeyword mean in a Struct? It indicates that a method within the struct is going to modify its own properties. This is necessary because structs are immutable by default. - Are
ArrayandStringin Swift classes or structures? They are Structures (structs). - What is “Copy on Write” (COW)? It is a Swift optimization for collections (like Arrays). Although they are value types, the actual copy only occurs when the data is modified, not when assigned, saving performance.
🟣 Level 4: Optionals Deep Dive
- What is “Optional Binding”? The process of checking if an optional has a value and extracting it to a safe constant/variable (using
if letorguard let). - What is “Optional Chaining” (
?.)? Allows calling properties or methods on an optional that might be nil. If it is nil, the chain stops and returns nil; otherwise, it continues. - What is the “Nil Coalescing” operator (
??)? Provides a default value in case the optional is nil. Ex:let name = user.name ?? "Guest". - What is “Force Unwrapping” (
!)? Extracts the value from the optional forcibly. If it isnil, the app crashes. Should only be used if you are 100% sure. - What is an “Implicitly Unwrapped Optional” (
Type!)? An optional that is assumed to always have a value after its first assignment. It does not require explicit unwrapping when used, but crashes if it is nil (common in@IBOutlets). - Can an optional contain
nilas a valid value inside another optional? Yes,Double Optional(String??).
🔴 Level 5: Functions and Closures
- What is a Closure? They are self-contained blocks of functionality that can be passed around and used in your code. Similar to lambdas in other languages.
- What is the syntax for a “Trailing Closure”? If the last parameter of a function is a closure, you can write it outside the parentheses of the call.
array.map { $0 * 2 }. - What do
$0,$1mean in a closure? They are shorthand argument names for the closure’s arguments. - What is
@escapingin a closure? Indicates that the closure can be executed after the function returns (e.g., an asynchronous network call). By default, they arenon-escaping. - What is
@autoclosure? Automatically converts an expression passed as an argument into a closure. Allows writingassert(condition)instead ofassert({ condition }). - What is a variadic function? A function that accepts zero or more values of a specific type (e.g.,
print(...)). It is written with.... - What are
inoutparameters? They allow a function to modify the value of a variable passed as a parameter (pass by reference). - Are functions first-class citizens in Swift? Yes, they can be assigned to variables, passed as arguments, and returned from other functions.
- What is a Higher Order Function? A function that takes another function as an argument or returns one. Examples:
map,filter,reduce.
⚫ Level 6: Properties and Methods
- Difference between “Stored Property” and “Computed Property”? Stored: Stores a value in memory. Computed: Calculates the value every time it is accessed (has a getter and optionally a setter).
- What are “Property Observers”?
willSet(runs just before the value changes) anddidSet(runs just after). - What is a
lazyproperty? A property whose initial value is not calculated until the first time it is used. It must be avar. - What does
staticmean? Defines a property or method that belongs to the type itself, not to an instance. - Difference between
staticandclassin methods? Both define type methods.staticcannot be overridden in subclasses (it is final),classdoes allowoverride. - What is a Singleton and how is it created in Swift? A pattern where only one instance of a class exists.
static let shared = MyClass(), with aprivate init().
⚪ Level 7: Protocols and Extensions (POP)
Swift is the first Protocol-Oriented language.
- What is a Protocol? A “contract” that defines a blueprint of methods, properties, and requirements that a class, structure, or enumeration must conform to.
- What is an Extension? Allows adding functionality to an existing type (even if you don’t have the original source code), such as new methods or computed properties (not stored).
- What are “Protocol Extensions”? They allow providing a default implementation for protocol methods. It is the basis of Protocol Oriented Programming.
- What is an “Associated Type” in a protocol? A placeholder for a type that will be defined when the protocol is adopted.
associatedtypeis used. - Can an extension add stored properties? No, only computed ones.
- What does
Codablemean? It is atypealiasfor theEncodableandDecodableprotocols. It allows converting objects to/from JSON or other formats. - What is
Equatable? A protocol that allows comparing two instances using==. - What is
Hashable? A protocol that allows an instance to generate an integer hash value, necessary to be a key in Dictionaries or an element in Sets. - What is
CaseIterablein enums? Automatically generates a collection of all cases of the enum (allCases).
🟤 Level 8: Memory Management (ARC)
Crucial for avoiding Memory Leaks.
- What is ARC? Automatic Reference Counting. It is Swift’s system for tracking and managing the app’s memory usage, releasing class instances that are no longer used.
- What is a “Retain Cycle”? When two instances point to each other with strong references, preventing ARC from releasing them, causing memory leaks.
- Difference between
strong,weak, andunowned?strong: Increments the reference count (default).weak: Does not increment the count. Must be optional (var?) because it can become nil.unowned: Does not increment the count. Is not optional (assumes it will always have a value). If the object dies and you access it, it crashes.
- When to use
unownedinstead ofweak? When the other instance has the same lifespan or longer (e.g., Customer and Credit Card; the card does not exist without a customer). - What is a “Capture List” in closures
[weak self]? Defines how the closure captures external variables.[weak self]avoids retain cycles if the closure is owned byselfandselfis used inside the closure. - Do Structs use ARC? No, because they are Value Types (managed in the Stack, not the Heap). ARC is only for classes.
🌓 Level 9: Error Handling
- What protocol must a type conform to in order to be thrown as an error?
Errorprotocol. - What do
try,try?, andtry!mean?try: Throws the error if it occurs (must be in do-catch or throwing function).try?: If it fails, returnsnil(ignores the error).try!: If it fails, crashes the app (you assert it won’t fail).
- What does
deferdo? Defines a block of code that will execute just before the current scope ends (doesn’t matter if it ends via return, error, or normal finish). Useful for closing files or freeing resources. - What is the
Resulttype? An enum with two cases:.success(Value)and.failure(Error). Widely used in completion closures.
✨ Level 10: Modern Concurrency (Swift 5.5+)
- What is
async/await? Syntax for writing asynchronous code that looks synchronous, eliminating “Callback Hell”. - What is an
Actor? A reference type (like a class) that protects its mutable state by ensuring only one thread accesses its data at a time. It is “Thread Safe” by default. - What is
@MainActor? An attribute ensuring that the function or class always runs on the Main Thread, crucial for UI updates. - What is a
Task? A unit of asynchronous work. Allows callingasyncfunctions from a synchronous context. - What is
TaskGroup? Allows creating multiple asynchronous tasks dynamically and waiting for all of them to finish (structured concurrency).
🧩 Level 11: Access Control
- What are the access levels in Swift (from most restrictive to most open)?
private,fileprivate,internal(default),public,open. - Difference between
privateandfileprivate?private: Only visible within the declaration scope (e.g., inside the class).fileprivate: Visible throughout the current.swiftfile. - Difference between
publicandopen? Both allow access from other modules.openallows the class to be subclassedand its methods overridden outside the module.publicdoes not.
🛠 Level 12: Advanced and Runtime
- What is “Method Dispatch”? The mechanism the program uses to know which operation to execute.
- Types of Dispatch in Swift? Static Dispatch (Direct, very fast, Structs), Table Dispatch (Classes), Message Dispatch (Objective-C).
- How do you achieve Static Dispatch in a class? Using
finalorprivate, which prevents overriding. - What is KVO (Key-Value Observing)? A pattern (inherited from Obj-C) to notify objects when properties of other objects change. Requires inheriting from
NSObjectand using@objc dynamic. - What is
some(Opaque Types)? Indicates that you return a specific type that conforms to a protocol, but hide exactly which one it is. - What is
associatedtype? Defines a generic type inside a protocol. - What are “Property Wrappers”? Types that wrap a property to add logic on read/write (e.g.,
@State,@Published,@UserDefault). - What does
finaldo? Prevents a class from being inherited or a method from being overridden. Improves performance. - What are “Raw Values” in an Enum? Pre-populated values (like Int or String) assigned to each enum case. Must be unique.
- What are “Associated Values” in an Enum? Values attached to an enum case at the time of instance creation (can be different each time).
- What is
autoreleasepool? A block that allows releasing temporary objects created in intensive loops immediately, reducing memory peaks. - How do you compare two tuples? The
==operator works automatically if the elements inside the tuple areEquatable(up to 6 elements).
🧠 Level 13: Swift Functional Programming
- What does
mapdo? Transforms each element of a collection using a function and returns a new array. - What does
compactMapdo? Same as map, but removes results that areniland unwraps the remaining optionals. - What does
flatMapdo? Flattens a collection of collections (e.g.,[[1,2], [3,4]]->[1,2,3,4]). - What does
reducedo? Combines all elements of a collection into a single value (e.g., sum all numbers). - What does
filterdo? Returns an array with only the elements that meet a condition. - What does
zipdo? Combines two sequences into a sequence of pairs (tuples). - What is “Currying” (although Swift no longer supports it syntactically by default)? Converting a function with multiple arguments into a sequence of functions with a single argument.
- Is Swift a functional language? Not purely, but it has strong support for functional programming (first-class functions, immutability, HOFs).
🔍 Level 14: Debugging and Miscellaneous
- What is
#if DEBUG? A conditional compilation directive to execute code only in development mode. - What is the difference between
Self(capital) andself(lowercase)?self: the current instance.Self: the type of the current instance (useful in protocols).
🧬 Level 15: Advanced Generics and Existential Types
This is the most common barrier between a Mid-level and a Senior developer.
- What is “Type Erasure” and why do we need it? It is a pattern for working with protocols that have
associatedtype. Since those protocols cannot be used as direct variable types (historically), they are wrapped in a generic class/struct (e.g.,AnyPublisher,AnyView) that “hides” the underlying concrete type. - What is the difference between
some Protocolandany Protocol(Swift 5.7+)?some(Opaque Type) guarantees that the type is fixed and concrete, but hidden from the caller (static performance).any(Existential Type) is a dynamic box that can hold any type that conforms to the protocol, allowing the value to change at runtime (has a performance cost). - What are “Opaque Return Types”? Functions that return
some View(orsome Protocol). They allow the compiler to know the exact type for optimizations, but force the developer to always return the same concrete type within the function. - What does the
whereconstraint mean in generics? It allows defining additional requirements for generic types. Ex:func compare<T>(a: T, b: T) where T: Equatable. - What is “Conditional Conformance”? It allows a generic type to conform to a protocol only if its internal types also conform. Ex:
ArrayisCodableonly if its elements (Element) areCodable. - What is a “Primary Associated Type” in protocols? Lightweight syntax (
Protocol<Type>) introduced in Swift 5.7 to constrain associated types. Ex:func process(list: some Collection<String>). - Why couldn’t protocols with
Selforassociatedtypebe used as types until recently? Because the compiler couldn’t know how much memory space to reserve for them without knowing the concrete type. Nowanysolves this by creating an “existential container” box. - What is covariance and contravariance in Swift? It refers to how subtypes relate in complex types. Swift is generally invariant in generics (an
Array<Cat>is not anArray<Animal>), but functions have special subtyping rules for their return types and arguments.
🛠 Level 16: Pointers and “Unsafe” Swift
Swift is safe, but it allows you to be dangerous if you need to interact with C or optimize to the max.
- What does “Unsafe” mean in Swift (e.g.,
UnsafePointer)? It means Swift disables its safety checks (like array bounds checking or automatic memory management). If you make a mistake here, you cause a crash or memory corruption. - Difference between
UnsafePointer,UnsafeMutablePointer,UnsafeRawPointer, andUnsafeBufferPointer.Pointer: Read-only, typed (UnsafePointer<Int>).Mutable: Read and write.Raw: Untyped (pure bytes,void*in C). It doesn’t know what data type is there, it only sees memory.Buffer: Works like an array (hascount) over a continuous memory region.
- What is
withUnsafeBytes? A method to temporarily access the byte representation of data (like an Array or Data) safely within a closure. - What is “Memory Layout” (alignment, size, and stride)?
size: Actual space the data occupies.alignment: Memory rule (e.g., must start at a multiple of 8).stride: Distance between the start of one element and the next in an array (includes padding).
- How do you convert a Swift String to a C
char *? Swift does automatic bridging in interoperability, or you can usestring.withCString { ptr in ... }. - What is a “Dangling Pointer”? A pointer that points to a memory address where the object has already been deallocated.
⚙️ Level 17: Compiler and Performance
- What are the main phases of Swift compilation? Parsing (Source code) -> AST (Abstract Syntax Tree) -> SIL (Swift Intermediate Language) -> LLVM IR -> Machine Code.
- What is SIL (Swift Intermediate Language)? An intermediate language specific to Swift where high-level optimizations occur (like ARC optimization, devirtualization, generics specialization) before passing to LLVM.
- What is “Whole Module Optimization” (WMO)? A compilation mode where the compiler analyzes the entire module at once (instead of file-by-file), allowing better optimizations like aggressive inlining and dead code elimination.
- What is “Method Swizzling”? An Objective-C runtime technique (possible in Swift by inheriting from NSObject) to change the implementation of a method at runtime.
- What is “Dynamic Dispatch” vs “Static Dispatch” vs “Witness Table”?
- Static: The function address is known at compile time (fast).
- Dynamic (V-Table): Looked up in a table at runtime (Classes).
- Witness Table: Used for Protocols.
- Message Dispatch: Obj-C Runtime (slower, but very flexible).
- How does Swift reduce the cost of ARC? The compiler (in the SIL phase) analyzes the code and removes redundant calls to
retainandrelease. - What is “Generic Specialization”? The compiler creates specific versions of a generic function for concrete types (e.g., creates a version of
sum<Int>and another ofsum<Float>) to avoid abstraction overhead. - What attribute do you use to force a function to be “inlined”?
@inline(__always).
🍏 Level 18: Interoperability (Obj-C and C++)
- What does the
@objcmodifier do? Exposes a Swift method or property to the Objective-C runtime. - What does
dynamicmean in Swift? Forces the method to use Objective-C “Message Dispatch” instead of Swift’s static or virtual table dispatch. Necessary for KVO and Swizzling. - Can a Swift
structbe used in Objective-C? No. Only classes inheriting fromNSObject(or pure Swift classes with@objcthat don’t use Swift-exclusive features) are visible. - What is a “Bridging Header”? A
.hfile that allows importing Objective-C headers so they are visible and usable from Swift code. - What is C++ Interop in Swift 5.9? The native ability to import and use C++ types directly in Swift without needing to create “wrappers” in Objective-C++.
📦 Level 19: Swift Package Manager (SPM) and Modularization
- What is the difference between a Library and a Framework? Technically, a library is compiled code (static or dynamic). A framework is a directory structure that packages the library along with resources (images, headers).
- Static vs Dynamic Library?
- Static: Code is copied inside your app’s executable (increases app size, faster launch).
- Dynamic: Code lives outside the executable and loads at launch (reduces app size, launch might be slower, allows code sharing between extensions).
- What is
Package.swift? The manifest file that defines the dependencies, targets, and products of an SPM package. - How do you manage resources (images/JSON) in an SPM package? Using the
Resourcesfolder and accessing viaBundle.module.
🔮 Level 20: Modern Swift (5.9, 6.0) and Macros
- What is a Macro in Swift (
#Predicate,@Model)? Code that runs at compile time to generate more Swift code, reducing boilerplate. - Difference between Freestanding Macro and Attached Macro?
- Freestanding: Appear on their own (e.g.,
#warning("Careful")). - Attached: Attached to a declaration (e.g.,
@Observableon a class).
- Freestanding: Appear on their own (e.g.,
- What is the “Ownership Manifesto”? A set of features to granularly control memory without ARC overhead, approaching Rust-like control.
- What do the keywords
consumingandborrowingdo?consuming: The function takes ownership of the value (and is responsible for destroying it).borrowing: The function “borrows” the value (read access) without incrementing reference counts.
- What is a
Noncopyable Type(~Copyable)? A type (struct or enum) that cannot be copied. Useful for unique resources like file descriptors or mutexes. - What is “Actor Reentrancy” and what problem does it cause? An actor can suspend a function (
await) and start processing another task before the first one finishes. This can change the actor’s internal state unexpectedly between the “before” and “after” of theawait.
🧩 Level 21: Trick Code Questions (“Output Prediction”)
The interviewer puts this code on the whiteboard. What is your answer?
- The Mystery of Protocol Dispatch:
protocol A { func a() }
extension A { func a() { print("A") } }
struct B: A { func a() { print("B") } }
let b = B()
let a: A = b
b.a() // What does it print?
a.a() // What does it print?Answer: Prints “B” and “B”. Since a() is defined in the protocol requirement, it uses dynamic dispatch (Witness Table) and finds B‘s implementation.
The Mystery of the Hidden Extension:
protocol A { }
extension A { func a() { print("A") } } // Not in the protocol definition
struct B: A { func a() { print("B") } }
let a: A = B()
a.a()Answer: Prints “A”. Since a() is not in the original protocol definition protocol A {}, static dispatch is used. The variable a is of type A, so it uses A‘s extension, ignoring B‘s.
Arrays and Closures:
var array = [1, 2, 3]
let closure = { print(array) }
array.append(4)
closure()Answer: Prints [1, 2, 3]. Arrays are value types and the closure captures a copy of the array at the moment of closure creation (implicit capture list for value types). Note: If array were a Class, it would print 1, 2, 3, 4.
Defer Stack:
func test() {
defer { print("1") }
defer { print("2") }
print("3")
}- Answer: “3”, “2”, “1”.
deferstatements execute in reverse order (like a stack) when exiting the scope. - Lazy var and Concurrency: Is it safe to access a
lazy varproperty from multiple threads at once? Answer: No.lazy varis not thread-safe. If two threads access it simultaneously for the first time, the initializer might run twice or cause a crash.
📐 Level 22: Design Patterns in Swift
- What is the “Delegate” pattern? A pattern where an object delegates responsibility or notification to another. In Swift, it is used with protocols
weak var delegate: DelegateProtocol?to avoid retain cycles. - How do you implement the “Observer” pattern in pure Swift? Using
NotificationCenter, KVO, or more modernly,@Publishedwith Combine/SwiftUI. - What is “Dependency Injection” and why is it vital? Passing dependencies to an object (usually in the
init) instead of the object creating them. Vital for Unit Testing with Mocks. - What is the “Builder” pattern? Useful for creating complex objects step-by-step. In Swift, it’s often seen functionally (e.g., URLRequest configurators).
- What is the “Coordinator” pattern? (Widely used in iOS) Extracts navigation logic from ViewControllers, facilitating flow and screen reusability.
🏛 Level 23: Data Structures and Algorithms (Swift Context)
- What is the complexity of
array.insert(element, at: 0)? O(n), because it has to shift all remaining elements one position. - What is the complexity of accessing a value in a Dictionary? O(1) on average.
- How does
Dictionarywork internally in Swift? It uses Linear Probing and open addressing hash tables. Requires keys to beHashable. - What is
ContiguousArray? A specialized version of Array that always stores its elements contiguously in memory. It is more efficient than standardArrayif storing classes or if bridging to Objective-CNSArrayis not needed. - What are the
Collectionprotocols?Sequence->Collection->BidirectionalCollection->RandomAccessCollection. Knowing which one to use is key to creating your own data structures.
🧪 Level 24: Testing
- Difference between
setUpandsetUpWithErrorin XCTest?setUpWithErrorallows throwing errors. If it fails, the test marks as failed cleanly without crashing. - What is a “Mock” vs a “Stub”?
- Stub: Fake object that returns predefined data (so the test runs).
- Mock: Fake object that also verifies behavior (e.g., “was this method called exactly 1 time?”).
- How do you test asynchronous code in old vs new XCTest? Old:
XCTestExpectationandwait. New: Mark the test function asasyncand useawait.
🏁 Level 25: Expert Miscellaneous
- What is
Neverin Swift? A type indicating that a function never returns (e.g.,fatalError()or a function that intentionally crashes). - What is
Voidreally? It is a typealias for an empty tuple(). - What is reflection (
Mirror) in Swift? Allows inspecting the structure of a type at runtime (listing properties, types). It is limited and slow compared to other languages, but useful for logging or custom serialization. - What is the
@discardableResultattribute? Silences the compiler warning if you call a function that returns something but you ignore the result. - What is the
@availableattribute? Allows marking code that should only run on certain iOS/macOS versions or that is deprecated. - What are “KeyPaths” (
\Person.name)? Safe references to a property of a type, not its value. They allow metaprogramming and elegant dynamic APIs. - What is
@dynamicMemberLookup? Allows accessing properties of a type using dot syntax (a.b) even if those properties don’t exist at compile time, resolving them dynamically (useful for wrapping JSON or Python). - What is
@propertyWrapper? The mechanism behind@State,@Published, etc. It allows you to encapsulate property storage logic in a reusable type. - How do you avoid generic code bloat in the binary? Using existential types (
any) where static performance is not critical, or using@_specializecarefully. - What is “ABI Stability”? Achieved in Swift 5.0. It means the Swift runtime is built into the OS (iOS) and apps don’t need to include Swift libraries inside the binary, reducing app size and allowing binary compatibility between versions.