🦅

Swift MCQ

Test your Swift knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.

100 Questions 40 Beginner 40 Intermediate 20 Advanced

How This Practice Test Works

Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

1

Which company created the Swift programming language?

C

Correct Answer

Apple

Explanation

Apple introduced Swift at WWDC 2014 as a replacement for Objective-C for iOS, macOS, and other Apple platform development.

2

How do you declare an immutable constant in Swift?

D

Correct Answer

let name = "Alice"

Explanation

let declares an immutable constant; var declares a mutable variable. Prefer let unless mutation is needed.

3

What is an optional in Swift?

B

Correct Answer

A type that can hold either a value or nil

Explanation

Optional<T> (shorthand T?) represents a value that may or may not exist. Must be unwrapped to access the value.

4

What does if let do in Swift?

B

Correct Answer

Optional binding — unwraps an optional and binds its value to a constant if non-nil

Explanation

if let name = optName { use name } safely unwraps optName, executing the block only if it is non-nil.

5

What is a struct in Swift?

B

Correct Answer

A value type stored on the stack that is copied on assignment

Explanation

Structs are value types in Swift — assignment and function passing copies the entire struct. Most standard library types (Array, String, Int) are structs.

6

What is the difference between struct and class in Swift?

B

Correct Answer

Classes are reference types; structs are value types

Explanation

Classes are reference types (heap, shared identity). Structs are value types (copied). Classes support inheritance; structs don't.

7

What is a protocol in Swift?

B

Correct Answer

A blueprint of methods, properties, and requirements that types can adopt

Explanation

Protocols define contracts like Java interfaces. Classes, structs, and enums can all conform to protocols.

8

What does guard let do?

B

Correct Answer

Unwraps an optional and exits the current scope with return/break/throw if nil

Explanation

guard let x = optX else { return } unwraps optX and makes x available in the rest of the function. It reduces nesting vs if-let chains.

9

What is the nil-coalescing operator ?? in Swift?

B

Correct Answer

Returns the wrapped optional value if non-nil; otherwise returns the right-hand default

Explanation

let name = optName ?? "Anonymous" returns optName's value if not nil, otherwise "Anonymous".

10

What is an enum in Swift?

B

Correct Answer

A value type defining a group of related values, supporting associated values and methods

Explanation

Swift enums are first-class types that can have associated values, raw values, computed properties, and methods.

11

What is an associated value in a Swift enum?

B

Correct Answer

Additional data attached to an enum case: case .success(Int) or case .failure(Error)

Explanation

enum Result { case success(Int); case failure(Error) } stores specific data per case. Switch over it with case .success(let n): to extract the value.

12

What is string interpolation in Swift?

B

Correct Answer

Embedding expressions in a string literal using \(expression)

Explanation

"Hello, \(name)!" embeds the value of name into the string literal.

13

What does the mutating keyword mean on a struct method?

B

Correct Answer

The method is allowed to modify the struct's stored properties

Explanation

Structs are value types, so by default methods cannot modify self. mutating func allows property changes inside the method.

14

What is a closure in Swift?

B

Correct Answer

A self-contained block of code that captures values from its surrounding context

Explanation

Closures in Swift are similar to lambdas. { (x: Int) -> Int in return x * 2 } can be shortened to { x in x * 2 } or even { $0 * 2 }.

15

What is the @escaping attribute on a closure parameter?

B

Correct Answer

Indicates the closure may outlive the function call (e.g., stored for async use)

Explanation

Without @escaping, a closure must be used synchronously. @escaping allows the closure to be stored or called asynchronously after the function returns.

16

What does the defer statement do?

B

Correct Answer

Executes code when the current scope exits, regardless of how it exits

Explanation

defer { cleanup() } ensures cleanup() runs when the function exits — even via return, throw, or error. Useful for resource cleanup.

17

What is a computed property?

B

Correct Answer

A property with get (and optionally set) accessors that compute a value rather than storing it

Explanation

var area: Double { get { return width * height } } computes area dynamically each time it's accessed.

18

What does lazy mean on a stored property?

B

Correct Answer

The property's initial value is not computed until it is first accessed

Explanation

lazy var expensiveResource = HeavyObject() defers initialization until first use. Must be var; let cannot be lazy.

19

What is Swift's Result type?

B

Correct Answer

An enum with .success(Value) and .failure(Error) cases for representing success or failure

Explanation

Result<T, E: Error> is a Swift standard type for functions that can succeed or fail without throwing.

20

What is the strong reference cycle in Swift?

B

Correct Answer

Two or more class instances holding strong references to each other, preventing ARC from deallocating them

Explanation

If A holds a strong reference to B and B holds a strong reference to A, neither is deallocated. Break cycles with weak or unowned references.

21

What is a weak reference?

B

Correct Answer

A reference that does not prevent the object from being deallocated by ARC; automatically becomes nil when the object is freed

Explanation

weak var delegate: MyDelegate? doesn't increase the retain count. When the object deallocates, the weak reference becomes nil.

22

What is an unowned reference?

B

Correct Answer

A non-optional reference that does not retain the object; assumes the object always exists when accessed (crashes if nil)

Explanation

unowned let customer: Customer assumes customer outlives the dependent object. Use when the referenced object always has a longer lifetime. Accessing a deallocated unowned reference crashes.

23

What is ARC in Swift?

B

Correct Answer

Automatic Reference Counting — Swift's memory management system that tracks and manages class instance lifetimes

Explanation

ARC automatically deallocates class instances when their reference count drops to zero. Structs and enums are value types and do not use ARC.

24

What is Swift's access control default?

C

Correct Answer

internal

Explanation

Declarations in Swift default to internal access — accessible within the same module but not outside. open is the most permissive (subclassable from other modules).

25

What does the throws keyword signify on a function?

B

Correct Answer

The function can throw errors that the caller must handle with do-catch or propagate with try

Explanation

func parse() throws must be called with try: let result = try parse(). Errors propagate or are caught with do { try } catch { }.

26

What does try? do in Swift?

B

Correct Answer

Calls a throwing function and returns an optional — nil if an error is thrown

Explanation

let val = try? parse() returns Optional<T>. If parsing succeeds, val wraps the result; if it throws, val is nil.

27

What is a generic in Swift?

B

Correct Answer

Code that works with any type, specified with type parameter <T>

Explanation

func swap<T>(_ a: inout T, _ b: inout T) works for any type T. Generics provide type safety without code duplication.

28

What are where clauses in Swift generics?

B

Correct Answer

Constraints on generic type parameters: func f<T: Comparable>() where T: Hashable

Explanation

where clauses add extra type constraints. extension Array where Element: Equatable adds methods only when Element conforms to Equatable.

29

What is the difference between Array and ContiguousArray in Swift?

B

Correct Answer

ContiguousArray always stores elements in a contiguous memory block; Array may bridge to NSArray for class types

Explanation

For performance-critical code with class or protocol types, ContiguousArray avoids NSArray bridging overhead by guaranteeing contiguous storage.

30

What is a property observer in Swift?

B

Correct Answer

willSet and didSet blocks that run before and after a property value changes

Explanation

var score: Int = 0 { willSet { print("About to set \(newValue)") } didSet { print("Set from \(oldValue)") } }

31

What is a typealias in Swift?

B

Correct Answer

An alternative name for an existing type

Explanation

typealias Completion = (Result<Data, Error>) -> Void creates a readable alias for a complex closure type.

32

What is the inout parameter keyword?

B

Correct Answer

Allows a function to modify the caller's variable by passing it by reference with &

Explanation

func increment(_ n: inout Int) { n += 1 }; increment(&count) modifies count in place.

33

What does the @discardableResult attribute do?

B

Correct Answer

Silences the compiler warning when the return value is not used

Explanation

@discardableResult on a function prevents the "result of call is unused" warning when callers choose not to use the return value.

34

What is Swift's switch statement requirement?

B

Correct Answer

Every switch must be exhaustive — it must cover all possible values or have a default

Explanation

Swift switch must be exhaustive. When switching over an enum, each case must be handled. No implicit fall-through (use fallthrough explicitly if needed).

35

What is a tuple in Swift?

B

Correct Answer

A group of multiple values combined into a single compound value

Explanation

let point = (x: 3, y: 4) groups values. Access with point.x or let (x, y) = point. Good for simple return values without defining a full struct.

36

What is a trailing closure syntax?

B

Correct Answer

A syntax allowing a closure argument to be written after the function call parentheses

Explanation

array.sort() { $0 < $1 } or array.sort { $0 < $1 } are trailing closure forms of sort(by:). Improves readability for long closures.

37

What does the some keyword do (opaque type)?

B

Correct Answer

Declares an opaque return type — the function returns a specific but unnamed conforming type

Explanation

var body: some View in SwiftUI returns a specific concrete type that conforms to View, without revealing the exact type to callers.

38

What is the any keyword in Swift 5.7 (existential type)?

B

Correct Answer

Explicitly marks an existential type: var p: any Drawable — a box that holds any value conforming to Drawable

Explanation

Swift 5.7 requires any to signal existential types (var shape: any Shape), distinguishing them from concrete types and opaque types (some Shape).

39

What is higher-order function map in Swift?

B

Correct Answer

Applies a transformation to each element in a collection and returns a new array

Explanation

[1, 2, 3].map { $0 * 2 } returns [2, 4, 6]. map, filter, reduce, and flatMap are core Swift collection functions.

40

What does @propertyWrapper do?

B

Correct Answer

Defines a reusable wrapper type that adds behavior to stored properties via the wrappedValue contract

Explanation

@propertyWrapper struct Clamped<T> { ... } allows @Clamped(0...100) var progress: Int. SwiftUI uses @State, @Binding, @Published as property wrappers.

1

What is Swift's async/await and how does it compare to completion handlers?

B

Correct Answer

async/await provides structured concurrency with linear readable code; completion handlers nest and complicate error handling

Explanation

async/await (Swift 5.5) replaces nested completion handlers with sequential-looking code that suspends at await points without blocking the thread.

2

What is a Swift actor?

B

Correct Answer

A reference type that protects its mutable state by serializing access, preventing data races

Explanation

actor BankAccount { var balance: Int } serializes access to balance. External code must await to access actor-isolated state.

3

What is the @MainActor attribute?

B

Correct Answer

Ensures that a type or function is accessed on the main thread, preventing UI mutations from background threads

Explanation

@MainActor class ViewModel { } or @MainActor func updateUI() guarantees execution on the main actor, crucial for UI updates.

4

What is a TaskGroup in Swift concurrency?

B

Correct Answer

A structured group of concurrent child tasks that can add tasks dynamically and collect results

Explanation

withTaskGroup(of: Int.self) { group in group.addTask { await fetchValue() } } manages concurrent tasks with structured lifetimes.

5

What is protocol-oriented programming in Swift?

B

Correct Answer

Modeling systems primarily through protocols and protocol extensions rather than class hierarchies

Explanation

POP (Apple's WWDC 2015 talk) favors protocol extensions for shared behavior over class inheritance, enabling composition and working with value types.

6

What is a protocol extension in Swift?

B

Correct Answer

Adding default implementations to protocol methods, which any conforming type gets for free

Explanation

extension Collection where Element: Equatable { func unique() -> [Element] { ... } } provides default methods to all conforming Collection types.

7

What are associated types in a protocol?

B

Correct Answer

Placeholder type names in protocols that conforming types resolve

Explanation

protocol Container { associatedtype Element; func append(_ item: Element) } — conforming types define what Element is.

8

What is the difference between value types and reference types regarding mutation?

B

Correct Answer

Mutating a value type creates a copy; mutating a reference type affects all references to the same object

Explanation

With value types (struct/enum), each copy is independent. With reference types (class), all variables pointing to the same object see the mutation.

9

What is @autoclosure?

B

Correct Answer

Automatically wraps an argument expression in a closure, enabling lazy evaluation

Explanation

func assert(_ cond: @autoclosure () -> Bool) { if !cond() { ... } } allows calling assert(x > 0) without the caller explicitly wrapping in {}.

10

What is the Sendable protocol?

B

Correct Answer

A marker protocol indicating a type is safe to share across concurrency domains (actors and tasks)

Explanation

Sendable types can be safely transferred across actor boundaries. Value types with Sendable properties are implicitly Sendable. The compiler enforces this.

11

What is copy-on-write (COW) in Swift?

B

Correct Answer

An optimization where value types (like Array) share storage until a mutation occurs, at which point a unique copy is made

Explanation

var b = a; b.append(1) — only when b is actually mutated does Swift create a new storage copy. This makes large-array assignment cheap.

12

What is the Hashable protocol?

B

Correct Answer

A protocol requiring a hash(into:) method so values can be used as Set members or Dictionary keys

Explanation

Types conforming to Hashable (which implies Equatable) can be stored in Set and used as Dictionary keys. Structs synthesize conformance if all stored properties are Hashable.

13

What is Codable in Swift?

B

Correct Answer

A type alias for Encodable & Decodable, enabling automatic JSON/Plist serialization and deserialization

Explanation

struct User: Codable { var name: String; var age: Int } can be encoded to JSON with JSONEncoder and decoded with JSONDecoder automatically.

14

What is dynamic dispatch vs static dispatch in Swift?

B

Correct Answer

Static dispatch resolves method calls at compile time (final/struct); dynamic dispatch uses vtable or witness table at runtime (class, protocol)

Explanation

Static dispatch enables inlining and is faster. Mark classes final for static dispatch. Protocol methods use witness tables (dynamic). Classes use vtables.

15

What is the @objc attribute used for?

B

Correct Answer

Exposes Swift declarations to Objective-C runtime, enabling use with Objective-C APIs, selectors, and dynamic dispatch

Explanation

@objc func handleTap(_ sender: UIButton) makes the method callable as a selector. Required for target-action, KVO, and Objective-C delegation.

16

What is a subscription type conformance (@dynamicMemberLookup)?

B

Correct Answer

An attribute allowing arbitrary member names to be resolved at compile time via subscript(dynamicMember:)

Explanation

@dynamicMemberLookup enables point.x syntax for types that implement subscript(dynamicMember key: String). Used by Swift for Python/JSON DSLs.

17

What is the difference between throwing and returning Result?

B

Correct Answer

Throwing is for synchronous error propagation; Result is useful when storing or passing errors as values, especially in async contexts

Explanation

do-try-catch works well for synchronous code. Result<T, E> is useful when the outcome needs to be stored, passed in closures, or the caller controls when to handle it.

18

What does the @Published property wrapper do (Combine)?

B

Correct Answer

Emits a publisher event whenever the property value changes, useful in ObservableObject classes

Explanation

@Published var name = "" in an ObservableObject class sends a Combine publisher event on each change. SwiftUI subscribes and re-renders views.

19

What is a KeyPath in Swift?

B

Correct Answer

A type-safe reference to a property or subscript of a type, enabling first-class property access

Explanation

\User.name creates a KeyPath<User, String>. Use with users.map(\User.name) or keyPath syntax in Combine/SwiftUI binding.

20

What is SwiftUI's @State property wrapper?

B

Correct Answer

Declares a source of truth for a view's private mutable state; changes trigger view re-renders

Explanation

@State var count = 0 stores state owned by the view. When count changes, SwiftUI re-renders the view. Pass to children with @Binding.

21

What is SwiftUI's @Binding?

B

Correct Answer

A two-way connection to state owned by a parent, allowing a child view to read and modify the parent's state

Explanation

@Binding var isOn: Bool in a child view connects to $isOn from the parent's @State. Changes in the child propagate back to the parent.

22

What is SwiftUI's @ObservedObject?

B

Correct Answer

A property wrapper for a reference to an ObservableObject; the view re-renders when the object's @Published properties change

Explanation

@ObservedObject var viewModel: MyViewModel causes re-renders when viewModel's @Published properties change. The view does not own the object.

23

What is the difference between @ObservedObject and @StateObject?

B

Correct Answer

@StateObject creates and owns the object, preserving it across re-renders; @ObservedObject receives it from outside and may be recreated

Explanation

Use @StateObject when a view creates its own view model. Use @ObservedObject when a parent passes the view model in. @StateObject survives parent re-renders.

24

What is Swift's Combine framework?

B

Correct Answer

A reactive programming framework using Publishers, Subscribers, and Operators for event-driven async code

Explanation

Combine provides Just, Future, PassthroughSubject, and operators like map, filter, flatMap, debounce for reactive pipelines.

25

What is the difference between publisher and subject in Combine?

B

Correct Answer

Publishers emit values over time; Subjects (PassthroughSubject, CurrentValueSubject) are publishers that can be imperatively sent values

Explanation

PassthroughSubject<Int, Never> lets you call send(5) to emit values imperatively. Used to bridge non-Combine code into Combine pipelines.

26

What is Swift Concurrency's withCheckedThrowingContinuation?

B

Correct Answer

A bridge converting callback-based APIs into async/await by manually calling continuation.resume(returning:) or continuation.resume(throwing:)

Explanation

let data = try await withCheckedThrowingContinuation { cont in oldAPI { result in cont.resume(returning: result) } } converts callbacks to async.

27

What is a Swift associated type with a default?

B

Correct Answer

An associated type with a default concrete type: associatedtype Element = Int, used when a conforming type doesn't specify it

Explanation

protocol Sequence { associatedtype Element } — if conforming type doesn't specify Element, the default applies. Reduces conformance boilerplate for common cases.

28

What is Swift's existential container layout?

B

Correct Answer

A 5-word heap allocation for any type conforming to a protocol: value buffer + type metadata + protocol witness tables

Explanation

var drawable: any Drawable stores up to 3 words inline; larger values heap-allocate. Plus 1 word for type metadata and 1 for the witness table. This overhead justifies preferring generics.

29

What is @discardableResult when used on property accessors?

B

Correct Answer

Silences the "result of call unused" warning when a method or property access result is not used

Explanation

@discardableResult on functions returning Self (for chaining) lets callers chain without needing the return value, avoiding warnings.

30

What are conditional conformances in Swift?

B

Correct Answer

A conformance that applies only when type constraints are met: extension Array: Equatable where Element: Equatable

Explanation

extension Optional: Equatable where Wrapped: Equatable means Optional<Int> is Equatable but Optional<UIView> is not. Powerful for composable conformances.

31

What is the @dynamicCallable attribute?

B

Correct Answer

Allows a type to be called like a function by implementing dynamicallyCall(withArguments:) or withKeywordArguments:

Explanation

@dynamicCallable struct PythonObject { func dynamicallyCall(withKeywordArguments: [String: Any]) -> PythonObject } enables obj(x: 1, y: 2) call syntax.

32

What is Swift's withUnsafeMutablePointer?

B

Correct Answer

Temporarily obtains a mutable raw pointer to a value for low-level or C-interop operations

Explanation

withUnsafeMutablePointer(to: &value) { ptr in ptr.pointee = 42 } — the pointer is only valid within the closure and must not escape.

33

What is Swift's AttributedString?

B

Correct Answer

A Swift-native, type-safe attributed string supporting interpolation and custom attributes for rich text in SwiftUI and AppKit/UIKit

Explanation

var str: AttributedString = "Hello"; str.font = .bold enables type-safe attribute access. Unlike NSAttributedString, attributes are accessed as typed properties.

34

What is the Swift AsyncStream?

B

Correct Answer

A way to bridge callback or delegate-based APIs into Swift async sequences using a closure-based builder

Explanation

let stream = AsyncStream<Int> { cont in timer.onTick { value in cont.yield(value) } } bridges timer callbacks into for await loops.

35

What is Swift's MainActor isolation checking?

B

Correct Answer

A compile-time check ensuring @MainActor-isolated properties are only accessed on the main thread, flagging unsafe cross-actor calls

Explanation

The compiler flags non-isolated async calls to @MainActor properties, requiring await actor.property. This prevents data races at compile time.

36

What is a Swift package plugin?

B

Correct Answer

A Swift Package that provides custom build tools or commands that run during the build phase, like code generators or linters

Explanation

Swift package plugins (SPM 5.6+) run during build (CommandPlugin, BuildToolPlugin). Used for source code generation, protobuf compilation, and other pre-build tasks.

37

What is the purpose of Swift's nonisolated keyword?

B

Correct Answer

Opts a method out of actor isolation, allowing it to be called from any context without await

Explanation

nonisolated func computeHash() on an actor can be called synchronously from any context, since it only accesses non-isolated (Sendable) data.

38

What is Swift's TaskLocal?

B

Correct Answer

A property wrapper for values implicitly propagated through the structured concurrency tree, providing task-scoped storage

Explanation

@TaskLocal static var requestId: String = ""; TaskLocal.$requestId.withValue("req-1") { await handler() } propagates requestId through all child tasks.

39

What is Swift's Clock protocol (Swift 5.7)?

B

Correct Answer

A protocol abstracting time measurement for async code, enabling test-controllable time in functions using sleep(for:) or sleep(until:)

Explanation

func retry<C: Clock>(clock: C) { await clock.sleep(for: .seconds(1)) } accepts a TestClock in tests to advance time without actual waits.

40

What is Swift's withCheckedContinuation for bridging synchronous callbacks?

B

Correct Answer

A non-throwing version of withCheckedThrowingContinuation for bridging non-throwing callbacks into async/await

Explanation

let value = await withCheckedContinuation { continuation in nonThrowingCallback { result in continuation.resume(returning: result) } }

1

What is structured concurrency in Swift 5.5+?

B

Correct Answer

A concurrency model where tasks have lifetimes scoped to parent tasks, preventing leaks and ensuring cancellation propagates

Explanation

Swift structured concurrency (async let, TaskGroup) guarantees all child tasks complete before the parent exits, making cancellation, error propagation, and cleanup deterministic.

2

What is the Swift type system's existential type erasure limitation?

B

Correct Answer

Protocols with associated types or Self requirements cannot be used as existential types without boxing them in AnyX wrappers or using any keyword

Explanation

var shapes: [any Shape] requires Swift 5.7. Pre-5.7, PATs (protocols with associated types) required type erasure wrappers like AnyCollection.

3

How does Swift implement generics specialization?

B

Correct Answer

The Swift compiler can specialize generic functions for specific concrete types at compile time, emitting dedicated copies for performance

Explanation

When the concrete type is known at compile time, Swift may emit a specialized copy of a generic function with inlined type information, avoiding the overhead of existential boxing.

4

What is the Swift runtime's metadata system?

B

Correct Answer

Compile-time-generated type metadata (type descriptors, witness tables, value witnesses) enabling generic code, protocol conformances, and reflection

Explanation

Swift metadata includes type descriptors and protocol witness tables. Generic code uses metadata to perform operations on unknown types (copy, destroy, cast).

5

What are result builders in Swift?

B

Correct Answer

A DSL mechanism using @resultBuilder to transform block syntax into method calls, underpinning SwiftUI's ViewBuilder

Explanation

@resultBuilder struct ViewBuilder transforms multiple child view expressions into a single TupleView. Used for HTML, SQL, and any embedded DSL.

6

What is the Swift concurrency model's cooperative thread pool?

B

Correct Answer

A fixed-size thread pool matching CPU cores where async tasks yield cooperatively at suspension points, enabling efficient parallelism

Explanation

Swift's actor runtime uses a cooperative thread pool (default: number of CPUs). Tasks yield at await points rather than blocking threads, maximizing throughput.

7

What is the ~Copyable protocol and noncopyable types in Swift?

B

Correct Answer

Types that suppress the implicit Copyable conformance, enabling move-only semantics where ownership must be explicitly transferred

Explanation

struct FileHandle: ~Copyable disables copying. The value must be moved or consumed. Enables RAII patterns and unique-ownership types at the language level.

8

What is the difference between opaque (some) and existential (any) types?

B

Correct Answer

some is a compile-time single specific type (statically resolved); any is a runtime-boxed type (dynamically dispatched)

Explanation

some View has static type identity — the compiler knows the exact type. any View boxes any conforming type at runtime with dynamic dispatch overhead.

9

What is macro expansion in Swift 5.9?

B

Correct Answer

A type-safe code generation mechanism where #macroName expands to Swift code at compile time based on Syntax tree analysis

Explanation

Swift 5.9 macros (declaration, expression, accessor) use SwiftSyntax to generate boilerplate at compile time. #Preview and @Observable use this mechanism.

10

What is the Swift Observation framework (@Observable)?

B

Correct Answer

A macro-based observation system in Swift 5.9 that tracks property accesses and triggers UI updates without boilerplate @Published declarations

Explanation

@Observable (Swift 5.9 / iOS 17) uses macros to instrument property access. SwiftUI views automatically track which properties they access and re-render on changes.

11

What is Swift's witness table and how does it relate to protocol performance?

B

Correct Answer

A per-conformance table of function pointers for each protocol requirement, consulted at runtime for existential dispatch (dynamic dispatch)

Explanation

Protocol witness tables (PWTs) enable dynamic dispatch for existential types (any P). Generic code with where constraints avoids PWTs via static dispatch.

12

What is the Swift compiler's whole-module optimization (WMO)?

B

Correct Answer

A compilation mode analyzing all module files together, enabling cross-file inlining, devirtualization, and dead code elimination

Explanation

WMO (-whole-module-optimization) compiles all Swift files as one unit. The compiler can inline across file boundaries and remove unused generics, improving performance significantly.

13

What is Swift's memory layout and how does Unsafe APIs expose it?

B

Correct Answer

MemoryLayout<T>.size/stride/alignment expose the exact byte layout. Unsafe APIs (UnsafePointer) allow direct memory manipulation matching C layouts

Explanation

MemoryLayout<Int>.size = 8 on 64-bit. MemoryLayout<(Int, Bool)>.stride = 16 (padding). Needed for C struct interop and performance analysis.

14

What is the Sendable checking and actor-isolated closure interaction?

B

Correct Answer

A @Sendable closure cannot capture non-Sendable actor-isolated state; the compiler prevents data races by ensuring closures only cross actor boundaries with Sendable data

Explanation

Task { @Sendable in nonSendableCapture } fails. The compiler requires that values crossing actor/task boundaries are Sendable to prevent data races.

15

What is Swift's _modify accessor?

B

Correct Answer

A coroutine-based accessor yielding a mutable reference to a property value, enabling in-place mutation without get/set copies

Explanation

_modify is part of Swift's coroutine-based accessor model. It yields an inout reference, enabling operations like array[0] += 1 to work in-place without copying.

16

What is Swift's Unmanaged<T> type?

B

Correct Answer

A wrapper for manually managing ARC reference counts, used in Core Foundation interop where retain/release must be explicit

Explanation

Unmanaged<CFString>.passRetained(str).toOpaque() passes a retained CF object. takeRetainedValue() / takeUnretainedValue() control whether ARC gets ownership.

17

What is Swift's type metadata and how does it enable generics?

B

Correct Answer

Compile-time-generated structures containing type size, alignment, and protocol conformance pointers, passed implicitly to generic functions

Explanation

Generic functions receive implicit metadata parameters for each type parameter. The runtime uses metadata for copy, destroy, and protocol conformance operations on unknown types.

18

What is Swift's opaque type and its interaction with primary associated types?

B

Correct Answer

some Collection<Int> constrains the opaque type's Element, enabling cleaner API than full generic constraints while hiding the concrete type

Explanation

func getNumbers() -> some Collection<Int> says "returns a specific Collection with Int elements" without revealing the concrete type (Array, Set, etc.).

19

What is the Swift actor reentrancy problem?

B

Correct Answer

Between await suspension points, another call may mutate actor state, making cached state before the await stale when execution resumes

Explanation

let balance = account.balance; await transfer(); // balance may be stale here! Between the await, another Task may have changed balance. Re-read state after every suspension.

20

What is the difference between Task and TaskGroup in structured concurrency?

B

Correct Answer

Task creates a single async work unit; TaskGroup creates a dynamic set of concurrent child tasks with structured lifetimes and result collection

Explanation

withTaskGroup(of: T.self) { group in group.addTask { work1() }; group.addTask { work2() }; for try await result in group { collect(result) } } manages dynamic concurrency.