Swift concurrency & memory

async/await, actors, Task lifecycle, and ARC with weak/unowned to avoid retain cycles. Retain-cycle diagnosis is a classic live iOS question.

About 22 min read3-question knowledge check

The mental model

Swift concurrency and Kotlin coroutines are the same idea in two dialects: keep slow work off the one thread that draws, express asynchronous code as if it were sequential, and tie every unit of work to a scope that cancels it automatically. If you understand viewModelScope and withContext, you already understand Task and await — the keywords differ, the model does not.

Two things make Swift's version distinctive, and both are heavily probed in iOS interviews.

**First, the actor.** An actor is a type that protects its own mutable state by allowing only one task inside it at a time. Where other languages hand you locks and hope you use them, Swift makes the compiler enforce it: you cannot touch an actor's mutable state from outside without await, and inside, access is serialized. @MainActor is the special actor that *is* the main thread — mark a type or function @MainActor and the compiler guarantees its code runs on the main thread, so UI updates are correct by construction, not by convention.

**Second, memory is automatic, but cycles are your job.** Swift uses **ARC** (Automatic Reference Counting), not a tracing garbage collector. Every strong reference bumps a count; when the count hits zero, the object is freed — deterministically, immediately. The failure mode ARC cannot solve on its own is the **retain cycle**: object A strongly holds B, B strongly holds A, so neither count ever reaches zero and both leak forever. This is *the* classic live iOS interview question — "here's a closure capturing self; find the leak" — and the fix is weak/unowned to break the cycle. Coroutines/GC languages rarely make you think about this; Swift makes it a daily discipline.

The unifying idea: **structured concurrency binds the *lifetime* of work to a scope, and ARC binds the *lifetime* of memory to reference counts — and the bugs in each are lifetime bugs.** A Task that outlives its screen leaks work; a closure that strongly captures self in a stored property leaks memory. Master both lifetimes and the two hardest iOS interview topics — cancellation and retain cycles — become routine.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision