Back to interview questions

100+ Swift Interview Questions and Answers

100+ Swift Interview Questions and Answers

Explore 120 Swift interview questions and answers on optionals, protocols, memory management, concurrency, API design and practical debugging.

Explore 120 Swift interview questions and answers on optionals, protocols, memory management, concurrency, API design and practical debugging.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Hiring a Swift developer calls for more than recognizing syntax or naming iOS frameworks. A candidate should be able to explain what a value means, who owns an object and which work can continue after an asynchronous suspension. Small code walkthroughs reveal whether the candidate can predict behavior and turn that understanding into maintainable application code.

This guide to 100+ Swift Interview Questions and Answers contains 120 questions across beginner, intermediate and experienced levels. It covers the language, value and reference semantics, protocols, memory management, error handling and concurrency. The emphasis is Swift reasoning that applies across supported platforms, with compiler version, language mode and isolation settings identified when they affect behavior.

How can recruiters assess Swift expertise when a candidate gives a confident answer but cannot explain the code’s lifetime or output?

Ask the candidate to trace a short program, change an assumption and explain what should happen next. A useful follow-up might replace a value with a reference, suspend an actor method or cancel a task. Strong candidates identify the relevant ownership or isolation boundary, describe the failure mode and propose a focused test rather than relying on a memorized rule.

Sherlock AI helps hiring teams assess signals of potential AI cheating, deepfakes, impersonation and unauthorized assistance during remote interviews. Combine those signals with code walkthroughs, debugging discussions and consistent follow-up questions. They support human review and should not be treated as conclusive proof of misconduct.

Swift Interview Questions

Choose foundational questions first, then add ownership, API design and concurrency scenarios that reflect the role. Every question has a matching numbered answer below.

Swift Interview Questions for Beginners

Establish types, optionals, control flow and basic data modeling.

  1. What is the difference between let and var in Swift?

  2. How does Swift type inference work?

  3. Why does Swift require explicit numeric conversions?

  4. How do String and Character differ?

  5. Why can’t you normally index a Swift String with an integer?

  6. What is an optional in Swift?

  7. How does if let unwrap an optional?

  8. When would you choose guard let instead of if let?

  9. What does the nil-coalescing operator do?

  10. What is optional chaining?

  11. Why can force unwrapping crash a program?

  12. How do if conditions differ from truthy checks in some languages?

  13. What makes Swift switch statements useful?

  14. How do closed and half-open ranges differ?

  15. When should you use for-in, while and repeat-while?

  16. How do break and continue affect a loop?

  17. When would you choose Array, Set or Dictionary?

  18. How do you access array elements safely?

  19. Why does a dictionary lookup return an optional?

  20. What does value semantics mean for Swift collections?

  21. How do map and filter differ?

  22. When is compactMap useful?

  23. What do argument labels contribute to a function call?

  24. How do return values differ from printing inside a function?

  25. How can a tuple return multiple related values?

  26. What are default parameter values useful for?

  27. What does an inout parameter mean?

  28. What is a closure in Swift?

  29. What is trailing-closure syntax?

  30. What does a closure capture from its surrounding scope?

  31. How do structs and classes differ at a basic level?

  32. How can two constants refer to the same mutable class instance?

  33. What is the difference between a stored and computed property?

  34. Why do some struct methods need mutating?

  35. What is the purpose of an initializer?

  36. How does an enum model a finite set of states?

  37. How do associated values differ from enum raw values?

  38. What is a protocol used for?

  39. When should a function throw an error rather than return an optional?

  40. How do try, try? and try! differ?

Swift Interview Questions for Intermediate

Explore ownership, generic APIs, errors and concurrency mechanisms.

  1. How does ARC determine when a class instance can be released?

  2. When should a relationship use weak instead of strong?

  3. How does unowned differ from weak?

  4. How can a stored closure create a strong reference cycle?

  5. What does a capture list change for a value variable?

  6. Why can strengthening weak self change the lifetime of an asynchronous operation?

  7. What should you know about ArraySlice storage and indices?

  8. Does a struct containing a class reference provide a deep copy?

  9. What must be considered when implementing custom copy-on-write storage?

  10. When is a generic parameter better than an existential protocol value?

  11. What does an associated type express in a protocol?

  12. How does a same-type constraint improve a generic API?

  13. What does some Protocol mean as a return type?

  14. How is some Protocol as a parameter different from an opaque return?

  15. What does any Protocol allow you to store?

  16. How do protocol requirements differ from extension-only methods?

  17. What can an extension add, and what can it not add?

  18. How do access control and setter visibility support invariants?

  19. How do public and open differ for classes?

  20. What does a property wrapper encapsulate?

  21. How do throws and Result represent failure differently?

  22. How should catch patterns and error translation be designed?

  23. What does typed throws add in modern Swift?

  24. How does defer help with cleanup?

  25. When is reduce(into:) useful for building an accumulated result?

  26. When can lazy collection transformations help?

  27. What performance assumptions should you make about Array operations?

  28. What must Hashable implementations preserve?

  29. How does Unicode canonical equivalence affect String equality?

  30. Does async mean a function runs on a background thread?

  31. What does await tell the reader?

  32. How does async let express structured concurrency?

  33. When should you use a task group?

  34. How does Task differ from a structured child task?

  35. When is Task.detached appropriate?

  36. How does cooperative cancellation work?

  37. What protection does an actor provide?

  38. Why are actors reentrant across suspension points?

  39. What does Sendable communicate?

  40. How do Swift 6 language mode and default actor isolation affect concurrency code?

Swift Interview Questions for Experienced

Assess diagnosis, API boundaries and safe evolution of concurrent systems.

  1. How would you diagnose an actor that produces stale results without a data race?

  2. How would you choose buffering for a callback-backed AsyncStream?

  3. How would you prevent duplicate asynchronous work in an actor cache?

  4. How would you diagnose cancellation that appears ineffective?

  5. How would you decide who owns an asynchronous task’s lifetime?

  6. Why can a task-group timeout return later than its deadline?

  7. How would you diagnose UI hangs in code marked async?

  8. How would you introduce bounded concurrency?

  9. How would you wrap a callback API with a continuation safely?

  10. How would you migrate a large project toward Swift 6 concurrency checking?

  11. How should default actor isolation affect a Swift migration plan?

  12. When is @unchecked Sendable an appropriate choice?

  13. How would you design an API that transfers data between isolation domains?

  14. How would you handle a protocol whose isolation requirements do not fit its implementation?

  15. How would you diagnose a task that keeps an object alive unexpectedly?

  16. How would you diagnose surprising retention in nested closures?

  17. How would you distinguish a memory leak from legitimate retention?

  18. How would you diagnose unexpectedly expensive mutations of a collection?

  19. How would you keep Hashable identity stable in a mutable domain model?

  20. How would you evolve a Codable model without breaking persisted data?

  21. How would you respond to an exclusivity violation?

  22. How would you optimize Swift code without weakening correctness?

  23. When would noncopyable types improve an API design?

  24. How would you review unsafe-pointer code at a C boundary?

  25. How would you design an autoclosure API without hiding important work?

  26. How would you design partial-failure semantics for a batch API?

  27. How would you make a retrying asynchronous API safe?

  28. How would you test actor reentrancy deterministically?

  29. How would you test cancellation and cleanup?

  30. How would you keep asynchronous tests from becoming flaky?

  31. How would you assess protocol-conformance evolution and retroactive conflicts?

  32. How would you review a public API for future evolution?

  33. When would you enable library evolution support?

  34. What risk does @inlinable introduce in a library?

  35. How would you evolve an enum used by external clients?

  36. How would you manage Swift package dependency upgrades?

  37. How would you handle Objective-C interoperability without losing Swift safety?

  38. How would you review AI-generated Swift code?

  39. What should a concurrency-focused Swift code review examine?

  40. What demonstrates senior Swift judgment?

Swift Interview Questions and Answers

Trace the concrete values and lifetimes before choosing an abstraction. For concurrency, distinguish the compiler version, selected language mode and project isolation settings; they are separate inputs to the behavior being discussed.

Swift Interview Questions and Answers for Beginners

Look for accurate predictions of values and output, clear explanations of optionality and practical choices between common language constructs.

1. What is the difference between let and var in Swift?

let creates a binding that cannot be reassigned after initialization; var permits reassignment. I use let when change is not part of the intended behavior, which makes that intent visible to both the compiler and readers. The distinction concerns the binding and the semantics of the bound type.

let limit = 3
var attempts = 0
attempts += 1
assert(attempts == 1 && limit == 3)
let limit = 3
var attempts = 0
attempts += 1
assert(attempts == 1 && limit == 3)
let limit = 3
var attempts = 0
attempts += 1
assert(attempts == 1 && limit == 3)

For a value-type counter, var is needed to increment it. A let reference to a class instance cannot be redirected to another instance, but the instance’s variable properties may still change. Therefore “let makes everything reachable immutable” is incorrect; the type and its exposed operations matter.

2. How does Swift type inference work?

Swift can infer a declaration’s type from its initializer and surrounding context, so an explicit annotation is not always necessary. The inferred type is still a static type; inference does not turn the variable into a container that can later hold unrelated types.

For example, var score = 10 normally infers Int, so assigning a String later is a compile-time error. An annotation such as let ratio: Double = 1 supplies a different context for the literal. I add annotations when they clarify an API, disambiguate a value or make an important representation choice visible.

3. Why does Swift require explicit numeric conversions?

Different numeric types have different representations and ranges. Explicit conversion makes a representation change visible rather than silently combining values in a way that may lose information. A conversion is not automatically safe merely because the source and destination are both numeric.

let count = 3
let unitCost = 2.5
let total = Double(count) * unitCost
assert(total == 7.5)
let count = 3
let unitCost = 2.5
let total = Double(count) * unitCost
assert(total == 7.5)
let count = 3
let unitCost = 2.5
let total = Double(count) * unitCost
assert(total == 7.5)

If three items cost 2.5 each, converting the integer count to Double expresses the intended multiplication. Converting a fractional Double to Int instead would discard its fractional part when the conversion is valid. I would choose the type based on the domain and validate range where values come from external input.

4. How do String and Character differ?

String represents a sequence of text characters, while Character represents one extended grapheme cluster. A character can consist of multiple Unicode scalars, so character counts are not interchangeable with byte counts. This matters for user-visible text and for interfaces that specify encoded byte lengths.

An emoji or accented letter may occupy several bytes while appearing as one character. I would not use String.count to enforce a protocol’s byte limit without checking its encoding. Conversely, slicing arbitrary bytes can split a visible character. Swift’s string APIs encourage working with appropriate indices instead of assuming every character occupies one byte.

5. Why can’t you normally index a Swift String with an integer?

String uses String.Index because the boundaries of user-perceived characters do not correspond to fixed-width integer offsets in memory. An integer such as 2 does not directly identify a valid encoded character boundary. The appropriate operation depends on whether you need iteration, a prefix or an index-based range.

To inspect the first character, text.first is clearer than calculating an offset and also handles an empty string through an optional result. If an index is needed, derive it through the string’s indexing APIs and respect its bounds. Repeatedly walking from the beginning to arbitrary offsets can also be unnecessarily expensive.

6. What is an optional in Swift?

An optional explicitly represents either a wrapped value or no value, written nil. The type Int? is different from Int because the caller must account for absence before using the integer. This is a domain signal, not merely an inconvenience to remove with punctuation.

let zero = Int("0")
let invalid = Int("apple")
assert(zero == 0)
assert(invalid == nil)
let zero = Int("0")
let invalid = Int("apple")
assert(zero == 0)
assert(invalid == nil)
let zero = Int("0")
let invalid = Int("apple")
assert(zero == 0)
assert(invalid == nil)

Parsing user text as an integer can fail, so the initializer returns an optional. A valid zero remains a present value and is not the same as nil. I would decide whether absence means invalid input, an omitted setting or a legitimate missing result before choosing how to handle it.

7. How does if let unwrap an optional?

Optional binding with if let checks whether an optional contains a value and introduces a non-optional binding inside the successful branch. It combines the check and extraction without a forced unwrap. The else branch can handle absence explicitly.

let input = "12"
if let quantity = Int(input), quantity > 0 {
    assert(quantity == 12)
} else {
    assertionFailure("Expected a positive fixture quantity")
}
let input = "12"
if let quantity = Int(input), quantity > 0 {
    assert(quantity == 12)
} else {
    assertionFailure("Expected a positive fixture quantity")
}
let input = "12"
if let quantity = Int(input), quantity > 0 {
    assert(quantity == 12)
} else {
    assertionFailure("Expected a positive fixture quantity")
}

For a parsed quantity, I can use the integer inside the successful branch and report invalid input otherwise. The bound name does not ordinarily escape that branch. I would also validate the resulting value: parsing -2 successfully does not prove that a negative quantity is allowed.

8. When would you choose guard let instead of if let?

guard let is useful when a value is required for the rest of the current scope. Its else branch must leave that scope, for example by returning or throwing. The successfully bound value remains available afterward, which can keep the normal path less nested.

func doubled(_ text: String) -> Int? {
    guard let value = Int(text), (0...100).contains(value) else {
        return nil
    }
    return value * 2
}
assert(doubled("4") == 8)
assert(doubled("bad") == nil)
func doubled(_ text: String) -> Int? {
    guard let value = Int(text), (0...100).contains(value) else {
        return nil
    }
    return value * 2
}
assert(doubled("4") == 8)
assert(doubled("bad") == nil)
func doubled(_ text: String) -> Int? {
    guard let value = Int(text), (0...100).contains(value) else {
        return nil
    }
    return value * 2
}
assert(doubled("4") == 8)
assert(doubled("bad") == nil)

A function that cannot calculate a label without a valid number can return early for invalid text. That makes the precondition prominent. I would still use if let when optional work belongs in a local branch and the surrounding function can continue without the value.

9. What does the nil-coalescing operator do?

The ?? operator provides a fallback when an optional is nil. It unwraps a present value and only uses the fallback when no value exists. A fallback should reflect the intended meaning of absence rather than hide an error that the caller needs to know about.

For an optional display nickname, falling back to “Guest” may be appropriate. For a missing payment amount, falling back to zero could silently misrepresent the transaction. An empty but present String does not trigger ??, so blank-text validation is a separate decision.

10. What is optional chaining?

Optional chaining attempts property, method or subscript access through an optional value and yields an optional result when the chain can fail because a value is absent. It avoids nested manual checks for straightforward access. It does not explain why a value was missing.

If an optional customer has an optional address, chaining can obtain an optional city. The caller still needs to decide what missing city means. When absence requires different messages at different steps, explicit binding may be clearer than one long chain that collapses several reasons into nil.

11. Why can force unwrapping crash a program?

The ! unwrap asserts that an optional contains a value. If it is nil, execution traps rather than producing a recoverable missing-value result. It should not be used simply to silence the compiler when external input can legitimately be absent.

A dictionary lookup or integer parse can return nil even if common test data succeeds. I would use binding, a justified fallback or an error path for those cases. Where an invariant truly guarantees presence, I would make that invariant understandable and test it; the exclamation mark does not establish the guarantee by itself.

12. How do if conditions differ from truthy checks in some languages?

Swift conditions require Boolean expressions. Integers, strings and optionals do not automatically become true or false based on their contents. This encourages the code to state which property is being tested instead of relying on an implicit convention.

For a collection, !items.isEmpty clearly means that at least one item exists. An optional requires a nil check or binding, while an integer needs a comparison such as count > 0. Those conditions are not interchangeable: a present count of zero is different from an absent count.

13. What makes Swift switch statements useful?

A switch matches a value against cases and must cover the possibilities relevant to its type, often through explicit cases or a default. Cases do not implicitly fall through to the next case. This supports clear branching for states rather than a chain of loosely related comparisons.

For a local enum, listing every case lets the compiler help identify a newly added state that needs handling. A catch-all default can be appropriate for broad input domains but may hide that signal for a closed set of states. I would choose cases to express the business meaning rather than use default as a way to avoid thinking about remaining outcomes.

14. How do closed and half-open ranges differ?

A closed range such as 1...3 includes both bounds. A half-open range such as 0..<3 excludes its upper bound. The choice matters at boundaries, especially when iterating counts or matching numeric intervals.

A half-open range is often convenient for zero-based array positions, but direct element iteration is clearer when positions are unnecessary. For collections, using their indices avoids assuming a particular index scheme. I would also handle invalid or reversed bounds deliberately rather than build a range from unchecked external values.

15. When should you use for-in, while and repeat-while?

for-in iterates a sequence, while repeats while a condition holds before each iteration, and repeat-while executes the body before checking its condition. The choice should express what controls progress. A loop needs a clear termination condition rather than an assumption that input will eventually change.

Iterating known names fits for-in. Processing until a bounded state is reached may fit while. A menu that must be shown once before deciding whether to repeat can fit repeat-while. For retries or external work, I would add an explicit stopping policy instead of an unbounded loop that only succeeds under ideal conditions.

16. How do break and continue affect a loop?

break leaves the loop, while continue skips the remainder of the current iteration and proceeds to the next one. They express different responses to a condition. Confusing them can either stop processing too early or continue after a situation that should terminate the operation.

When scanning measurements, a missing optional entry might be skipped, but a sentinel indicating the end of a batch might end the loop. I would make those meanings explicit in the code. For nested loops, a label can identify the intended target, but excessive control transfers can make a simpler function decomposition easier to read.

17. When would you choose Array, Set or Dictionary?

Array preserves an ordered sequence and permits repeated values. Set represents unique hashable elements without a promised iteration order. Dictionary maps unique hashable keys to values, also without a promised iteration order. The structure should match the question the program needs to answer.

A playlist belongs in an Array because ordering and repeated songs can matter. Membership in a collection of enabled feature names may suit a Set. Looking up a stock count by product code suits a Dictionary. Converting a sequence to a set can remove duplicates but also discards ordering, so it is not a neutral cleanup step.

18. How do you access array elements safely?

An Array subscript requires a valid index and traps when the index is out of bounds. It does not return an optional simply because the requested position might be missing. Properties such as first provide an optional when that is the intended operation.

let names = ["Mira", "Jon"]
let requested = 2
let name = names.indices.contains(requested) ? names[requested] : nil
assert(name == nil)
assert(names.first == "Mira")
let names = ["Mira", "Jon"]
let requested = 2
let name = names.indices.contains(requested) ? names[requested] : nil
assert(name == nil)
assert(names.first == "Mira")
let names = ["Mira", "Jon"]
let requested = 2
let name = names.indices.contains(requested) ? names[requested] : nil
assert(name == nil)
assert(names.first == "Mira")

For external positions, I would check the array’s valid indices before subscripting. I would not use count itself as the last index: a nonempty array ends at count minus one. Iterating elements directly is usually safer when the task does not need positions.

19. Why does a dictionary lookup return an optional?

The requested key may not exist, so the subscript returns an optional value. A missing key is distinct from a key whose stored value happens to be zero or empty. The caller should choose a fallback or missing-key response that fits the domain.

An inventory lookup returning zero means the product is known but has no units; nil can mean an unknown product code. Replacing every missing key with zero may be acceptable for a frequency counter but misleading for inventory validation. The same API can support different policies, so that decision belongs in the surrounding logic.

20. What does value semantics mean for Swift collections?

Array, Set and Dictionary are value types: assigning a collection or passing it as a value preserves independent value behavior when the collection is changed. Their implementation can share storage internally until a write requires separation. That optimization does not change the observable value contract.

var original = [1, 2]
var copy = original
copy.append(3)
assert(original == [1, 2])
assert(copy == [1, 2, 3])
var original = [1, 2]
var copy = original
copy.append(3)
assert(original == [1, 2])
assert(copy == [1, 2, 3])
var original = [1, 2]
var copy = original
copy.append(3)
assert(original == [1, 2])
assert(copy == [1, 2, 3])

If an Array contains class instances, copying the array does not recursively clone those instances. Changing the copied array’s membership is distinct from changing a property on a shared object inside it. I would distinguish container value semantics from the semantics of its elements rather than promise a deep copy of every reachable value.

21. How do map and filter differ?

map transforms each element into a corresponding result, while filter keeps elements satisfying a Boolean predicate. For ordinary eager arrays, map preserves the element count and filter preserves the relative order of retained elements. They express different intentions and can be composed when both are needed.

let values = [-2, 3, 4]
let doubledPositives = values.filter { $0 > 0 }.map { $0 * 2 }
assert(doubledPositives == [6, 8])
let values = [-2, 3, 4]
let doubledPositives = values.filter { $0 > 0 }.map { $0 * 2 }
assert(doubledPositives == [6, 8])
let values = [-2, 3, 4]
let doubledPositives = values.filter { $0 > 0 }.map { $0 * 2 }
assert(doubledPositives == [6, 8])

If I need the doubled values of positive numbers, filtering first makes the eligibility rule visible and mapping then expresses the transformation. I would avoid using map only for side effects when a loop better communicates the task. A compact expression is useful only if the sequence of operations remains clear.

22. When is compactMap useful?

compactMap transforms elements with a closure that can return an optional and keeps only the non-nil results. It is useful when absence means that no result should be emitted. It also means failed conversions can disappear, so it is not automatically the right tool for validating every input.

Converting optional numeric text for a best-effort display may fit compactMap. Importing a required dataset may need a separate list of failed records instead. For inputs “2”, “bad” and “5”, compactMap with Int produces two integers, which is convenient only if dropping “bad” is intentional.

23. What do argument labels contribute to a function call?

Argument labels describe the role of values at the call site, while parameter names are used inside the function. A function can use different names for those roles or omit an external label with an underscore. Good labels make similar-looking arguments harder to confuse.

A call such as distance(from: start, to: end) communicates direction better than two unlabeled points. I would not omit labels everywhere just to shorten calls. Labels are part of an API’s readability and should reflect how a developer naturally describes the operation.

24. How do return values differ from printing inside a function?

A return value supplies a result to the caller for further use, while printing produces an output side effect. Separating calculation from presentation makes a function easier to reuse and test. A function that only prints does not give the caller the computed value as a result.

For a total-price calculation, returning the total lets a UI format it, a test compare it or another calculation use it. Printing can help demonstrations, but it should not replace an explicit return type when the result is part of the function’s contract. A function without a meaningful return value has Void as its result type.

25. How can a tuple return multiple related values?

A tuple groups a fixed set of values into one compound value, with optional element labels. It can be useful for a small local result where the parts naturally travel together. A named struct is often clearer when the result has a lasting domain meaning, behavior or many call sites.

func summary(_ values: [Int]) -> (count: Int, total: Int) {
    (values.count, values.reduce(0, +))
}
let result = summary([2, 3])
assert(result.count == 2 && result.total == 5)
func summary(_ values: [Int]) -> (count: Int, total: Int) {
    (values.count, values.reduce(0, +))
}
let result = summary([2, 3])
assert(result.count == 2 && result.total == 5)
func summary(_ values: [Int]) -> (count: Int, total: Int) {
    (values.count, values.reduce(0, +))
}
let result = summary([2, 3])
assert(result.count == 2 && result.total == 5)

A function can return a count and total together so they describe the same input. Labels make their roles visible and avoid confusing two integers. I would not use increasingly large positional tuples as an informal replacement for a well-named model type.

26. What are default parameter values useful for?

A default parameter lets callers omit an argument when a documented common value is appropriate. It reduces repetitive call-site detail without removing the caller’s ability to choose another value. The default remains a behavioral decision and should be unsurprising.

A formatting function might default to a concise label while allowing a more detailed one. A default that silently performs destructive work would be much harder to justify. I would also consider whether changing the default later changes existing callers’ behavior, even though those callers contain no explicit reference to that value.

27. What does an inout parameter mean?

An inout parameter permits the function to update a caller’s variable, and the call uses an ampersand to make that modification visible. It is appropriate when mutation is the API’s intent. It should not be described as an unrestricted pointer that can be stored and used after the call.

A helper can normalize a small value in place, but a function returning a transformed value may be clearer when callers want to keep the original. The argument must be suitable mutable storage, not a constant or arbitrary temporary expression. I would make the mutation evident in the function name and document its bounds.

28. What is a closure in Swift?

A closure is a value representing executable functionality that can be passed to another function or stored. Closure expressions provide a concise way to describe behavior at the point of use. They can also capture values from their surrounding context, which affects how the behavior uses outside state.

A sorting call can receive a closure that compares two elements. Named parameters may be clearer than shorthand arguments when the comparison has several steps. I would use the shortest form that remains understandable, not compress a complicated rule into punctuation simply because the language permits it.

29. What is trailing-closure syntax?

Trailing-closure syntax places a closure argument after the call’s parentheses when the call permits it. It is a readability feature; it does not create a different kind of function or change whether the closure executes immediately. Execution timing depends on the receiving API.

An array transformation such as values.map { $0 * 2 } reads naturally because the transformation is the main behavior being supplied. The same visual syntax can appear on APIs that store work for later, so I would read the function contract rather than infer scheduling or concurrency from the braces.

30. What does a closure capture from its surrounding scope?

A closure can use names from the context where it is defined, allowing behavior to depend on surrounding state. Capture does not always mean taking a frozen snapshot at the moment the closure expression appears. The binding and capture semantics determine what later execution observes.

func capturedResult() -> Int {
    var offset = 1
    let adjusted = { (value: Int) in value + offset }
    offset = 4
    return adjusted(3)
}
assert(capturedResult() == 7)
func capturedResult() -> Int {
    var offset = 1
    let adjusted = { (value: Int) in value + offset }
    offset = 4
    return adjusted(3)
}
assert(capturedResult() == 7)
func capturedResult() -> Int {
    var offset = 1
    let adjusted = { (value: Int) in value + offset }
    offset = 4
    return adjusted(3)
}
assert(capturedResult() == 7)

A local closure that reads a mutable offset can see a later offset change when called. If a fixed value is intended, that choice should be explicit. This beginner example demonstrates observable local behavior only; lifetime and reference-cycle design require further analysis for stored closures.

31. How do structs and classes differ at a basic level?

Structs have value semantics, while classes have reference semantics and identity. Both can define properties, methods and initializers and conform to protocols. Choosing between them should follow whether independent values or a shared identity best represents the model.

A coordinate is naturally a value: changing one copy should not alter another. A shared session object may need one identity observed through several references. I would not choose a class merely because it can have methods; structs can have methods too. Nor would I claim that choosing a struct automatically makes every contained reference independent.

32. How can two constants refer to the same mutable class instance?

Assigning a class reference to another binding does not copy the instance. Both references can identify the same object, and changes through one can be observed through the other. let prevents rebinding the reference but does not prohibit changes to accessible var properties on the instance.

final class Counter {
    var value = 0
}
let first = Counter()
let second = first
second.value = 2
assert(first === second)
assert(first.value == 2)
final class Counter {
    var value = 0
}
let first = Counter()
let second = first
second.value = 2
assert(first === second)
assert(first.value == 2)
final class Counter {
    var value = 0
}
let first = Counter()
let second = first
second.value = 2
assert(first === second)
assert(first.value == 2)

This matters when passing shared models between parts of a program: an apparently local edit can affect another observer. If independent state is needed, the design needs an actual value copy or an explicit copying operation, not simply another assignment.

33. What is the difference between a stored and computed property?

A stored property holds state, while a computed property derives a value through accessors instead of storing that value directly. A computed property is useful when the result should remain consistent with other state. It is not automatically cached, so expensive computation deserves attention.

A rectangle’s area can be computed from width and height instead of maintaining a third stored value that might become stale. For a cheap calculation this improves consistency. If an accessor performs substantial work or side effects, property syntax can obscure that cost, so the API should remain predictable.

34. Why do some struct methods need mutating?

A struct or enum method that changes the instance’s value must be marked mutating. This makes mutation part of the method’s interface and prevents calling it on an immutable value binding. A class method changing its instance’s stored properties does not use the same mutating marker.

struct Score {
    var value = 0
    mutating func increment() { value += 1 }
}
var score = Score()
score.increment()
assert(score.value == 1)
struct Score {
    var value = 0
    mutating func increment() { value += 1 }
}
var score = Score()
score.increment()
assert(score.value == 1)
struct Score {
    var value = 0
    mutating func increment() { value += 1 }
}
var score = Score()
score.increment()
assert(score.value == 1)

For a score value, an increment method changes the score instance and therefore needs mutating. A method that merely returns a proposed new score can avoid changing self. I would choose based on the intended usage rather than add mutating only after a compiler error without understanding which state the method owns.

35. What is the purpose of an initializer?

An initializer establishes a usable instance by setting its required state. It should ensure the type’s intended invariants hold rather than leave callers responsible for completing setup through unrelated later assignments. Structs and classes have different initializer rules, so synthesized behavior should not be assumed identical.

For a bounded quantity, initialization can reject or otherwise handle invalid input instead of constructing an impossible state. A failable initializer can return nil where failure is part of the contract. I would decide whether absence alone adequately describes that failure or whether a throwing operation should provide a reason.

36. How does an enum model a finite set of states?

An enum defines named cases representing alternatives, making the allowed states explicit in the type system. It avoids arbitrary strings and spelling differences when the state set is known. A switch can then handle those cases directly.

For an upload state, idle, running and complete communicate more than unrelated Boolean flags that might simultaneously claim running and complete. I would model only valid alternatives and decide what additional information each requires. An enum is not restricted to integers or strings; cases can exist without any raw value.

37. How do associated values differ from enum raw values?

Associated values store information specific to a particular enum instance and case. Raw values provide fixed representations assigned to cases for a raw-value enum. They solve different problems: carrying payload data versus mapping a case to a stable representation.

enum ImportOutcome {
    case accepted(count: Int)
    case rejected(reason: String)
}
let outcome = ImportOutcome.accepted(count: 3)
switch outcome {
case .accepted(let count):
    assert(count == 3)
case .rejected:
    assertionFailure("Unexpected fixture rejection")
}
enum ImportOutcome {
    case accepted(count: Int)
    case rejected(reason: String)
}
let outcome = ImportOutcome.accepted(count: 3)
switch outcome {
case .accepted(let count):
    assert(count == 3)
case .rejected:
    assertionFailure("Unexpected fixture rejection")
}
enum ImportOutcome {
    case accepted(count: Int)
    case rejected(reason: String)
}
let outcome = ImportOutcome.accepted(count: 3)
switch outcome {
case .accepted(let count):
    assert(count == 3)
case .rejected:
    assertionFailure("Unexpected fixture rejection")
}

A result case can carry the number of accepted records or a rejection message, with different values each time. A raw String case may represent a fixed external code. I would avoid treating every state as a string and parsing its payload manually when an associated value can express that structure safely.

38. What is a protocol used for?

A protocol defines requirements that conforming types must satisfy, such as properties or methods. It expresses a capability without requiring every implementation to inherit from one class. Structs, enums and classes can conform when they meet the requirements.

A labeling capability can let several unrelated models supply a display label. I would keep the protocol focused on the behavior consumers actually need rather than create a large checklist for hypothetical future types. Conformance is a contract about available behavior; it does not by itself guarantee that an implementation is meaningful or free of side effects.

39. When should a function throw an error rather than return an optional?

An optional is useful when the important distinction is whether a value exists. A throwing function is useful when failure has information the caller needs to handle or explain. Errors are represented by types conforming to Error, and callers can handle or propagate them.

enum QuantityError: Error {
    case invalidText
    case negative
}
func quantity(_ text: String) throws -> Int {
    guard let value = Int(text) else { throw QuantityError.invalidText }
    guard value >= 0 else { throw QuantityError.negative }
    return value
}
do {
    let value = try quantity("7")
    assert(value == 7)
} catch {
    assertionFailure("Unexpected fixture error")
}
enum QuantityError: Error {
    case invalidText
    case negative
}
func quantity(_ text: String) throws -> Int {
    guard let value = Int(text) else { throw QuantityError.invalidText }
    guard value >= 0 else { throw QuantityError.negative }
    return value
}
do {
    let value = try quantity("7")
    assert(value == 7)
} catch {
    assertionFailure("Unexpected fixture error")
}
enum QuantityError: Error {
    case invalidText
    case negative
}
func quantity(_ text: String) throws -> Int {
    guard let value = Int(text) else { throw QuantityError.invalidText }
    guard value >= 0 else { throw QuantityError.negative }
    return value
}
do {
    let value = try quantity("7")
    assert(value == 7)
} catch {
    assertionFailure("Unexpected fixture error")
}

A quantity parser may distinguish invalid text from a negative value, allowing a useful response instead of an unexplained nil. I would not catch an error merely to replace it with a misleading success value. This fixture uses only local parsing and validates the result without external effects.

40. How do try, try? and try! differ?

try marks a call that can throw and must be handled or propagated. try? converts failure into an optional nil result, discarding the error information. try! asserts that throwing will not occur and traps if an error is thrown. These choices express different failure contracts rather than interchangeable syntax.

If the reason for a failed import matters, try? can erase information needed for recovery or a useful message. try! is especially inappropriate for untrusted input or an unreliable external operation. I would use ordinary do-catch or propagation when the caller needs to respond, and reserve optional conversion for cases where “no result” is genuinely sufficient.

Swift Interview Questions and Answers for Intermediate

These answers connect language features to their contracts. Useful examples explain what the code guarantees and where reference lifetimes, type constraints or suspension change the result.

41. How does ARC determine when a class instance can be released?

Automatic Reference Counting tracks strong ownership of class instances. When no strong references keep an instance alive, it can be deinitialized and its storage reclaimed. ARC is not a tracing garbage collector, so a group of instances that strongly retain one another can remain alive even when the rest of the program cannot reach them.

I reason about ownership edges rather than count variable names. A stored closure, collection, or task can retain an instance indirectly. Removing one visible variable does not prove the object should disappear if another owner still needs it. Conversely, weak references do not keep it alive merely because a property still exists.

42. When should a relationship use weak instead of strong?

A weak reference observes an instance without owning its lifetime and becomes nil when that instance is released. It is appropriate when the referenced object can legitimately disappear first. Weak references are optional and apply to class instances or suitable class-constrained abstractions.

A delegate often belongs to another owner, so a weak delegate can avoid a cycle between a controller and its worker. I still identify who strongly owns the delegate; making every relationship weak can cause required objects to vanish immediately. The choice follows the lifetime contract, not a rule that all backward-looking properties must be weak.

43. How does unowned differ from weak?

An unowned reference does not keep an instance alive, but a normal unowned reference assumes the instance remains valid whenever it is accessed. It does not provide the same automatic optional-nil behavior as weak. Accessing it after the instance is gone is a programming error that can trap.

I use unowned only when the ownership design guarantees the referenced object outlives every access. For an asynchronous callback whose owner might be dismissed, that guarantee may not hold, making weak a safer expression of the contract. Unowned is not simply a faster spelling of weak, and avoiding optional handling does not justify an invalid lifetime assumption.

44. How can a stored closure create a strong reference cycle?

A class can retain a closure through a property, while that closure retains the class through a captured reference. The two strong ownership edges keep each other alive. I inspect the closure’s capture list and the duration for which it is stored rather than assume every use of self leaks.

If a view model stores a callback that reads its own state, a weak capture may break the cycle when losing the owner should cancel the callback’s useful work. Alternatively, the design may release the callback after completion. A short-lived nonescaping closure has a different ownership situation from a callback stored indefinitely.

45. What does a capture list change for a value variable?

A capture list can capture the current value of a variable when the closure is created, instead of having the closure refer to the variable’s later value. This is useful when a callback should represent a snapshot. For reference-type values, capturing the reference does not deep-copy the object it points to.

In the example, the closure returns 1 after the outer variable changes to 2. Without that explicit value capture, the closure can observe the later variable state. I distinguish snapshotting a value from sharing an object so that a capture list does not create a false expectation of immutability.

var number = 1
let snapshot = { [number] in number }
number = 2
assert(snapshot() == 1)
assert(number == 2)
var number = 1
let snapshot = { [number] in number }
number = 2
assert(snapshot() == 1)
assert(number == 2)
var number = 1
let snapshot = { [number] in number }
number = 2
assert(snapshot() == 1)
assert(number == 2)

46. Why can strengthening weak self change the lifetime of an asynchronous operation?

Converting a weak reference to a strong local reference keeps the object alive for the period that local reference is needed. That can be intentional so an operation completes against a valid owner, but it can also extend the owner’s lifetime across suspension or a long-running loop.

I decide whether the operation should continue after the UI or owner disappears. A weak capture followed immediately by a long-lived strong self binding does not mean the object remains weakly held throughout the task. I also define cancellation and task ownership explicitly, rather than expect a capture list alone to stop background work.

47. What should you know about ArraySlice storage and indices?

An ArraySlice represents a view of a portion of an array and can share storage with the original array. A small long-lived slice may therefore keep a much larger backing allocation alive. When independent compact ownership matters, constructing an Array from the slice can express that intention.

A slice also preserves the corresponding indices rather than necessarily starting at zero. The example takes the last two elements of a four-element array, so its startIndex is 2. I use collection-provided indices when working with the slice and explicitly materialize an array when an API requires zero-based array indexing or the slice should not retain the original storage.

let values = [10, 20, 30, 40]
let tail = values[2...]
assert(tail.startIndex == 2)
assert(tail[tail.startIndex] == 30)
let compact = Array(tail)
assert(compact.startIndex == 0)
assert(compact == [30, 40])
let values = [10, 20, 30, 40]
let tail = values[2...]
assert(tail.startIndex == 2)
assert(tail[tail.startIndex] == 30)
let compact = Array(tail)
assert(compact.startIndex == 0)
assert(compact == [30, 40])
let values = [10, 20, 30, 40]
let tail = values[2...]
assert(tail.startIndex == 2)
assert(tail[tail.startIndex] == 30)
let compact = Array(tail)
assert(compact.startIndex == 0)
assert(compact == [30, 40])

48. Does a struct containing a class reference provide a deep copy?

No. Copying the struct copies its stored reference value, so both struct values can still refer to the same class instance. The outer value semantics do not automatically clone every reachable object. I inspect the semantics of the stored properties before describing a type as an independent snapshot.

If two structs each hold the same mutable Settings object, changing that object through one struct can be observed through the other. A truly independent snapshot may require immutable referenced state, explicit copying, or a different representation. Merely replacing class with struct at the outermost declaration does not solve shared-state concerns.

49. What must be considered when implementing custom copy-on-write storage?

I need a reference-backed storage object, a way to establish exclusive ownership before mutation, and a complete audit of every mutation path. Copy-on-write preserves semantics only if no exposed alias can mutate the supposedly shared storage behind the value’s back.

A uniqueness check such as isKnownUniquelyReferenced can support the implementation, but it is not a general synchronization primitive. Concurrent unsynchronized access remains a separate problem. I prefer standard value types unless custom storage has a measured benefit, because subscripts, nested references, and escaped storage aliases can make an apparently simple implementation incorrect.

50. When is a generic parameter better than an existential protocol value?

A generic parameter preserves a concrete type relationship for a call and can express constraints between inputs and outputs. An existential value, written with any, supports storing values whose conforming concrete type can vary at runtime. I choose according to the required abstraction rather than treating one form as universally superior.

A function comparing two values of the same generic Equatable type can express that shared type directly. A heterogeneous collection of independently conforming renderers may need existential storage. Generics can enable specialization, but actual performance depends on compilation and usage; any does not mean every value must always incur a heap allocation.

51. What does an associated type express in a protocol?

An associated type names a type that each conforming implementation supplies, allowing requirements to refer to that type consistently. It is useful when a protocol describes a relationship, such as a container’s element or a producer’s output, without fixing one concrete type for all conformers.

A protocol with an Output associated type can require a method returning Output. One conformer can produce Int and another String. Generic constraints can then relate the associated type to other parameters. I do not assume every member can be called through an unconstrained existential, because some operations require type relationships the existential interface does not expose.

52. How does a same-type constraint improve a generic API?

A same-type constraint states that two type expressions must be identical, letting the compiler verify relationships that would otherwise require casts or runtime checks. It is commonly used with associated types in a where clause. The constraint should reflect a real requirement rather than overrestrict an otherwise flexible API.

For a function combining two collections element by element, requiring their Element types to match can make the operation type-safe. If the function only formats each element independently, that restriction may be unnecessary. I design constraints from the operations the implementation actually needs, not from the concrete types used by the first caller.

53. What does some Protocol mean as a return type?

An opaque return type hides the concrete type from callers while preserving one underlying type identity for that declaration’s return paths, subject to its generic parameters. Callers use the declared protocol capabilities without naming the implementation type. The implementation still chooses a consistent concrete return type.

A function returning some Shape cannot ordinarily return a Circle in one branch and an unrelated Square in another just because both conform. It can use a consistent wrapper or another appropriate design. Opaque types provide abstraction without the same runtime heterogeneity as an any Shape value.

54. How is some Protocol as a parameter different from an opaque return?

A parameter written as some Protocol is shorthand for an unnamed generic parameter constrained to the protocol. The caller supplies the concrete conforming type for that invocation. An opaque return instead hides a concrete type chosen by the implementation. These positions reverse who chooses the type.

Two separate some Protocol parameters introduce separate generic types, so they do not inherently have the same concrete type. If the function requires that equality, I use a named generic parameter for both. This matters when comparing values or connecting associated types; similar-looking syntax does not establish a shared type relationship.

55. What does any Protocol allow you to store?

An existential protocol value can hold a conforming value whose concrete type may vary at runtime. It exposes operations supported through that existential interface, with restrictions where associated-type or Self relationships cannot be satisfied safely. It is useful for runtime heterogeneity and abstraction boundaries.

A list of different conforming formatters may use existential elements, while a generic pipeline may preserve concrete type relationships more naturally. I do not erase types simply to avoid designing constraints, because that can move complexity into casts or wrappers. Conversely, I do not force generics through every layer when runtime variation is the actual requirement.

56. How do protocol requirements differ from extension-only methods?

A protocol requirement participates in the conformance contract, and an extension can provide its default implementation. A method defined only in an extension is not the same kind of requirement. Dispatch through a generic or protocol-typed interface can therefore differ from calling a concrete type’s similarly named method.

If customization by conformers is part of the design, I declare the operation in the protocol rather than rely on a same-named extension helper being overridden. I test calls through both concrete and abstract interfaces when dispatch matters. This avoids an API that appears customizable in a direct call but uses the extension implementation through its intended abstraction.

57. What can an extension add, and what can it not add?

Extensions can add functionality such as computed properties, methods, subscripts, initializers within the applicable rules, and protocol conformance. They cannot simply add stored instance properties to an existing type. This makes them useful for organizing behavior without changing the original storage layout.

A computed distance property can derive from existing coordinates in an extension. If the design requires additional per-instance state, I consider a wrapper or changes to the original type instead of pretending a computed property stores data. I also keep unrelated extensions restrained so a familiar type does not accumulate surprising domain-specific behavior everywhere it is imported.

58. How do access control and setter visibility support invariants?

Access control limits which code can depend on or modify an API. A property can expose a wider getter while keeping its setter narrower, allowing observation without unrestricted mutation. This helps preserve invariants through methods that validate changes.

For a counter, private(set) can allow callers to read the count while requiring them to use an increment operation. The exact accessible scope also depends on the enclosing type and declaration. I avoid exposing mutable implementation details merely to simplify a test; tests should generally exercise the intended contract or use an appropriately designed internal boundary.

59. How do public and open differ for classes?

Public makes an API available outside its defining module, while open additionally permits the relevant class subclassing or member overriding across module boundaries. Open therefore exposes a larger extensibility contract that future changes must respect. It is not simply a more visible version of every declaration.

A library can provide a public final class for use without supporting inheritance. If external subclassing is a deliberate extension mechanism, open may be appropriate, but the library must consider override behavior and initialization invariants. I prefer composition or protocols where they express the required customization without exposing a fragile inheritance contract.

60. What does a property wrapper encapsulate?

A property wrapper packages repeated access or storage behavior around a wrappedValue, with an optional projectedValue for additional functionality. It can make call sites concise, but it does not automatically provide validation semantics, persistence, or synchronization beyond its actual implementation.

A clamping wrapper might keep a numeric value within a declared range. I still define whether invalid assignment is clamped, rejected, or reported, because those are different business behaviors. I also inspect initialization and value/reference semantics; hiding a mutable reference inside a wrapper can introduce shared state that the concise property declaration does not make obvious.

61. How do throws and Result represent failure differently?

A throwing function propagates failure through control flow, while Result stores success or failure as a value that can be passed, saved, or transformed. The better choice depends on whether the API is naturally a direct operation or needs a first-class outcome value. Neither should erase useful error information.

A synchronous parser can throw and let its caller use do/catch. A collection of completed operations may store Result values so successes and failures can be inspected together. I avoid wrapping every throwing function in Result without a purpose, because it adds another layer while preserving the same underlying error-handling obligation.

62. How should catch patterns and error translation be designed?

I handle errors at the layer that can make a meaningful decision, using specific catch patterns before a broader fallback. Error translation can expose a stable domain contract while retaining enough underlying context for diagnosis. I avoid turning every failure into the same message or treating an unexpected failure as success.

For a profile-loading service, a known not-found response might become a domain-level missingProfile error, while authentication and transport failures need different handling. A broad catch should not accidentally hide cancellation or make retryable failures permanent. I separate user-facing wording from diagnostic details and preserve the causal information appropriately without leaking credentials or sensitive payloads.

63. What does typed throws add in modern Swift?

Typed throws specifies the error type in the function’s signature, allowing an API to communicate a more precise failure contract. In Swift 6-era syntax, ordinary untyped throws corresponds to throwing any Error. The feature is useful when the error domain is stable and callers benefit from exhaustively understanding it.

A small parser may promise a dedicated ParseError enum, while a function combining many evolving external services may need a broader contract. I consider API evolution before promising a narrow type. Typed throws does not make an operation infallible or eliminate the need to handle cancellation and other failures where they belong in the design.

64. How does defer help with cleanup?

defer schedules cleanup for when execution leaves the current scope, including normal return and thrown-error paths. Multiple defer blocks execute in reverse registration order. It is useful for local invariants, but it is not a substitute for recovery after process termination or a place to assume asynchronous work can be awaited.

The example appends 0 in the body, then 2 and 1 as the nested scope exits. I register cleanup after acquiring the resource it protects so the cleanup only applies when acquisition succeeded. For an async resource API, I follow its explicit lifetime and cancellation contract rather than force asynchronous cleanup into a synchronous defer block.

var trace: [Int] = []
do {
    defer { trace.append(1) }
    defer { trace.append(2) }
    trace.append(0)
}
assert(trace == [0, 2, 1])
var trace: [Int] = []
do {
    defer { trace.append(1) }
    defer { trace.append(2) }
    trace.append(0)
}
assert(trace == [0, 2, 1])
var trace: [Int] = []
do {
    defer { trace.append(1) }
    defer { trace.append(2) }
    trace.append(0)
}
assert(trace == [0, 2, 1])

65. When is reduce(into:) useful for building an accumulated result?

reduce(into:) passes a mutable accumulator to the combining closure, making it convenient to build a collection or other value incrementally. It avoids repeatedly expressing the result as a newly returned value, which can be beneficial for copy-on-write accumulators. The closure should mutate the accumulator according to a clearly defined aggregation rule.

The example counts occurrences of each word and produces two entries, with red counted twice. A conventional reduce can express the same result, but repeatedly constructing a new dictionary or array at every step can introduce unnecessary work. I choose the clearer implementation and measure performance where it matters rather than claim every use of reduce(into:) is automatically faster.

let words = ["red", "blue", "red"]
let counts = words.reduce(into: [String: Int]()) { result, word in
    result[word, default: 0] += 1
}
assert(counts == ["red": 2, "blue": 1])
let words = ["red", "blue", "red"]
let counts = words.reduce(into: [String: Int]()) { result, word in
    result[word, default: 0] += 1
}
assert(counts == ["red": 2, "blue": 1])
let words = ["red", "blue", "red"]
let counts = words.reduce(into: [String: Int]()) { result, word in
    result[word, default: 0] += 1
}
assert(counts == ["red": 2, "blue": 1])

66. When can lazy collection transformations help?

A lazy transformation can defer computation until elements are requested and avoid some intermediate collections. It is useful when only a prefix or selected subset will be consumed. It does not guarantee caching, faster execution in every case, or the absence of repeated work.

If a search stops at the first matching transformed value, eagerly mapping the entire array may do unnecessary work. If the lazy result is traversed repeatedly, the transformation may run repeatedly too. I keep side effects out of such transformations where possible and measure the actual workload rather than assume lazy is a universal optimization.

67. What performance assumptions should you make about Array operations?

Array supports efficient indexed access, and append is typically amortized constant time, while inserting or removing near the front can require shifting elements. Copy-on-write can add a buffer copy when mutating shared storage. Complexity should be considered alongside element cost and allocation behavior.

Repeatedly calling removeFirst to implement a large queue can create avoidable total work. I choose a suitable queue representation or maintain an index where appropriate instead of assuming every collection operation is constant time. reserveCapacity can reduce reallocations for known growth, but it does not change front-removal semantics or solve unnecessary copying.

68. What must Hashable implementations preserve?

Values that compare equal must produce compatible hash results by combining the same equality-relevant information. Unequal values may collide, so a hash value is not a unique identifier. I use Hasher rather than rely on a stable numeric hash across program runs.

If a key’s equality depends on an identifier, hashing unrelated mutable fields violates the contract. Mutating identity-relevant state of a reference used as a dictionary key can also make lookups behave unexpectedly. I prefer stable value keys and do not persist hashValue as an external database key or security fingerprint.

69. How does Unicode canonical equivalence affect String equality?

Swift String equality recognizes canonical equivalence, so different Unicode scalar sequences can represent equal text. That does not mean their UTF-8 bytes are identical, nor does it imply case-insensitive or locale-specific matching. The equality contract should match the task rather than assume visible similarity, scalar equality, and byte identity are interchangeable.

The example compares a precomposed accented character with a base character plus a combining mark: the strings are equal while their UTF-8 arrays differ. For signing, hashing an external byte protocol, or round-tripping source files, I follow the protocol’s explicit encoding and normalization rules. I do not normalize identifiers or security-sensitive input opportunistically, because that can change the meaning expected by another system.

let composed = "é"
let decomposed = "e\u{301}"
assert(composed == decomposed)
assert(Array(composed.utf8) != Array(decomposed.utf8))
let composed = "é"
let decomposed = "e\u{301}"
assert(composed == decomposed)
assert(Array(composed.utf8) != Array(decomposed.utf8))
let composed = "é"
let decomposed = "e\u{301}"
assert(composed == decomposed)
assert(Array(composed.utf8) != Array(decomposed.utf8))

70. Does async mean a function runs on a background thread?

No. async permits suspension; it does not by itself promise a background thread or parallel execution. Actor isolation, the called operation, compiler settings, and language features influence where work executes. I separate concurrency semantics from assumptions about a particular thread.

A CPU-intensive loop inside an actor-isolated async function can still occupy that actor until it reaches an appropriate suspension or scheduling boundary. Swift 6.2 adds configurable default isolation and caller-isolation behavior, so I check the project settings before repeating older executor rules. Offloading work requires an explicit design, not merely adding async to the signature.

71. What does await tell the reader?

await marks a potential suspension point when accessing an asynchronous operation or crossing an isolation boundary that requires it. It does not guarantee suspension on every invocation. At a suspension point, other work may run, so assumptions about mutable state may need to be reconsidered afterward.

If I read an actor’s balance, await an external decision, and then act on the earlier value, another task may have changed the balance in between. I revalidate the relevant condition or design an appropriate reservation protocol. The presence of await is therefore both a syntax requirement and a signal to inspect state continuity.

72. How does async let express structured concurrency?

async let starts a child task whose lifetime is tied to the enclosing scope. It is useful for a known small number of independent asynchronous operations whose results will be combined. The scope cannot simply abandon its child work without the structured-concurrency cleanup behavior.

Two independent reads can be started with separate async let declarations and awaited together, rather than awaiting the first before beginning the second. I use this only when they are genuinely independent. If the second request requires the first result or they mutate shared state without a valid isolation design, parallel syntax does not make the dependency safe.

73. When should you use a task group?

A task group supports a dynamic set of structured child tasks and collection of their results within a scope. Results are typically consumed as tasks complete, not automatically in submission order. I carry an index or identifier when output order matters.

For a batch of independent transformations, each child can return its source index with the result, and the parent can assemble the desired ordering. I also bound concurrency where the workload or downstream service requires it instead of creating unlimited tasks. Structured lifetime management does not mean unlimited resources or automatic rate limiting.

74. How does Task differ from a structured child task?

Task creates an unstructured task whose lifetime is not automatically bounded by the lexical scope in the same way as async let or a task-group child. It can inherit relevant context, including actor isolation, under the applicable language rules. I retain a handle when cancellation or result observation matters.

Launching Task from a UI action can bridge synchronous code to async work, but returning from the action does not mean the task is canceled. I define who owns that task and what should happen when the screen disappears. Fire-and-forget work without error observation can conceal failures even when the compiler accepts it.

75. When is Task.detached appropriate?

A detached task is an unstructured task that does not inherit the same actor context and task-local environment as an ordinary context-inheriting Task. It is appropriate only when that independence is intentional. It still needs safe data transfer, cancellation ownership, and error handling.

I do not use detached as a routine workaround for an isolation diagnostic. Capturing a non-Sendable mutable object can still be invalid, and detached does not establish a dedicated thread. Often a structured task or explicitly designed concurrent function communicates the intended lifetime and execution behavior more clearly.

76. How does cooperative cancellation work?

Cancellation signals that work is no longer wanted; it does not forcibly stop arbitrary Swift code at an unpredictable instruction. Tasks and operations must check or respond to cancellation appropriately. Some async APIs throw cancellation errors, while CPU-bound work may need explicit checks.

In a long loop, I can periodically check Task.isCancelled or use Task.checkCancellation in a throwing context. Cleanup still needs to preserve invariants, and cancellation does not undo external effects already completed. I avoid swallowing cancellation in a broad catch and continuing indefinitely unless the operation explicitly requires a bounded cleanup phase.

77. What protection does an actor provide?

An actor isolates its mutable state so access is coordinated through the language’s concurrency rules. External callers generally need asynchronous access to isolated operations when crossing that boundary. The protection concerns isolated state, not every external object or side effect the actor happens to use.

An actor can own a counter and provide an increment method so callers do not race on the stored count directly. If it exposes a mutable reference without a safe transfer or isolation design, the broader system can still be incorrect. I keep state transitions inside the actor and distinguish isolation from a guarantee of business-level atomicity across await points.

78. Why are actors reentrant across suspension points?

When an actor-isolated function suspends, other work can execute on the actor before the original function resumes. This allows progress rather than holding the actor idle during an external wait. It also means a sequence spanning await is not automatically one indivisible state transition.

For an inventory reservation, checking stock, awaiting payment, and then decrementing the earlier stock value can oversell if another request intervenes. I may reserve before awaiting and compensate on failure, or revalidate afterward under a suitable protocol. An actor prevents certain data races but does not choose the correct transactional business design.

79. What does Sendable communicate?

Sendable describes values that can be safely transferred across concurrency boundaries under the language’s rules. The compiler can verify many value types whose stored members satisfy the requirements. A conformance is a safety contract, not a claim that all methods can run simultaneously without further isolation.

An immutable value payload is often straightforward to transfer. A class containing unsynchronized mutable state is not made safe by adding unchecked conformance; @unchecked Sendable moves the proof obligation to the programmer. I first consider immutability, actor ownership, or a properly synchronized implementation rather than silence a diagnostic with an unsupported promise.

80. How do Swift 6 language mode and default actor isolation affect concurrency code?

Swift 6 language mode strengthens concurrency checking, while compiler version, upcoming features, and default actor-isolation settings determine additional behavior. Swift 6.2 supports opting into MainActor default isolation and changed nonisolated async behavior through the relevant feature settings. These are not one universal setting applied identically to every project.

I inspect the target’s language mode and isolation configuration when reviewing a concurrency error or migrating code. An unannotated declaration can have different isolation under different configurations, so I prefer explicit boundaries in reusable APIs where useful. I test the actual target settings instead of assuming that installing a newer compiler automatically changes every source file’s concurrency model.

Swift Interview Questions and Answers for Experienced

Strong answers use evidence to locate ownership and isolation failures, distinguish logical races from data races and explain how a proposed change will be verified.

81. How would you diagnose an actor that produces stale results without a data race?

I would inspect assumptions that span suspension points. Actor isolation prevents overlapping access to protected state, but another actor-isolated operation can change that state while an earlier operation is suspended.

A search response may return after the user starts a newer search and overwrite the newer result. Capture a request identity and validate that it is still current before publishing, or redesign the state transition. The fix addresses logical ordering; adding another actor around the same sequence does not automatically make the whole asynchronous method atomic.

82. How would you choose buffering for a callback-backed AsyncStream?

I would decide whether every element must be retained or whether newer state can replace older observations. A continuation-backed AsyncStream can buffer values when its consumer is slower than its producer. Its yield call does not wait for consumption, so a bounded buffer with a dropping policy is not producer backpressure.

For a live position display, keeping only the newest pending update may be reasonable; for financial events, silently dropping old or new events is not an acceptable substitute for reliable delivery. Choose and inspect the buffering policy and yield outcome, then arrange a producer-specific pause, durable queue or explicit failure policy when loss is unacceptable. Also stop the underlying callback source when consumption terminates. Bounding memory is useful only if the lost-data and cleanup behavior matches the contract.

83. How would you prevent duplicate asynchronous work in an actor cache?

I would distinguish a completed cache entry from an in-flight request and define whether callers should share that request. Without an explicit in-flight state, several callers can all miss the cache while the first lookup is suspended.

Store an appropriately managed task or request state where the design warrants it, then define who cancels it, how failures clear it and whether old results can replace newer data. Sharing work changes lifetime and cancellation semantics. A caller losing interest should not accidentally cancel useful work for every other caller unless that is the intended policy.

84. How would you diagnose cancellation that appears ineffective?

I would check whether the operation observes cancellation and whether its dependencies support it. Swift cancellation is cooperative; setting a task’s cancellation state does not forcibly stop arbitrary synchronous work or undo completed side effects.

A CPU-intensive loop may need deliberate checks, while a wrapped legacy API may need an explicit cancellation bridge. Distinguish stopping future work from compensating an action already accepted remotely. Test cancellation before work starts, during suspension and just before publication, so a canceled screen does not still display an obsolete result.

85. How would you decide who owns an asynchronous task’s lifetime?

I would identify the scope that needs the result and what should happen when that scope ends. Prefer structured child work when its lifetime belongs to the enclosing operation; use unstructured tasks only with an explicit owner and cleanup policy.

A view model that starts a long-lived observation task should know when to cancel it and release related resources. Simply discarding the handle does not cancel the task. Conversely, canceling on every short-lived UI transition may interrupt work that belongs to an application service. Ownership follows the requirement, not whichever object conveniently launches the task.

86. Why can a task-group timeout return later than its deadline?

A common timeout design races an operation against a sleeping child task, then cancels the losing child. Structured concurrency still requires the group to wait for its children to finish before leaving the scope. Cancellation is cooperative, so an operation that ignores it can keep the group waiting even after the timer wins.

I would distinguish a deadline for accepting a result from a guarantee that the caller returns by that time. Verify that the underlying API supports cancellation and bridge it correctly; test an operation that deliberately ignores the signal. Moving the operation into an unstructured task can change who waits, but leaves work alive that needs an owner, cleanup and stale-result suppression. It does not safely kill blocking code or undo an already accepted external request.

87. How would you diagnose UI hangs in code marked async?

I would identify where CPU-bound or blocking work actually executes. Async allows suspension; it does not promise that a function’s synchronous work runs away from the main actor.

A large parse performed before an await can still monopolize the UI execution context. Inspect isolation annotations and relevant language features, then move appropriate work using an explicit supported mechanism and safe inputs. The behavior of nonisolated async code can depend on adopted Swift concurrency features, so state the toolchain and settings rather than relying on an old universal rule.

88. How would you introduce bounded concurrency?

I would limit the number of in-flight operations according to downstream capacity and resource costs, rather than create one task for every input immediately. Structured tasks provide lifecycle management, but do not automatically select an appropriate business concurrency limit.

For a large image batch, keep a bounded working set and admit new work as earlier tasks complete. Preserve result identity if completion order differs from input order. Test cancellation and one failing operation so the limiter does not leave waiting work stranded. The useful limit depends on memory, CPU and service constraints, not only processor count.

89. How would you wrap a callback API with a continuation safely?

I would map every completion path to exactly one continuation resumption, including errors and cancellation races. A continuation is a bridge for suspending and resuming work, not a mechanism that makes an unreliable callback contract correct.

A callback that can fire twice or never fire needs an explicit state machine and synchronization appropriate to its execution context. Checked continuations help diagnose misuse but do not invent a missing result. Keep the bridge small and test simultaneous completion and cancellation; do not silence the problem by switching to an unchecked continuation.

90. How would you migrate a large project toward Swift 6 concurrency checking?

I would inventory shared mutable state and module boundaries, enable relevant diagnostics incrementally and fix ownership and isolation deliberately. Compiler version and selected language mode are separate: installing a newer compiler does not by itself establish Swift 6 language-mode checking.

Migrate in manageable target-sized steps with tests around cross-module behavior. Prioritize real shared-state designs over blanket annotations that merely quiet warnings. Interoperability and unsafe escape hatches still deserve review. A clean build supports data-race safety within the checked model; it does not prove correct business ordering, cancellation or external-system behavior.

91. How should default actor isolation affect a Swift migration plan?

I would record the target’s default-isolation configuration alongside explicit annotations and upcoming-feature settings. Newer Swift toolchains can support main-actor default isolation, but it is a setting to understand, not a universal description of all Swift code.

A helper type that previously crossed isolation boundaries freely may acquire different constraints under a new target configuration. Review reusable library boundaries separately from UI code and test the intended API from representative callers. Do not copy annotations from a project with different defaults and assume they express the same contract.

92. When is @unchecked Sendable an appropriate choice?

Only when the implementation can uphold the required concurrency safety and that reasoning is documented and maintained. The annotation shifts responsibility from compiler verification to the author; it does not add synchronization.

A reference type protecting every relevant access with a correct synchronization protocol may justify it in a constrained design. A mutable class with unsynchronized properties does not become safe by adding the conformance. Review aliases, callbacks and subclassing assumptions, then test relevant races while recognizing that stress tests cannot prove every interleaving safe.

93. How would you design an API that transfers data between isolation domains?

I would prefer a clear value or ownership-transfer boundary and specify what the receiver may retain or mutate. The API should expose the information needed for the operation without sharing a mutable object graph unnecessarily.

For example, send a request snapshot containing identifiers and immutable parameters rather than a UI controller. Depending on the toolchain, supported transfer features can express more precise ownership, but their semantics must be checked for the selected language configuration. Avoid using broad unchecked annotations to make an oversized boundary compile.

94. How would you handle a protocol whose isolation requirements do not fit its implementation?

I would examine the protocol’s intended callers and decide whether the contract should be actor-isolated, asynchronous or based on safely accessible immutable data. A conformance diagnostic can reveal a genuine design mismatch.

A synchronous requirement callable anywhere cannot casually read main-actor mutable state. Where appropriate, adapt through a snapshot or revise the protocol boundary; do not simply remove isolation from the implementation. Public protocol changes affect clients, so consider compatibility and the installed compiler’s supported conformance features before selecting the migration approach.

95. How would you diagnose a task that keeps an object alive unexpectedly?

I would inspect the ownership graph, including closures, task handles and long-lived asynchronous sequences. A task retaining an object that stores the task can create a lifetime problem even without a traditional delegate cycle.

Weakly capturing self at creation may not help if the closure immediately promotes it to a strong reference for an indefinitely running operation. Define an explicit stop path and determine whether the task should belong to a different owner. Verify deallocation after cancellation and completion rather than assuming one capture-list change solves every lifetime pattern.

96. How would you diagnose surprising retention in nested closures?

I would inspect each closure’s capture and lifetime independently. A weak capture in an inner closure does not prove that an outer stored closure avoids retaining the same object; the outer closure may retain what it needs to construct the inner one.

For example, an object can store a callback that later creates a task with a weak capture. If the stored callback already keeps the object alive, that inner capture does not solve the ownership cycle. Trace the actual references, decide which owner should retain each closure and verify release after the callback is removed or its work ends. Avoid adding weak everywhere without defining what should happen when the owner disappears.

97. How would you distinguish a memory leak from legitimate retention?

I would observe repeated workloads and inspect which objects remain reachable after their intended lifetime, separating caches and pending tasks from unintended ownership. A rising resident-memory graph alone does not identify a retain cycle.

A cache that reaches its configured capacity may be operating normally, while one retained screen per navigation cycle suggests a lifecycle defect. Use memory-graph and allocation evidence in the relevant environment, then test the expected release boundary. Fix ownership or eviction policy rather than add weak references indiscriminately and risk losing required state.

98. How would you diagnose unexpectedly expensive mutations of a collection?

I would inspect value sharing, mutation patterns, element behavior and bridging before assuming the collection operation is intrinsically slow. Copy-on-write can defer copying until mutation, so a seemingly cheap assignment can shift cost to a later write.

Keeping snapshots of a large array while repeatedly mutating copies may trigger substantial copying. Confirm the pattern with a release-build profile and consider a different ownership or batching design. Value semantics describe observable behavior, not a promise that storage is copied immediately or that every operation has the same allocation cost.

99. How would you keep Hashable identity stable in a mutable domain model?

I would define equality and hashing around a stable identity when the object represents a persistent entity, rather than include mutable display or status fields that can change while it is used as a key. Equal values must produce compatible hashes, and a collection key must retain the required equality and hashing behavior while stored.

A customer object used in a Set can become difficult to find if changing its name also changes its hash. Prefer an immutable identifier as the key and keep mutable attributes in the associated value, or remove and reinsert according to a carefully defined value model. Never persist hashValue as an external identifier: hashing is an implementation facility, not a durable business identity.

Swift example: stable key, mutable associated value The identifier remains unchanged while the customer’s display name changes. This fixture checks lookup behavior, not persistent hash values.

struct CustomerID: Hashable { let rawValue: Int }
struct Customer { var name: String }
let id = CustomerID(rawValue: 7)
var customers = [id: Customer(name: "Before")]
customers[id]?.name = "After"
precondition(customers[id]?.name == "After")
precondition(customers.count == 1)
struct CustomerID: Hashable { let rawValue: Int }
struct Customer { var name: String }
let id = CustomerID(rawValue: 7)
var customers = [id: Customer(name: "Before")]
customers[id]?.name = "After"
precondition(customers[id]?.name == "After")
precondition(customers.count == 1)
struct CustomerID: Hashable { let rawValue: Int }
struct Customer { var name: String }
let id = CustomerID(rawValue: 7)
var customers = [id: Customer(name: "Before")]
customers[id]?.name = "After"
precondition(customers[id]?.name == "After")
precondition(customers.count == 1)

100. How would you evolve a Codable model without breaking persisted data?

I would treat the encoded representation as a versioned contract separate from the current Swift property names. Codable synthesis is convenient, but it does not design a migration policy for previously stored payloads. Explicit CodingKeys or a custom decoding implementation can preserve the external names and interpret older representations where required.

If displayName replaces an older encoded name key, renaming the Swift property alone should not be assumed to preserve compatibility. Define how missing, null and malformed values are handled and whether an older payload needs migration before constructing the current model. Keep fixtures from supported historical versions, test them with the new decoder and verify new output with any older reader that must remain supported. A successful encode/decode round trip using only the new type cannot establish backward compatibility.

101. How would you respond to an exclusivity violation?

I would identify overlapping accesses to the same storage and restructure the operation so mutation has the required exclusive access. Swift can diagnose some conflicts at compile time and others at runtime.

Passing a value as inout while a closure or another argument also accesses that storage can violate the rule even on one thread. Use a local snapshot or split the operation where that matches the intended semantics. Do not treat the issue as only a multithreading race or disable checks to preserve an unclear aliasing design.

102. How would you optimize Swift code without weakening correctness?

I would profile a representative release build and identify the expensive operation before changing representation or ownership. Performance assumptions from a debug build can mislead because optimization and checking differ.

If bridging or repeated allocation dominates, changing an algorithm may matter more than a low-level annotation. Preserve output and lifetime tests, then compare realistic distributions and error paths. Unsafe memory or unchecked concurrency should require a specific justified design, not be the default response to a slow benchmark.

103. When would noncopyable types improve an API design?

They can express that a value represents a resource whose ownership should not be duplicated implicitly, where supported by the target toolchain and generic constraints. The goal is a clearer resource contract, not a universal replacement for ordinary value types.

A unique handle may benefit from explicit consuming operations and a defined release path. Consider how clients store, transfer and test the value before adopting the design. Language support and interoperability evolve, so check actual compiler capabilities. Noncopyability alone does not establish that a resource is safe to use concurrently or that every external failure is handled.

104. How would you review unsafe-pointer code at a C boundary?

I would verify the pointer’s lifetime, initialization, binding, bounds and ownership against the C API’s exact contract. A pointer valid inside a closure is not necessarily valid after that closure returns.

If C retains a buffer or callback context, temporary Swift storage cannot simply be passed and forgotten. Define the allocation and release owner and handle error paths. Keep the unsafe boundary narrow, expose a safer Swift interface and use targeted tests. Successful execution on one input does not prove that a dangling pointer or layout assumption is valid.

105. How would you design an autoclosure API without hiding important work?

An @autoclosure parameter wraps a caller expression in a closure, allowing the callee to defer evaluation even though the call site looks like an ordinary value argument. I use it only when the API name and contract make that laziness clear. It does not inherently memoize the result or promise exactly one evaluation.

A diagnostic-message API can avoid constructing an expensive message when logging is disabled. It should document whether the expression is evaluated at all and whether it can run more than once; a caller should not hide a required state change inside that expression. If the API stores the closure, the escaping and capture lifetimes also become part of the contract. Prefer an explicit closure when the delayed work is consequential, so the call site shows that behavior instead of disguising it as a simple value.

106. How would you design partial-failure semantics for a batch API?

I would decide whether the batch is one atomic operation or a collection of independent operations and make the result contract reflect that decision. A single thrown error can be insufficient when some items have already succeeded and cannot be rolled back.

For an upload batch, return stable item identities with accepted, rejected or uncertain outcomes where appropriate, and distinguish batch-level setup failure from item failure. Cancellation should state what may already have completed. A caller needs enough information to retry safely without duplicating accepted work. Do not imply that a throwing Swift function automatically reverses external side effects performed before the error.

107. How would you make a retrying asynchronous API safe?

I would define which failures are retryable, whether the operation is idempotent and how cancellation and deadlines apply across attempts. Retrying a failed read differs from repeating a request with an uncertain external side effect.

A timeout after remote acceptance may require reconciliation instead of a new operation. Bound attempts and waiting according to the caller’s lifetime, and preserve a stable operation identity where the service supports it. A generic catch-and-retry loop cannot infer those business guarantees from the Swift Error value alone.

108. How would you test actor reentrancy deterministically?

I would control the dependency that suspends so the test can pause one operation, perform a conflicting state change and then resume the first operation. This exercises the invariant at a known boundary.

For a search model, complete the newer response before the older response and verify that the old result does not replace current state. Avoid relying only on arbitrary sleeps, which can pass without producing the intended interleaving. Such a test checks the modeled sequence; it does not prove all concurrency behavior or replace reasoning about the protocol.

109. How would you test cancellation and cleanup?

I would verify the observable contract at several cancellation points, including whether work stops, resources are released and stale results are suppressed. Cancellation tests need a controllable dependency and a clear completion signal.

Cancel before a request starts, while it is suspended and near result delivery. Check that cleanup runs exactly as required and does not cause duplicate completion. Do not assume canceling a task instantly terminates a legacy operation. Test its bridge separately and document cases where the external side effect cannot be undone.

110. How would you keep asynchronous tests from becoming flaky?

I would coordinate on meaningful events rather than elapsed wall-clock guesses, inject time or dependencies where appropriate and avoid shared mutable test state. Test isolation matters especially when the framework runs cases concurrently.

A test waiting for a callback should observe a controlled signal and a bounded failure timeout, not assume that a fixed sleep is long enough. Preserve diagnostic context when a timeout occurs. Different test frameworks and toolchains offer different APIs, so match the implementation to the project rather than mixing XCTest and Swift Testing conventions without checking.

111. How would you assess protocol-conformance evolution and retroactive conflicts?

I would examine who owns the type and protocol and whether the conformance is part of the public contract. A retroactive conformance for a foreign type and foreign protocol can conflict if another module or a later dependency release supplies its own conformance.

For example, an application-specific serialization interpretation for a library type may be safer behind a wrapper owned by the application. An acknowledgment attribute supported by newer Swift versions does not make competing conformances harmless. When evolving a protocol, review existing conformers and clients as well as default implementations; adding a requirement or changing behavior needs compatibility analysis under the actual distribution model and toolchain.

112. How would you review a public API for future evolution?

I would examine exposed types, invariants, error behavior and concurrency annotations as contracts clients can depend on. Reducing accidental public surface preserves room to change implementation.

A public mutable property may let clients construct states the library cannot safely support later. Prefer deliberate operations where they clarify valid transitions. For separately distributed binary libraries, source compatibility, ABI compatibility and module stability are distinct concerns. Review the actual distribution model rather than assuming ordinary source-package versioning provides every binary-evolution guarantee.

113. When would you enable library evolution support?

I would consider it for a binary framework intended to evolve separately from clients while preserving supported binary compatibility. It is not automatically necessary for code always built and shipped together.

Library evolution introduces resilience choices and can affect optimization and public contracts. Plan it before distributing a stable binary interface rather than treating it as a late packaging toggle. Verify supported platforms and toolchains. Module stability helps compiler-version interoperability, while library evolution concerns compatible library changes; neither means every arbitrary API change becomes safe.

114. What risk does @inlinable introduce in a library?

It exposes implementation details for use by client compilation and can make referenced declarations part of a wider compatibility commitment. The optimization opportunity must be weighed against the ability to change internals later.

A helper referenced by an inlinable body may need an appropriate visibility annotation and cannot be treated as freely removable merely because it is not source-public. Apply the attribute to measured hot paths with a clear evolution plan. It does not promise that the compiler will inline every call, so avoid exporting implementation solely as a speculative speed improvement.

115. How would you evolve an enum used by external clients?

I would consider the distribution model and the promises made about possible cases. Exhaustive switching is useful, but clients need an appropriate strategy for future cases where the library’s contract permits them.

A frozen public enum in a library-evolution context commits to its case set and representation constraints. Do not add such a promise casually to silence a diagnostic. For a resilient API, document meaningful fallback behavior rather than silently map unknown cases to success. Source and binary compatibility need separate review for the actual release.

116. How would you manage Swift package dependency upgrades?

I would inspect the dependency change, toolchain requirements and affected public or runtime behavior, then test the consuming application rather than only the package in isolation. Reproducible resolution and approved versions matter for release evidence.

A dependency can change concurrency annotations or minimum platform support without altering the call sites that first appear relevant. Review those boundaries and retain a compatible rollback plan. A successful build is not evidence that behavior, performance or binary distribution assumptions remain unchanged. Avoid uncontrolled upgrades while diagnosing an unrelated production issue.

117. How would you handle Objective-C interoperability without losing Swift safety?

I would review the imported API’s nullability, ownership, threading and callback contracts rather than assume Swift can infer guarantees the foreign interface does not state. Add a focused adapter where it can express the intended contract more clearly.

An Objective-C callback may arrive on an unspecified queue or expose mutable state outside Swift’s checking. Validate the required isolation and lifetime handling at that boundary. Optional bridging and annotations help, but they do not correct an implementation that violates its contract. Keep platform-specific behavior explicit instead of generalizing it to every Swift environment.

118. How would you review AI-generated Swift code?

I would verify the target toolchain, language mode, platform availability and ownership and isolation assumptions before accepting the implementation. Plausible annotations can hide an incorrect concurrency design.

Generated code may use Task.detached to evade an isolation error, capture self indefinitely or assume a newer API exists in the deployment target. Test a safe minimal case and inspect cancellation, repeated calls and failure paths. Compiler success is useful evidence but does not validate business invariants, foreign-code contracts or every unsafe escape hatch.

119. What should a concurrency-focused Swift code review examine?

It should identify who owns mutable state, where suspension can invalidate assumptions, how tasks end and what crosses isolation boundaries. Follow the operation through success, cancellation and failure rather than reviewing annotations in isolation.

For example, a screen refresh may be data-race-free but still publish responses in the wrong order or retain its owner forever. Require a clear invariant and a controllable test for the important boundary. Record any unchecked or foreign-code assumptions, and match the review to the target’s language and isolation settings.

120. What demonstrates senior Swift judgment?

A senior engineer connects language guarantees with lifetime, business ordering, performance and interoperability limits. They distinguish a data race from a logical race and a convenient annotation from a defensible design.

When a UI shows old data, they inspect suspension and request identity; when memory grows, they trace ownership instead of adding weak everywhere. They use representative evidence and narrowly scoped tests, then explain what remains unverified. Reliable Swift code comes from clear contracts and failure handling as well as compiler assistance.

Swift Documentation and Further Reading

These official Swift and Apple references cover the language and its concurrency model. Use documentation and compiler settings appropriate to the project, particularly when migrating language modes.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts