Skip to content
Tutorials Center
My learning

Topics

Lesson 144 of 146 ยท Practice

Swift Interview Questions

Prepare for a Swift interview with 40 questions and clear answers on optionals, value types, protocols, generics, ARC, error handling and concurrency, with runnable code.

Interviewers rarely want a definition recited word for word. They want to hear that you understand why Swift works the way it does: why optionals exist, why structs are the default, why a closure can leak memory, why Swift 6 rejects a harmless-looking global variable. This lesson collects 40 questions in the order a typical interview follows, from language basics through memory and concurrency, with answers short enough to say out loud.

Read each question, answer it in your own words first, and only then read the answer. Where a short experiment makes the answer stick, there is a runnable example. The examples use Swift 6 language mode and an optimized build, so a few crashes here print no message at all. The notes say so where it matters.

A good interview answer has three parts: the rule ("a struct is copied on assignment"), a consequence ("so changing one copy does not affect the other") and a trade-off or example ("I use a class when I need shared identity"). Practice giving all three.

Language basics

1. What is the difference between let and var?

let declares a constant that cannot be reassigned after it is set. var declares a variable that can. Prefer let by default: the compiler then proves the value never changes, which makes code easier to reason about. For a value type such as a struct or array, let also makes the contents immutable. For a class instance, let only fixes the reference; the object's var properties can still change. See constants and variables.

2. What is type inference, and does it make Swift dynamically typed?

No. Swift is statically typed: every value has one type known at compile time. Inference lets the compiler work that type out from the right-hand side, so let n = 42 is an Int and let pi = 3.14 is a Double. You can still annotate (let n: Int64 = 42) when the default is not what you want.

3. Why does Swift refuse to add an Int and a Double?

There are no implicit numeric conversions. Silent conversions lose precision or hide bugs, so you convert explicitly: Double(count) / 2. Literals are flexible (2 can be a Double when the context needs one), but typed values are not. See basic types.

4. What happens on integer overflow?

Plain operators trap: the program crashes instead of wrapping around silently. If you want wrap-around, use the overflow operators (&+, &-, &*). If you want to detect overflow, use addingReportingOverflow and its relatives.

Swift let, var, copies and overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that b is an independent copy of a, so appending to b leaves a alone. Question 13 returns to that.

5. What is the difference between String and Character, and why can't you index a string with an integer?

A String is a collection of Character values, and a Character is one extended grapheme cluster: what a person sees as a single symbol, which may be several Unicode scalars (an "e" plus an accent, a flag, a family emoji). Because characters have different sizes in memory, finding the nth one means walking the string, so Swift makes that cost visible with String.Index instead of offering s[3]. See strings.

6. What does switch offer that if chains do not?

A switch must be exhaustive: the compiler rejects it if a possible value is not covered, and for enums it reports the missing cases. It also supports ranges, tuples, where clauses and value-binding patterns, and cases do not fall through by default. Adding a case to an enum therefore turns every non-exhaustive switch into a compile error, which is exactly what you want. See switch and pattern matching.

Swift Mutating a let constant (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: cannot use mutating member on immutable value: 'numbers' is a 'let' constant and suggests changing let to var. Appending to copy is fine because that one is a var. A compile-time error like this is cheaper than any runtime bug.

Optionals

7. What is an optional, really?

An optional is an ordinary enum with two cases: .none (written nil) and .some(Wrapped). Int? is shorthand for Optional<Int>. The point is that the type system tells you which values may be absent, so a plain Int can never be nil, and you cannot use an Int? as an Int without handling the missing case. See optionals.

8. List the ways to unwrap an optional and say when you would use each.

  • Optional binding (if let, guard let): the default; use the value inside the branch or after the guard.
  • Nil-coalescing (??): supply a fallback value.
  • Optional chaining (a?.b?.c): call or read through optionals, getting an optional back.
  • map / flatMap: transform the value only if present.
  • Force unwrap (!): only when nil would mean a bug in your program.

9. When is a force unwrap acceptable?

When you have just established the value exists in a way the compiler cannot see, and a failure means a programming mistake. Examples are a hard-coded URL literal in a test, or a value you set a line earlier. For anything that comes from input, files or the network it is not acceptable: use guard let and report an error.

10. What is the difference between compactMap and map on an array of optionals?

map keeps whatever the closure returns, so a closure returning Int? gives [Int?] with nil entries. compactMap drops the nil values and unwraps the rest, giving [Int].

guard checks a condition and requires the else block to leave the scope (return, throw, continue, break or a call that returns Never). Bindings made by guard let stay available after the guard, so the happy path stays unindented instead of nesting inside many if let blocks. See guard and early exit.

12. What is an implicitly unwrapped optional?

A type written T! is an optional that is unwrapped automatically when used as a non-optional, and traps if it is nil. It exists for two-phase setup, mainly interface-builder outlets, where a value is guaranteed to be set before first use but not at initialization. In new code prefer a real optional or a non-optional set in the initializer.

Swift Safe unwrapping in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The last two lines show question 10 directly: [1, 3] against [Optional(1), nil, Optional(3)].

Swift Force unwrapping nil (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

looking up Bob is printed, then the program dies with SIGILL and a backtrace. In this optimized build there is no message text; a debug build would print Fatal error: Unexpectedly found nil while unwrapping an Optional value. Either way it cannot be caught, which is why ! is reserved for real bugs.

Value and reference types

13. What is the difference between a struct and a class?

Structs (and enums, tuples, arrays, strings) are value types: assigning or passing one creates an independent copy. Classes are reference types: assignment copies the reference, so two names refer to the same object. Classes also add inheritance, deinit, identity (===) and reference counting. Structs get a free memberwise initializer and automatic Equatable/Hashable synthesis when you ask for it. See structures, classes and value vs. reference semantics.

Swift Value copy versus shared reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

14. When would you choose a class over a struct?

Choose a class when you need shared, mutable identity (one object many parts of the program observe), inheritance from a class-based framework, or a deinit that releases a resource. Otherwise start with a struct; it is simpler to reason about and avoids accidental sharing. Use an actor when shared mutable state is touched from several tasks.

15. What is copy-on-write?

Standard library collections such as Array, Dictionary and String store their data in a heap buffer. Copying the value copies only a reference to that buffer, and the real copy is made lazily, when one of the copies is first mutated and the buffer is shared. You get value semantics at close to reference cost. Your own struct does not get this for free: you implement it with isKnownUniquelyReferenced around a class-based buffer.

16. What does mutating mean?

A struct method that changes the struct's own properties must be marked mutating, because it effectively replaces self. You cannot call it on a let constant. Classes have no such keyword, since a method on a reference can always change the object.

17. What is the difference between == and ===?

== is equality through Equatable: do these two values count as the same? === is identity and works only on class instances: are these two references the very same object? Two different User objects can be equal and still not identical.

18. How do you make a custom type usable as a dictionary key or set member?

Conform it to Hashable. If all stored properties are Hashable, the compiler synthesizes the conformance for you. Implement == and hash(into:) yourself only when equality should ignore some properties; just make sure equal values always produce the same hash. See Equatable, Hashable and Comparable.

Protocols and generics

19. What is protocol-oriented programming?

You describe capabilities with protocols, supply default behavior in protocol extensions, and compose value types that conform, instead of building deep class hierarchies. It works with structs and enums, which classes-only inheritance cannot. See protocols and protocol extensions.

20. What is the difference between static and dynamic dispatch with protocol extensions?

Methods that are requirements of the protocol are dispatched dynamically: calling through a protocol-typed value uses the conforming type's own implementation. Methods that exist only in an extension are dispatched statically, by the type the compiler sees. That surprises many people.

Swift A requirement versus an extension-only method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

greet is a requirement, so both lines print hello from Loud. shout is extension-only, so the call through any Greeter prints the extension version. The last two lines preview questions 21 and 22.

21. What is the difference between some Protocol and any Protocol?

some P is an opaque type: one specific concrete type, chosen by the implementation and hidden from the caller. It is resolved at compile time, so it is fast and keeps type information. any P is an existential: a box that can hold any conforming type at run time, which costs an indirection and loses details such as associated types. Prefer some (or a generic) in parameters and return values, and use any for heterogeneous collections. See opaque and existential types.

22. What is a generic constraint, and why use one?

func largest<T: Comparable>(_ items: [T]) -> T? says "any type, as long as it can be compared". The constraint lets the body use < and max(), while the compiler still creates a fast specialized version per type. A where clause expresses richer rules, such as where T.Element: Equatable. See generic functions and generics.

23. What are associated types?

A protocol can declare a placeholder type with associatedtype, which each conforming type fixes. Sequence has Element; Collection adds Index. Primary associated types let you write some Collection<Int> or any Sequence<String>. See associated types.

24. What is conditional conformance?

A generic type conforms to a protocol only when its type arguments do. Array is Equatable when Element is Equatable, so [1, 2] == [1, 2] compiles but an array of non-equatable values cannot be compared. See conditional conformance.

25. What is a noncopyable type?

A type marked ~Copyable cannot be duplicated: it has a single owner, and passing it consumes it unless you borrow it. It models resources such as file handles or locks, where copying would be a bug, and gives a deterministic deinit. See noncopyable types.

Memory and ARC

26. How does Swift manage memory?

With Automatic Reference Counting. Each class instance has a count of strong references; the compiler inserts retain and release operations, and when the count reaches zero the object is deinitialized immediately. There is no garbage collector pausing the program, so deinit runs at a predictable moment. Value types need no counting for themselves. See memory management with ARC.

27. What is a retain cycle and how do you break one?

If two objects hold strong references to each other (or an object holds a closure that captures it), neither count reaches zero and both leak. Make one direction weak (an optional that becomes nil when the target is freed) or unowned (a non-optional that traps if used after the target is gone). The "child points to parent" link is the usual weak one.

Swift weak references and deinit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both objects are freed as soon as scope() returns, because pet.owner is weak. Make owner strong and the two deinit lines never print. In Counter, the closure captures self weakly, so the object is freed after run().

28. weak or unowned: how do you decide?

Use weak when the other object may legitimately disappear first; you handle the nil. Use unowned only when you can guarantee the other object outlives this one, such as a child that cannot exist without its parent; a mistake becomes a crash. When in doubt, choose weak.

29. When does a closure capture self strongly, and what is a capture list?

An escaping closure that mentions self (or a property of it) keeps the object alive for as long as the closure lives. A capture list, [weak self] or [unowned self], changes how the closure holds it. Non-escaping closures run immediately and cannot leak, so they need no list. See escaping closures and autoclosures.

30. Do value types have memory-management problems?

Not cycles, but there are costs. A struct that contains class references still shares those objects between copies. Large structs are copied more than you might think, though copy-on-write collections soften this. And a closure stored in a struct can still capture a class instance and create a cycle.

Error handling

31. How does error handling work in Swift?

Functions that can fail are marked throws; they throw a value conforming to Error. Callers must acknowledge the possibility: try inside a do/catch, try? to turn failure into nil, or try! to assert there is none. Errors propagate through the call stack as ordinary return values, without the cost of C++-style unwinding. See error handling.

32. What are typed throws?

Since Swift 6 a function can declare the exact error type it throws: throws(ParseError). Callers then get a precisely typed error in their catch and need no cast. Untyped throws stays the default for most APIs, because it keeps room for new failure modes. See typed throws.

Swift Typed throws and try?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

33. When do you use Result instead of throws?

When the outcome needs to be stored or passed around as a value: a callback API, a collection of outcomes, a property. throws is better for straight-line code. You can convert in both directions with Result { try ... } and .get(). See the Result type.

34. What is the difference between an error and a precondition failure?

Errors are expected failures a caller can handle. precondition, fatalError, a failed force unwrap and an out-of-range index are bugs, and they stop the program. assert does so in debug builds only. Never crash on input from users or the network. See assertions and preconditions.

Concurrency

35. What problem does async/await solve?

It lets you write asynchronous code in straight lines. An async function can suspend at each await, freeing its thread for other work, and resume later, so you avoid callback pyramids and manual thread management. await marks every possible suspension point, which makes them visible when you read the code. See async and await.

36. What is structured concurrency?

Child tasks live inside a scope, and the scope does not finish until its children do. async let and task groups create child tasks that are cancelled and awaited automatically if the parent is cancelled or throws. That prevents leaked background work. Unstructured Task { } and Task.detached escape this model, so use them sparingly. See tasks and task groups.

37. What is an actor?

A reference type that protects its mutable state by running one operation at a time. Outside code must await to call its methods, and the compiler checks that you do. Because an actor can suspend inside a method, other calls may run in between (reentrancy), so never assume state is unchanged across an await. See actors.

Swift An actor, a task group and async let

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

One hundred concurrent increments always give exactly 100, because the actor serializes them. The two async let calls run concurrently and print 25. The concurrency code lives in a function on purpose: with this compiler version, async let directly inside a top-level do/catch crashes swiftc.

38. What is Sendable?

A marker protocol for types that are safe to pass between concurrency domains: value types made of sendable parts, immutable classes, actors, and types that guard their own state. In Swift 6 mode the compiler checks it, so sharing a non-sendable value across tasks is an error rather than a data race. See Sendable and data races.

39. What does @MainActor mean, and why does Swift 6 reject a plain global var used from a task?

@MainActor isolates code and data to the main actor, the one that runs UI work. In a main.swift file, top-level variables are implicitly main-actor isolated in Swift 6. A Task { } closure is not on the main actor, so it may not mutate them, and the compiler says so instead of letting a race happen.

Swift Mutating a global from a Task (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error is main actor-isolated var 'total' can not be mutated from a nonisolated context. The fixes, in order of preference: keep the state inside an actor, annotate the task closure with @MainActor, or protect the value with a Mutex. See synchronization and shared state.

40. How does cancellation work?

It is cooperative. Cancelling a task only sets a flag; the running code must look at it, with try Task.checkCancellation() or Task.isCancelled, and many suspending calls such as Task.sleep do this for you by throwing CancellationError. Cancellation flows down from a parent to its child tasks. Clean up in defer so cancelled paths release their resources. See cancellation and timeouts.

If you are asked about DispatchQueue, Thread and locks, say they still work and are common in older code, but that new code prefers actors, tasks and Mutex. See threads and dispatch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you force-unwrap an optional that is nil?

    A failed force unwrap is a trap. You cannot catch it, which is why it is for situations where nil means a bug.
  2. 2. Given let a = Box() where Box is a class, then let b = a, what do a and b share?

    Classes are reference types. Assignment copies the reference, so both names point to one instance.
  3. 3. A method exists only in a protocol extension, not as a requirement. Called through any Proto, which implementation runs?

    Extension-only methods are dispatched statically by the type the compiler sees. Only protocol requirements use the conforming type's implementation.
  4. 4. Why is Owner.pet strong and Pet.owner weak in a parent and child relationship?

    Two strong references pointing at each other keep both counts above zero. One weak side breaks the cycle.
  5. 5. Why does await counter.increment() need await when counter is an actor?

    An actor runs one operation at a time. A call from outside may suspend until the actor is free, so Swift marks that point with await.

Summary

  • Know the rule, the consequence and a trade-off for each answer; explain why Swift is designed this way.
  • Optionals make absence part of the type; unwrap with binding, ??, chaining and map, and keep ! for real bugs.
  • Prefer structs and enums; use classes for shared identity, and actor for shared mutable state across tasks.
  • Protocol requirements dispatch dynamically, extension-only methods statically; some is opaque and fast, any is a flexible box.
  • ARC frees objects when the strong count hits zero; break cycles with weak or unowned, and watch closure captures.
  • Errors are for expected failures, preconditions and traps for bugs; typed throws give precise catch types.
  • Swift 6 concurrency is checked at compile time: tasks and actors, Sendable, main-actor isolation and cooperative cancellation.

That is the end of the Swift tutorial. Revisit the cheat sheet and common mistakes before an interview, and rebuild one of the projects from scratch to prove to yourself that it all fits together.