Skip to main content
InterviewHubPRO
HomeTracksSection 50: Swift & Concurrency (50 Qs)
Section 50 of 6450 Questions (1 Per Page)

Swift Language, Memory Safety & Modern Concurrency Master Interview Bank

Automatic Reference Counting (ARC), Value vs Reference Types, Copy-on-Write, Swift Concurrency (async/await, Actors, Sendable), and Protocols.

Curriculum Roadmap & Learning Path

3 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Core Language, Memory & Value Types (1 - 10)

10 Questions
1
JuniorCode#TypeScript

What are the key differences between Value Types (struct, enum) and Reference Types (class) in Swift?

The core architectural distinction in Swift: Value Types (struct, enum, primitives like Int, String, Array) • Allocated on the Stack (fast allocation and deallocation) • Copied on assignment or when passed to functions (Copy-On-Write) • Thread-safe by default because each thread operates on its own isolated copy.

2
Junior#swift#Core Language

How does Automatic Reference Counting (ARC) work in Swift?

ARC automatically manages memory for class instances on the heap: Every time a new reference to an instance is created, ARC increments its reference count by 1 • When a reference goes out of scope or is set to nil, ARC decrements the reference count by 1.

3
JuniorCode#swift#Core Language

What is a Retain Cycle (Strong Reference Cycle) and how do you resolve it?

A retain cycle occurs when two class instances hold strong references to each other, preventing either reference count from ever reaching 0: Result: Memory Leak; neither instance can ever be deallocated! • Resolution: Break the cycle using weak or unowned references • weak: Does not increment reference count.

4
Most AskedJuniorCode#Closures & Scope

What is a Capture List in Swift Closures (`[weak self]`)?

Closures are reference types that strongly capture any variables referenced within their body: If a class instance owns a closure (e.g. onComplete), and the closure references self (self.refreshUI()), a Retain Cycle is formed (self ->.

5
Junior#swift#Core Language

What are Optionals and how do you safely unwrap them in Swift?

An Optional represents a variable that can either hold a wrapped value or nil: Optional Binding (if let / guard let): Safely unwraps the value (preferred standard) • Nil-Coalescing Operator (??): Provides a fallback default value (let name = inputName ??

6
Most AskedSeniorCode#Async & Promises

How does Swift Concurrency (`async/await`) work and how does it replace completion handlers?

Before Swift 5.5, asynchronous code relied on nested completion handler closures, leading to "Callback Hell" and unhandled error states: async/await: Writes asynchronous code that reads like synchronous procedural code • When code hits await, the execution thread is suspended, freeing the underlying OS thread to do other work.

7
JuniorCode#swift#Core Language

What are Actors in Swift and how do they eliminate Data Races?

An actor is a reference type that protects its mutable state through Actor Isolation: Only one task can execute code inside an actor instance at any given time • All external calls to an actor's methods or properties must use await, waiting their turn in an orderly queue.

8
JuniorCode#swift#Core Language

What is `@MainActor` in Swift?

A globally unique actor that always executes code on the Main Thread (UI thread): Annotating a class, function, or view model with @MainActor guarantees that all state mutations and UI updates are executed on the main thread.

9
Junior#swift#Core Language

What is the `Sendable` protocol in Swift 6?

The cornerstone of Data-Race Safety in Swift 6: A Sendable type is safe to transfer across concurrency boundaries (between tasks or actors) • What is Sendable?: Value types (structs with Sendable members), Actors, and immutable final classes with immutable properties.

10
SeniorCode#swift#Core Language

What are Tasks and TaskGroups in Swift Concurrency?

Task: The basic unit of asynchronous execution • Structured Concurrency (async let / withTaskGroup) • async let: Runs multiple independent async calls in parallel and awaits them together • withTaskGroup: Runs a dynamic list of concurrent child tasks, automatically propagating cancellation if the parent task fails.

Part 2: Concurrency, Actors & Advanced Architecture (11 - 24)

14 Questions
11
SeniorCode#System Design

What is Copy-On-Write (COW) in Swift and how do you implement it for custom structs?

Standard Swift collections (Array, Dictionary, String) are value types with Copy-On-Write optimization: When you assign b = a, memory is not duplicated immediately; both variables share the same underlying memory buffer • Memory is only duplicated when one of the variables attempts to mutate data!

12
SeniorCode#System Design

What are Method Dispatch mechanisms in Swift (Static vs Table vs Message Dispatch)?

How the CPU determines which executable memory address to jump to when calling a method: Static / Direct Dispatch (Fastest): Resolved at compile time • Table / Witness Table Dispatch (Medium): Dynamic dispatch via a virtual function table (vtable for classes, witness table for protocols).

13
Senior#System Design

What is Swift 6 Complete Concurrency Checking and how do you migrate legacy code?

Swift 6 enables strict compile-time concurrency checking by default: Flags all data races, unsafe global variables, and non-Sendable type sharing across tasks as compiler errors • Migration Strategy • Enable -warn-concurrency in Swift 5.10 • Mark shared reference classes as actor or wrap in @MainActor.

14
Senior#System Design

What are Protocols, Protocol Extensions, and Protocol-Oriented Programming (POP) in Swift?

Swift prioritizes composition over class inheritance. Protocols define contracts of methods and properties. Protocol Extensions allow providing default implementations for protocol methods, enabling modular, horizontal code sharing across structs and classes without fragile base class hierarchies.

15
Senior#System Design

What is the difference between Opaque Return Types (some) and Existential Any (any)?

some Protocol (Opaque Type): The function returns a specific concrete type known to the compiler, but hidden from the caller • any Protocol (Existential Container): A dynamic box holding any type that conforms to the protocol.

16
Senior#System Design

What are Property Wrappers (@propertyWrapper) and how do they work under the hood?

A Property Wrapper encapsulates property access logic (validation, caching, persistence). The compiler synthesizes a backing storage property prefixed with an underscore (_propertyName) and a projected value ($propertyName).

17
Senior#System Design

How does ResultBuilder in Swift enable declarative DSL syntax like SwiftUI?

@resultBuilder is a compiler transformation feature. It translates a list of sequential statements or expressions inside a closure into a single combined return value by invoking static builder methods (buildBlock, buildEither, buildOptional).

18
Senior#System Design

What are KeyPaths and Dynamic Member Lookup in Swift?

A KeyPath is a strongly typed, uninvoked reference to a property of an object. @dynamicMemberLookup allows classes/structs to intercept dot-syntax property lookups dynamically at compile time.

19
Senior#System Design

How does Structured Concurrency differ from Unstructured Concurrency (Task.detached) in Swift?

Structured (async let, withTaskGroup): Child tasks inherit task priorities, cancellation state, and task-local values from the parent scope • Unstructured (Task.detached): Spawns an independent background task that does not inherit caller priority or cancellation, requiring manual.

20
Senior#System Design

How does Error Handling work in Swift: do-try-catch vs Result<T, E> vs Typed Throws in Swift 6?

Historically, Swift functions threw untyped any Error. Swift 6 introduces Typed Throws (throws(PaymentError)), allowing the compiler to know the exact error type and eliminating untyped catch-all boilerplate.

21
Senior#System Design

What is MemoryLayout<T> and how does Swift handle struct alignment and stride?

Size: Contiguous bytes of actual data stored • Alignment: Memory boundary required by CPU architecture (e.g. 8-byte boundary) • Stride: Distance in bytes between successive elements in an array, including padding bytes required for alignment.

22
Senior#System Design#HTTP & REST APIs

What is the Unsafe Pointer API in Swift (UnsafePointer, UnsafeMutableRawPointer)?

Swift is memory-safe by default. Unsafe pointer types provide direct, unmanaged C-style memory address manipulation for low-level systems programming and C interoperability.

23
Senior#Forms#System Design

How do Swift Macros (Freestanding vs Attached) transform syntax at compile time?

Introduced in Swift 5.9, Swift Macros use SwiftSyntax to inspect code AST at compile time and emit new Swift code safely in sandboxed out-of-process compiler plugins.

24
Senior#System Design

How does C and C++ Interoperability work in modern Swift?

Swift has native, bidirectional C and C++ interop. You can import C++ headers directly into Swift modules and call C++ templates, vectors, and member functions without writing manual C wrappers.

Part 3: Runtime Internals, Swift 6 Safety & Systems Programming (25 - 35)

26 Questions
25
Senior#Async & Promises

What is AsyncSequence and AsyncStream in Swift Concurrency?

AsyncSequence represents an asynchronous stream of values delivered over time (like WebSocket frames or notifications) iterated with for await value in stream.

26
Senior#Forms#Performance

How does Whole Module Optimization (WMO) and @inlinable optimize Swift binary performance?

Standard compilation compiles files individually. WMO analyzes all files in a module simultaneously, allowing the compiler to devirtualize protocol witness tables and inline method implementations across files.

27
Senior#TypeScript

What are Generics with where clauses and Primary Associated Types in Swift?

Primary associated types (protocol CollectionElement) simplify generic code by allowing constraints to be specified inline rather than requiring complex outer where clauses.

28
Senior#swift#Runtime Internals

What is Non-Copyable Types (~Copyable) in Swift 5.9+ and why are they critical for systems programming?

Types in Swift are copyable by default. Suppressing copyability with ~Copyable guarantees unique ownership of resources (like file handles or hardware locks) with zero ARC retain/release overhead.

29
Senior#swift#Runtime Internals

How does the Swift Runtime manage weak references via the Side Table?

Every Swift object has an inline reference count. When an object is referenced by a weak pointer, the runtime allocates a Side Table, moving reference counts there so the object's inline memory can be freed as soon as strong references reach zero.

30
Senior#swift#Runtime Internals

What is Dynamic Member Lookup and @dynamicCallable in Swift?

Allows Swift to interoperate smoothly with dynamic languages like Python or JavaScript, allowing arbitrary method calls and property lookups to be resolved at runtime.

31
Most AskedSenior#Databases & SQL

How does String manipulation work in Swift and why does String not support integer indexing?

Swift strings are collections of extended grapheme clusters (Unicode characters can consist of multiple code points, like flags and emojis with skin tones). Because characters vary in byte length, integer indexing cannot be O(1) and is disallowed.

32
Senior#swift#Runtime Internals

What are Custom Operators and Precedence Groups in Swift?

Swift allows defining custom infix, prefix, and postfix operators with explicit precedence and associativity rules relative to existing operators.

33
Senior#swift#Runtime Internals

What is Mutating functions in Structs and how does it relate to the inout parameter?

Because structs are value types, their methods cannot modify properties by default. Marking a method mutating implicitly passes self as an inout reference, writing changes back to the caller.

34
Senior#TypeScript

How does Enums with Associated Values provide Algebraic Data Types in Swift?

Swift enums are sum types that can carry strongly typed payloads for each case, making illegal application states unrepresentable.

35
Senior#swift#Runtime Internals

When should you choose Swift on the Server (Vapor / Hummingbird) over Node.js or Go?

Choose Server-Side Swift for teams sharing models and validation logic between iOS clients and backend services, combined with high throughput and predictable memory usage without GC pauses.

36
Senior#swift#Runtime Internals

Swift 6 Complete Concurrency and Data-Race Safety: Strict checking, `@Sendable`, and region-based isolation.

Swift 6 introduces Compile-Time Data-Race Freedom: Code that mutates shared mutable state concurrently across threads without protection is rejected at compile time • @Sendable Closures: Closures that can safely cross concurrency boundaries.

37
Senior#swift#Runtime Internals

Swift Macros (Freestanding vs Attached): Metaprogramming with SwiftSyntax.

Swift Macros replace fragile pre-processor templates with type-safe compile-time code generation: Freestanding Macros (#) • expression: Produces a value (e.g. #URL("https://apple.com") validates the URL at compile time) • declaration: Generates one or more declarations (e.g. #warning).

38
Senior#swift#Runtime Internals

Method Dispatch in Swift: Static vs Table vs Message Dispatch.

How the CPU resolves which function implementation to execute: Static / Direct Dispatch (Fastest): Resolved at compile time • Table Dispatch (V-Table & Witness Table): Looked up via function pointer arrays at runtime • Message Dispatch (Most Dynamic / Slowest): Uses Objective-C runtime (objc_msgSend).

39
Senior#swift#Runtime Internals

ARC Memory Management: Strong, Weak, Unowned, and resolving Retain Cycles.

Automatic Reference Counting (ARC) automatically tracks and manages memory: Strong Reference: Increments retain count • Weak Reference: Does not increment retain count • Unowned Reference: Does not increment retain count.

40
Senior#swift#Runtime Internals

Copy-on-Write (CoW) in Custom Value Types: Implementing CoW using `isKnownUniquelyReferenced()`.

Standard Swift collections (Array, Dictionary, String) are value types that copy cheaply: When you assign b = a, memory is not duplicated immediately; both variables point to the exact same underlying buffer • Memory is copied only when one variable attempts a write (Copy-on-Write) • Custom CoW Implementation.

41
Senior#swift#Runtime Internals

Existential Any vs Opaque Some Types (`any Protocol` vs `some Protocol`).

Opaque Types (some View / some Protocol) • Represents a specific, fixed concrete type chosen by the implementation, hidden from the caller • Zero performance overhead (static dispatch) • Existential Types (any Protocol).

42
SeniorCode#swift#Runtime Internals

Property Wrappers (`@propertyWrapper`): Wrapped value, projected value, and composition.

Adds reusable management logic to property read/write access.

43
Senior#swift#Runtime Internals

Result Builders (`@resultBuilder`): How SwiftUI declarative body DSL is compiled.

Result builders allow writing declarative list-like syntax without commas or return statements (e.g. SwiftUI VStack { Text("A"); Text("B") }): The compiler rewrites the block into static calls on the builder type • buildBlock( parts: Component...) • buildEither(first:) and buildEither(second:) for if/else statements.

44
SeniorCode#swift#Runtime Internals

KeyPaths in Swift: Type-safe property referencing and functional composition.

KeyPaths allow referencing properties as first-class un-invoked values.

45
Senior#swift#Runtime Internals

Concurrency: Actors vs Global Actors (`@MainActor`) and Actor Reentrancy hazards.

Actors: Reference types that protect internal mutable state by synchronizing access through a private serial mailbox queue • @MainActor: A global actor that guarantees code executes strictly on the primary UI thread (crucial for view updates).

46
SeniorCode#swift#Runtime Internals

Error Handling: `Result`, typed throws in Swift 6 (`throws(MyError)`), and `rethrows`.

Untyped Throws (Classic Swift): func fetch() throws erases error types to any Error • Typed Throws (Swift 6).

47
Senior#swift#Runtime Internals

C and C++ Interoperability: Direct C++20 standard library calls and Objective-C bridging.

Swift 5.9+ supports bidirectional, zero-overhead C++ interop: Include C++ headers directly into Swift modules via module.modulemap • Swift can directly instantiate C++ classes, invoke methods, and pass std::string and std::vector without writing Objective-C++ (.mm) wrapper shims.

48
Senior#swift#Runtime Internals

Unsafe Swift: `UnsafePointer`, `UnsafeMutableRawPointer`, and memory alignment.

Direct manual memory manipulation for high-frequency low-level algorithms: UnsafePointerT: Equivalent to C const T • UnsafeMutablePointerT: Equivalent to C T • UnsafeMutableRawPointer: Equivalent to C void* (untyped byte buffer).

49
SeniorCode#swift#Runtime Internals

Custom String Interpolation and `ExpressibleByLiteral` protocols.

ExpressibleByStringLiteral / ExpressibleByIntegerLiteral: Allows custom types to be initialized directly from literals (let id: UserID = 1042) • Custom String Interpolation: Extend String.StringInterpolation to create secure, type-safe formatters.

50
Senior#swift#Runtime Internals

Swift Package Manager (SPM): Binary targets, plugins, and dependency resolution.

SPM is Apple's native dependency manager integrated into Xcode: Binary Targets (.xcframework): Distributes closed-source, pre-compiled multi-architecture libraries supporting iOS devices, Simulators, and Mac.