<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akanksha Singh on Medium]]></title>
        <description><![CDATA[Stories by Akanksha Singh on Medium]]></description>
        <link>https://medium.com/@aksingh20feb?source=rss-12293b6c4473------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jlb0PbBZJs5Da9Su-iTS4A.png</url>
            <title>Stories by Akanksha Singh on Medium</title>
            <link>https://medium.com/@aksingh20feb?source=rss-12293b6c4473------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:47:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aksingh20feb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift Concurrency: Actors Explained — Thread Safety, Reentrancy, and Data Isolation]]></title>
            <link>https://medium.com/@aksingh20feb/swift-concurrency-actors-explained-thread-safety-reentrancy-and-data-isolation-fd0de630ca75?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd0de630ca75</guid>
            <category><![CDATA[actors]]></category>
            <category><![CDATA[actor-in-swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 14:14:51 GMT</pubDate>
            <atom:updated>2026-07-16T07:46:20.120Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous articles, we explored how Swift Concurrency works under the hood and how async/await manages execution and suspension.</p><p><a href="https://medium.com/@aksingh20feb/swift-concurrency-architecture-explained-ee1c831b6031"><strong>Swift Concurrency Architecture Explained</strong></a></p><p><a href="https://medium.com/@aksingh20feb/swift-concurrency-async-await-how-it-really-works-suspension-points-concurrency-and-memory-0f2894d9777d"><strong>Swift Concurrency Async Await</strong></a></p><p>But execution is only half the story.</p><blockquote><em>The real challenge in concurrent programming is </em><strong><em>data safety</em></strong><em>.</em></blockquote><p>When multiple tasks run at the same time, how do you prevent them from corrupting shared data?</p><p>This is where <strong>Actors</strong> come in.</p><h3>The Problem: Data Races &amp; Shared Mutable State</h3><p>Let’s start with the real issue.</p><h4>Data Race</h4><p>A <strong>data race</strong> happens when:</p><ul><li>Multiple threads/tasks access the same memory</li><li>At least one of them modifies it</li><li>There’s no synchronization</li></ul><p><strong>Example</strong>:</p><pre>var balance = 1000<br><br>DispatchQueue.global().async {<br>    balance -= 100<br>}<br>DispatchQueue.global().async {<br>    balance -= 200<br>}</pre><p>Result? <strong>Unpredictable</strong></p><ul><li>Could be 700</li><li>Could be 800</li><li>Could even crash in complex cases</li></ul><h3>Why Shared Mutable State is Dangerous</h3><p>The problem is not concurrency itself.</p><p>It’s <strong>shared mutable state</strong>.</p><ul><li>Multiple threads → accessing same variable</li><li>No control → inconsistent data</li><li>Hard to debug → bugs are non-deterministic</li></ul><h3>Why GCD + Locks Are Painful</h3><p>Before Swift Concurrency, we used:</p><h4>Locks</h4><pre>lock.lock()<br>balance -= 100<br>lock.unlock()</pre><p>Problems:</p><ul><li>Easy to forget unlock → deadlock</li><li>Hard to scale</li><li>Error-prone</li></ul><h4>Serial Queues</h4><pre>let queue = DispatchQueue(label: &quot;bank&quot;)<br><br>queue.async {<br>    balance -= 100<br>}</pre><p>Problems:</p><ul><li>Manual control</li><li>No compiler safety</li><li>Hard to reason in large systems</li></ul><p><em>We needed something safer, simpler, and enforced by the compiler.</em></p><h3>Actor vs Mutex (Lock)</h3><p>Both Actors and mutexes solve the same fundamental problem: <strong>protecting shared mutable state</strong>. The difference lies in <strong>how</strong> they achieve it.</p><h3>Mutex (Lock)</h3><p>A mutex gives developers manual control over synchronization.</p><pre>let lock = NSLock()<br><br>lock.lock()<br>balance -= 100<br>lock.unlock()</pre><p>While this works, it comes with several challenges:</p><ul><li>You must remember to call <em>unlock</em>().</li><li>Forgetting to unlock can lead to deadlocks.</li><li>Locking the wrong section of code can cause race conditions.</li><li>The compiler cannot verify whether your locking logic is correct.</li></ul><p>The responsibility for thread safety lies entirely with the developer.</p><h3>Why Actors?</h3><p>Swift’s concurrency model doesn’t just make asynchronous code easier to write — it also aims to make concurrent code safer by design.</p><p>Instead of asking developers to manually protect shared state with locks and queues, Swift introduces <strong>Actors</strong>, a language feature that lets the compiler enforce thread safety for shared mutable data.</p><h3>What is an Actor?</h3><p>An <strong>Actor</strong> is a special reference type in Swift that:</p><ul><li>Protects its internal state</li><li>Ensures only one task accesses it at a time</li><li>Eliminates data races</li></ul><p><strong>Basic Example</strong></p><pre>actor BankAccount {<br>    var balance: Int = 1000<br><br>    func withdraw(amount: Int) {<br>        balance -= amount<br>    }<br>}</pre><p><strong>Key Properties</strong></p><ul><li>Reference type (like class)</li><li>Mutable state is protected</li><li>Access is automatically serialized</li></ul><h3>Actors are Reference Types</h3><ul><li>stored in heap</li><li>managed by ARC</li><li>shared by reference</li><li>unlike classes, mutable state is automatically protected</li><li>Shared identity</li></ul><h3>Accessing Actor</h3><pre>let account = BankAccount()<br><br>Task {<br>    await account.withdraw(amount: 100)<br>}</pre><p>Notice <em>await</em></p><p>This tells us:</p><p><strong><em>Access to actor state may suspend and is controlled by the runtime</em></strong></p><h3>Why await is needed</h3><pre>let account = BankAccount()<br><br>Task {<br>    await account.withdraw(amount: 100)<br>}</pre><p>The <em>await </em>isn’t because <em>withdraw() </em>is asynchronous.</p><p>It’s because the actor may already be executing another task.</p><h3>Actor Isolation</h3><p>This is the most important concept to understand.</p><h4>What is Actor Isolation?</h4><ul><li>All stored properties inside an actor are <strong>isolated</strong></li><li>They cannot be accessed directly from outside</li></ul><h4>Not Allowed</h4><pre>let account = BankAccount()<br>print(account.balance) // Error</pre><h4>Correct Way</h4><pre>actor BankAccount {<br>    var balance: Int = 1000<br><br>    func getBalance() -&gt; Int {<br>        return balance<br>    }<br>}<br>let balance = await account.getBalance()</pre><h4>Why?</h4><p>Because Swift ensures:</p><blockquote><em>Only one task can access actor state at a time</em></blockquote><h4>Important Behavior</h4><ul><li>Inside the actor → synchronous access</li><li>Outside the actor → requires <em>await</em></li></ul><h4>Mental Model</h4><p>Think of an actor as:</p><blockquote><em>“A protected box where only one task can enter at a time”</em></blockquote><pre>Outside Actor<br>       │<br>       ▼<br> ❌ Cannot touch stored properties<br><br>       │<br>       ▼<br><br> Public async methods<br><br>       │<br>       ▼<br><br> Actor&#39;s isolated state</pre><h3>How Actors Process Work</h3><p>Your task must wait until it can safely enter the actor’s isolation domain.</p><pre>Task A<br>    │<br>    ▼<br>+------------------+<br>|                  |<br>|  Actor Mailbox   |<br>|                  |<br>+------------------+<br>      │<br>      ▼<br>Execute Task A<br><br>Task B<br>      │<br>      ▼<br>(waiting...)<br><br>Task C<br>      │<br>      ▼<br>(waiting...)</pre><p>Actors don’t execute all tasks simultaneously.</p><p>Tasks wait in a mailbox.</p><p>Only one executes at a time.</p><h3>What Actors DON’T Protect</h3><p>This is extremely important.</p><p>Example:</p><pre>actor Counter {<br><br>    var numbers: [Int] = []<br><br>    func getNumbers() -&gt; [Int] {<br>        numbers<br>    }<br>}</pre><p>Safe.</p><p>But</p><pre>class User {<br>    var name = &quot;&quot;<br>}<br><br>actor Store {<br><br>    let user = User()<br>}</pre><p>Returning</p><pre>await store.user</pre><p>doesn’t magically make <em>User</em> thread-safe.</p><p>Actors only isolate access <strong>inside</strong> themselves.</p><p>This naturally leads into <strong>Sendable</strong>.</p><h3>Sendable Protocol</h3><p>Actors protect internal state, but what about data passed <em>between</em> tasks?</p><p>Swift uses <em>Sendable</em></p><pre>struct User: Sendable {<br>    let name: String<br>}</pre><h4>Why important:</h4><ul><li>Prevents unsafe data sharing across concurrency boundaries</li><li>Compiler enforces it</li></ul><p>In General:</p><ul><li>Value types → usually safe</li><li>Classes → NOT safe unless explicitly marked</li><li>Most reference types are <strong>not automatically <em>Sendable</em></strong>, because multiple tasks can mutate the same instance simultaneously.</li></ul><h3>Reentrancy</h3><p>Reentrancy improves responsiveness because actors don’t remain blocked while waiting for asynchronous work to complete. The trade-off is that actor state may change before execution resumes.</p><h4>What is Reentrancy?</h4><p>When an actor hits an <em>await</em>, it:</p><ul><li><em>Releases control temporarily</em></li><li>This allows another task to enter the actor.</li></ul><p>Think of <em>await </em>as temporarily unlocking the actor.</p><p>During that suspension, another task may enter and modify the actor’s state before the original task resumes.</p><h4>Why This Matters</h4><p>Even though actors prevent data races…</p><p>They can still lead to <strong>logical bugs</strong></p><p><strong>Example: Subtle Bug</strong></p><pre>actor BankAccount {<br>    var balance = 1000<br><br>    func withdraw(amount: Int) async {<br>        if balance &gt;= amount {<br>            await someAsyncWork()<br>            balance -= amount<br>        }<br>    }<br>}</pre><h4>What Can Go Wrong?</h4><ol><li>Task A checks balance → 1000</li><li>Task A hits <em>await </em>→ actor becomes free</li><li>Task B enters → withdraws 1000 → balance = 0</li><li>Task A resumes → subtracts again → balance = -1000</li></ol><h4>Result</h4><p>Inconsistent state, even though no data race occurred.</p><h4>Fix</h4><p>Always re-check state after suspension:</p><pre>func withdraw(amount: Int) async {<br>    if balance &gt;= amount {<br>        await someAsyncWork()<br><br>        guard balance &gt;= amount else { return }<br>        balance -= amount<br>    }<br>}</pre><p>Actors guarantee safety, not correctness</p><h3>Actor Hop (Hidden Performance Cost)</h3><p>Every time you call:</p><pre>await account.withdraw()</pre><p>The task may:</p><ul><li>Suspend</li><li>The task may suspend and resume on another actor executor. This may or may not involve switching threads.</li><li>Resume later</li></ul><p>This is called an <strong>actor hop</strong></p><pre>Task<br><br>↓<br><br>Actor A Executor<br><br>↓<br><br>await<br><br>↓<br><br>Actor B Executor<br><br>↓<br><br>resume</pre><h4>Why it matters:</h4><ul><li>Too many awaits = performance overhead</li><li>Especially inside loops</li></ul><p>Example:</p><pre>for item in items {<br>    await actor.process(item) // multiple actor hops<br>}</pre><p>Better:</p><pre>await actor.processBatch(items)</pre><p>An actor hop is <strong>not necessarily a thread switch</strong>.</p><p>It’s a switch between actor executors.</p><p>The runtime may or may not move execution to another thread.</p><h3>Global Actors</h3><h4>@MainActor:</h4><p>Use when an entire type or function should always execute on the main actor.</p><p>Ensures code runs on the main thread.</p><pre>@MainActor<br>class ViewModel {<br>    var data: String = &quot;&quot;<br><br>    func updateUI() {<br>        data = &quot;Updated&quot;<br>    }<br>}</pre><ul><li>Entire type isolated</li><li>Compile-time enforcement</li><li>Preferred</li></ul><h4>await MainActor.run</h4><p>Use when only one small block needs to run on the main actor.</p><pre>await MainActor.run {<br>    self.label.text = &quot;Updated&quot;<br>}</pre><ul><li>Single block</li><li>Runtime hop</li><li>One-off work</li></ul><h4>Why It Matters</h4><ul><li>UIKit / SwiftUI require main thread updates</li><li>Prevents UI inconsistencies and crashes</li></ul><h4>@globalActor:</h4><pre>@globalActor<br>actor DatabaseActor {<br>    static let shared = DatabaseActor()<br>}</pre><p>Usage:</p><pre>@DatabaseActor<br>func save() {<br> }</pre><h4>Why important:</h4><ul><li>Custom isolation domains</li><li>Large-scale architecture</li></ul><h3>Isolated Parameters</h3><p>Very few articles cover this — huge differentiator.</p><pre>actor BankAccount {<br>    var balance = 1000<br>    <br>    func withdraw(_ amount: Int) {<br>        balance -= amount<br>    }<br>}<br><br><br>func transfer(<br>    amount: Int,<br>    from source: isolated BankAccount,<br>    to destination: BankAccount<br>) async {<br>    source.withdraw(amount)<br>    await destination.deposit(amount)<br>}</pre><p>Inside the function, <em>source</em> is already isolated, so multiple accesses don’t require repeated <em>awaits</em>.</p><p>Benefit:</p><ul><li>Avoids multiple awaits</li><li>Executes within same isolation</li></ul><p>This is <strong>top-tier advanced Swift knowledge</strong></p><h3>Nonisolated Stored vs Computed Context</h3><h4>nonisolated</h4><p>Used when a method does NOT access actor state.</p><pre>actor Bank {<br>    let bankName = &quot;ABC&quot;<br>    nonisolated var description: String {<br>        bankName<br>    }<br>}</pre><p>No <em>await</em> needed</p><p>Difference:</p><ul><li><em>nonisolated</em> → no actor protection</li><li>Must NOT access actor state</li></ul><p>Edge case:</p><pre>actor Test {<br>    var value = 10<br><br>    nonisolated func invalid() {<br>        print(value) // ❌ Not allowed<br>    }<br>}</pre><h3>Actor Inheritance &amp; Protocols (Edge Case)</h3><p>Actors:</p><ul><li>Do NOT support inheritance like classes</li><li>Can conform to protocols</li></ul><pre>protocol Cache {<br>    func get() -&gt; Data?<br>}<br><br>actor ImageCache: Cache { }</pre><p>This is commonly asked in interviews.</p><h3>Cross-Actor Calls (Subtle but Important)</h3><pre>actor A {<br>    let b = B()<br><br>    func callB() async {<br>        await b.doSomething()<br>    }<br>}</pre><p>This is:</p><ul><li>Actor → Actor communication</li><li>Causes suspension</li></ul><p>Insight:</p><blockquote><em>Each actor has its own isolation domain</em></blockquote><h3>Distributed Actors (Optional but Powerful)</h3><p>Brief mention is enough:</p><ul><li>Used for <strong>networked systems</strong></li><li>Actor across processes/machines</li></ul><pre>distributed actor ChatServer { }</pre><h3>Memory Model + ARC Interaction</h3><ul><li>Actors are reference types.</li><li>They are allocated on the heap.</li><li>Managed by ARC.</li><li>Actor isolation protects mutable state — not memory management.</li></ul><h3>Actor vs Locks vs Queues</h3><ul><li>Locks → manual, error-prone</li><li>Queues → manual serialization</li><li>Actors → compiler-enforced safety</li></ul><h3>How Actors Compare with GCD</h3><pre>DispatchQueue<br><br>↓<br><br>Developer manages synchronization<br><br>↓<br><br>Possible mistakes</pre><p>vs</p><pre>Actor<br><br>↓<br><br>Compiler manages synchronization<br><br>↓<br><br>Safer code</pre><p>This reinforces why actors exist.</p><h3><em>Actors are NOT Parallel</em></h3><p>People think:</p><p>actor == concurrent</p><p>Actually</p><pre>Task A<br>↓<br><br>Actor<br><br>↓<br><br>Task B waits<br><br>↓<br><br>Task C waits</pre><p>Actor methods execute serially.</p><h3>let Properties</h3><p>Many people don’t know immutable properties behave differently.</p><p>Example</p><pre>actor User {<br><br>    let id = UUID()<br>}</pre><p>Immutable state doesn’t require the same synchronization guarantees as mutable state.</p><h3>Performance Considerations</h3><h4>Are Actors Slow?</h4><p>Not exactly.</p><p>But:</p><ul><li>They serialize access</li><li>Only one task runs inside at a time</li></ul><h4>When NOT to Use Actors</h4><ul><li>High-performance computation</li><li>Stateless logic</li><li>Tight loops</li></ul><h4>When to Use Actors</h4><ul><li>Shared mutable state</li><li>Caching systems</li><li>Resource managers</li><li>Networking layers</li></ul><h3>Real-World Example: Image Cache</h3><pre>Image Cache<br><br>Authentication Manager<br><br>Token Refresh Manager<br><br>Analytics Queue<br><br>Database Manager<br><br>Bluetooth Manager<br><br>Download Manager<br><br>WebSocket Manager</pre><h4>Why This Works Well</h4><ul><li>Prevents duplicate writes</li><li>Ensures thread safety</li><li>Keeps API simple</li></ul><h3>Actor vs Class vs Struct (Very Important)</h3><h4>Struct</h4><p>Explain:</p><pre>struct User {<br>    var name: String<br>}</pre><p>Key concepts:</p><ul><li>value type</li><li>copied on assignment</li><li>safer in concurrency</li><li>no shared mutable state by default</li></ul><p>Example:</p><pre>var user1 = User(name: &quot;Akanksha&quot;)<br>var user2 = user1<br><br>user2.name = &quot;John&quot;</pre><p>Explain:</p><ul><li><em>user1</em> unchanged</li><li>independent copies</li><li>naturally thread-safe in many cases</li></ul><h4>Class</h4><pre>class User {<br>    var name: String<br>    <br>    init(name: String) {<br>        self.name = name<br>    }<br>}</pre><p>Example:</p><pre>let user1 = User(name: &quot;Akanksha&quot;)<br>let user2 = user1<br><br>user2.name = &quot;John&quot;</pre><p>Explain:</p><ul><li>shared reference</li><li>both point to same memory</li><li>race conditions possible</li><li>manual synchronization needed</li></ul><p>This is where you connect to:</p><ul><li>DispatchQueue</li><li>locks</li><li>mutexes</li><li>NSLock</li></ul><h4>Actor</h4><pre>actor UserStore {<br>    var users: [String] = []<br>    <br>    func add(_ user: String) {<br>        users.append(user)<br>    }<br>}</pre><p>Explain:</p><ul><li>reference type like class</li><li>BUT protected mutable state</li><li>serialized access</li><li>built for concurrency</li></ul><h3>Common Mistakes</h3><h4>“Actors solve all concurrency problems”</h4><p>They prevent data races, not logical bugs.</p><h4>Ignoring Reentrancy</h4><p>Always remember:</p><blockquote><em>Every </em><strong>await</strong><em> is a potential state change point</em></blockquote><h4>Overusing @MainActor</h4><pre>@MainActor<br>class Everything { }</pre><p>This removes concurrency benefits</p><h4>Using Actors Everywhere</h4><p>Actors are powerful, but not always needed.</p><p>Avoid using them for:</p><ul><li>Simple models</li><li>Pure functions</li><li>Stateless logic</li></ul><h3>Interview Questions &amp; Quick Recap</h3><h4>1. Why were Actors introduced?</h4><p>Actors were introduced to eliminate <strong>data races</strong> caused by shared mutable state.</p><p>Before Actors, developers relied on locks, serial queues, and other synchronization mechanisms that were easy to misuse. Actors provide <strong>compiler-enforced isolation</strong>, ensuring that only one task can access an actor’s mutable state at a time.</p><h4>2. What is the difference between an Actor and a Class?</h4><p>Both Actors and Classes are <strong>reference types</strong> managed by ARC, but they differ in how they handle mutable state.</p><p><strong>Class</strong></p><ul><li>Shared by reference.</li><li>Multiple threads can access and modify its properties simultaneously.</li><li>Thread safety must be implemented manually using locks or queues.</li></ul><p><strong>Actor</strong></p><ul><li>Also shared by reference.</li><li>Mutable state is automatically isolated.</li><li>Only one task can access actor-isolated state at a time.</li><li>The compiler enforces safe access.</li></ul><h4>3. Why does actor access require await?</h4><p>Accessing an actor from outside its isolation domain may require waiting until the actor becomes available.</p><pre>let account = BankAccount()<br>await account.withdraw(amount: 100)</pre><p>The <em>await</em> isn&#39;t because <em>withdraw()</em> is inherently asynchronous. It&#39;s because another task may already be executing inside the actor, so your task must wait until it can safely enter the actor&#39;s isolated context.</p><h4>4. What is Actor Isolation?</h4><p>Actor isolation is the rule that protects an actor’s mutable state.</p><p>Stored properties inside an actor cannot be accessed directly from outside the actor. Instead, external code must interact with the actor through its methods or computed properties.</p><p>This guarantees that only one task can modify the actor’s state at a time, preventing data races.</p><h4>5. What is Reentrancy?</h4><p>When an actor reaches an <em>await</em>, it temporarily suspends execution and allows another task to enter the actor.</p><p>This improves responsiveness but also means the actor’s state may change before the original task resumes.</p><p>That’s why you should always validate critical state after an <em>await </em>if your logic depends on it.</p><h4>6. What is an Actor Hop?</h4><p>An actor hop occurs when execution moves from one actor’s isolation domain to another.</p><pre>await cache.store(image)</pre><p>The current task suspends, switches to the target actor’s executor, and resumes when that actor is ready.</p><p>An actor hop is <strong>not necessarily a thread switch</strong>. It’s a transition between actor executors, and the Swift runtime decides whether a thread change is required.</p><h3>7. What is the difference between <strong>@MainActor </strong>and <strong>DispatchQueue.main.async</strong>?</h3><p>Both ensure code executes on the main thread, but they work very differently.</p><p><strong>DispatchQueue.main.async</strong></p><ul><li>A GCD API that schedules work on the main queue.</li><li>The compiler has no knowledge of thread isolation.</li><li>Easy to accidentally update UI from the wrong thread elsewhere.</li></ul><pre>DispatchQueue.main.async {<br>    label.text = &quot;Updated&quot;<br>}</pre><p><strong>@MainActor</strong></p><ul><li>A Swift Concurrency feature.</li><li>The compiler enforces that annotated code always executes on the Main Actor.</li><li>Provides compile-time safety instead of relying on manual dispatching.</li></ul><pre>@MainActor<br>class ProfileViewModel {<br>    func updateUI() {<br>        // Always executes on the Main Actor<br>    }<br>}</pre><p>Whenever you’re writing new Swift Concurrency code, prefer <em>@MainActor</em><strong> </strong>over manually dispatching to <em>DispatchQueue.main</em>.</p><h3>8. What is the difference between @MainActor and MainActor.run?</h3><p><em>@MainActor</em> isolates an entire type, property, or function to the Main Actor.</p><pre>@MainActor<br>class ViewModel { }</pre><p>Use it when UI-related code should <strong>always</strong> execute on the Main Actor.</p><p><em>MainActor.run</em> temporarily switches execution to the Main Actor for a single block.</p><pre>await MainActor.run {<br>    label.text = &quot;Updated&quot;<br>}</pre><p>Use it when only a small portion of your code needs to update the UI.</p><p>In general:</p><ul><li><em>@MainActor</em> → Entire type or function.</li><li><em>MainActor.run</em> → One specific block.</li></ul><h4>9. What is Sendable?</h4><p><em>Sendable</em> is a protocol that indicates a type can be safely transferred across concurrency boundaries.</p><pre>struct User: Sendable {<br>    let name: String<br>}</pre><p>Swift uses <em>Sendable </em>to prevent unsafe sharing of mutable data between tasks.</p><p>As a rule of thumb:</p><ul><li>Immutable value types are usually <em>Sendable</em>.</li><li>Most mutable reference types are <strong>not</strong> automatically <em>Sendable</em>.</li></ul><p>Actors protect shared mutable state, while <em>Sendable </em>ensures values can safely move between concurrent tasks.</p><h4>10. When should you avoid Actors?</h4><p>Actors are excellent for protecting shared mutable state, but they are not the right solution for every problem.</p><p>Avoid Actors when:</p><ul><li>Your code is stateless.</li><li>You’re writing pure functions.</li><li>You’re performing CPU-intensive computations.</li><li>High-performance loops would suffer from repeated actor hops.</li><li>There’s no shared mutable state to protect.</li></ul><p>Use Actors where synchronization is required — not by default.</p><h3>Final Thoughts</h3><p>Swift Concurrency is built on three pillars:</p><ul><li>Tasks → execution</li><li>Async/Await → flow</li><li>Actors → safety</li></ul><p>Actors bring something incredibly powerful:</p><blockquote><em>Compiler-enforced thread safety</em></blockquote><p>But they also require deeper understanding:</p><blockquote><em>Especially reentrancy and state consistency</em></blockquote><p>If you truly understand Actors, you’ve moved from:</p><p>“I can use concurrency”</p><p>to</p><p><strong>“I can design safe concurrent systems”</strong></p><h3>What’s Next?</h3><p>In the next article, we’ll explore:</p><p>👉 <strong>AsyncSequence &amp; Streams — handling continuous asynchronous data</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd0de630ca75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Kernel in Operating Systems]]></title>
            <link>https://medium.com/@aksingh20feb/understanding-the-kernel-in-operating-systems-0e27ce21fe0f?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e27ce21fe0f</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[laptop]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Mon, 18 May 2026 09:43:09 GMT</pubDate>
            <atom:updated>2026-05-18T09:57:23.192Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Core Engine Behind Mobile Phones, Laptops, Servers, and Smart Devices</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izIRQO25ksmOzTcwJOueCQ.png" /></figure><p>Every time you unlock your phone, open an app, play a game, or browse the internet on your laptop, something extremely important is working silently in the background:</p><p>The <strong>Kernel</strong>.</p><p>Most users never see it.<br>Most beginners hear the term but don’t fully understand it.</p><p>Yet the kernel is the most critical component of an operating system.</p><p>Without it:</p><ul><li>Android cannot run</li><li>iOS cannot work</li><li>Windows cannot boot</li><li>macOS cannot manage hardware</li><li>Linux servers cannot handle requests</li></ul><p>The kernel is essentially the <strong>brain and manager of the operating system</strong>.</p><h3>What is a Kernel?</h3><p>A <strong>Kernel</strong> is the central core of an operating system that directly communicates with the hardware and manages system resources.</p><p>It acts as a bridge between:</p><ul><li>Software (apps)</li><li>Hardware (CPU, RAM, storage, camera, keyboard, etc.)</li></ul><p>Applications cannot directly access hardware safely.</p><p>Instead:</p><pre>Application → Operating System → Kernel → Hardware</pre><p>The kernel controls:</p><ul><li>CPU usage</li><li>Memory allocation</li><li>Device communication</li><li>Process scheduling</li><li>File systems</li><li>Security and permissions</li></ul><h3>Simple Real-Life Analogy</h3><p>Imagine a large company.</p><ul><li>Employees = Applications</li><li>Machines/resources = Hardware</li><li>Manager = Kernel</li></ul><p>Employees cannot directly use every company resource whenever they want.</p><p>The manager:</p><ul><li>decides priorities</li><li>allocates resources</li><li>prevents conflicts</li><li>ensures security</li><li>manages communication</li></ul><p>That manager is exactly what the kernel does inside a computer or smartphone.</p><h4>Why Do We Need a Kernel?</h4><p>Without a kernel:</p><ul><li>Apps could overwrite each other’s memory</li><li>Multiple apps could crash the CPU</li><li>Hardware access would become chaotic</li><li>Security would completely fail</li><li>System stability would collapse</li></ul><p>The kernel ensures:</p><ul><li>Stability</li><li>Security</li><li>Multitasking</li><li>Efficient resource management</li></ul><h3>Main Responsibilities of a Kernel</h3><h4>1. Process Management</h4><p>Modern devices run many applications simultaneously.</p><p>Examples:</p><ul><li>Music playing</li><li>WhatsApp notifications</li><li>Browser tabs</li><li>Background downloads</li><li>Camera processing</li></ul><p>The kernel manages:</p><ul><li>Process creation</li><li>Scheduling</li><li>Context switching</li><li>CPU allocation</li></ul><p>It decides:</p><pre>Which process runs?<br>For how long?<br>When should it pause?</pre><p>This is why multitasking works.</p><h4>2. Memory Management</h4><p>RAM is limited.</p><p>The kernel:</p><ul><li>allocates memory to applications</li><li>frees unused memory</li><li>prevents memory corruption</li><li>isolates processes securely</li></ul><p>Without this:</p><p>one app could destroy another app’s data.</p><h4>3. Device Management</h4><p>Hardware devices include:</p><ul><li>Keyboard</li><li>Mouse</li><li>Camera</li><li>GPU</li><li>Bluetooth</li><li>WiFi</li><li>Speakers</li><li>Touchscreen</li></ul><p>Applications do not directly control these devices.</p><p>The kernel uses:</p><ul><li>Device drivers</li><li>Hardware abstraction</li><li>Interrupt handling</li></ul><p>This allows apps to work consistently across different hardware.</p><h4>4. File System Management</h4><p>Whenever you:</p><ul><li>save photos</li><li>download files</li><li>install apps</li></ul><p>the kernel manages:</p><ul><li>disk access</li><li>storage blocks</li><li>file permissions</li><li>reading/writing operations</li></ul><h4>5. Security and Permissions</h4><p>The kernel protects the system from:</p><ul><li>unauthorized access</li><li>malicious applications</li><li>memory violations</li><li>privilege escalation</li></ul><p>For example:</p><ul><li>Apps on Android are sandboxed</li><li>iOS apps have restricted permissions</li></ul><p>The kernel enforces these security boundaries.</p><h3>User Space vs Kernel Space</h3><p>Operating systems separate execution into two major areas.</p><h4>User Space</h4><p>Where normal applications run.</p><p>Examples:</p><ul><li>Instagram</li><li>Chrome</li><li>Spotify</li><li>VS Code</li></ul><p>Apps in user space have limited permissions.</p><h4>Kernel Space</h4><p>Where the kernel runs with full system access.</p><p>The kernel can:</p><ul><li>access all memory</li><li>communicate with hardware</li><li>execute privileged instructions</li></ul><p>This separation improves security and stability.</p><h3>What Happens When You Open an App?</h3><p>Suppose you open YouTube on your phone.</p><p>The following happens:</p><ol><li>App requests CPU time</li><li>Kernel schedules execution</li><li>Memory is allocated</li><li>Network access is requested</li><li>GPU rendering begins</li><li>Audio drivers are used</li><li>File system loads cached data</li></ol><p>All these operations are coordinated by the kernel.</p><h3>Types of Kernels</h3><p>Different operating systems use different kernel architectures.</p><h4>1. Monolithic Kernel</h4><p>A monolithic kernel contains most operating system services inside the kernel itself.</p><p>Includes:</p><ul><li>memory management</li><li>file systems</li><li>drivers</li><li>networking</li></ul><p>Advantages:</p><ul><li>Very fast</li><li>High performance</li></ul><p>Disadvantages:</p><ul><li>Large and complex</li><li>Bugs can crash the entire system</li></ul><p>Examples:</p><ul><li>Linux Kernel</li><li>Android Kernel (Linux-based)</li></ul><h4>2. Microkernel</h4><p>A microkernel keeps only essential components inside the kernel.</p><p>Most services run in user space.</p><p>Advantages:</p><ul><li>Better isolation</li><li>More stable</li><li>More secure</li></ul><p>Disadvantages:</p><ul><li>Slightly slower due to communication overhead</li></ul><p>Examples:</p><ul><li>MINIX</li><li>QNX</li></ul><h3>3. Hybrid Kernel</h3><p>Combines monolithic and microkernel approaches.</p><p>Used by:</p><ul><li>Windows</li><li>macOS (XNU kernel)</li></ul><p>It aims to balance:</p><ul><li>performance</li><li>modularity</li><li>stability</li></ul><h3>Kernels in Popular Operating Systems</h3><h4>Linux</h4><p>Used in:</p><ul><li>Servers</li><li>Android phones</li><li>Embedded systems</li><li>Supercomputers</li></ul><p>Features:</p><ul><li>Open source</li><li>Monolithic design</li><li>Extremely popular</li></ul><h4>Android Kernel</h4><p>Android uses a modified Linux kernel.</p><p>Handles:</p><ul><li>touch input</li><li>power management</li><li>mobile hardware</li><li>process isolation</li></ul><p>Android framework sits above the Linux kernel.</p><h4>Windows NT Kernel</h4><p>Used in:</p><ul><li>Windows 10</li><li>Windows 11</li></ul><p>Hybrid kernel architecture.</p><p>Supports:</p><ul><li>desktop systems</li><li>gaming</li><li>enterprise workloads</li></ul><h4>XNU Kernel (macOS &amp; iOS)</h4><p>Apple uses the XNU kernel.</p><p>XNU combines:</p><ul><li>Mach microkernel</li><li>BSD components</li></ul><p>Used in:</p><ul><li>macOS</li><li>iOS</li><li>iPadOS</li></ul><p>Optimized heavily for Apple hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ibr8sHLOhvOgLKeNyPa9Xg.png" /></figure><h3>How Mobile Kernels Differ from Laptop Kernels</h3><p>Mobile operating systems have additional challenges.</p><p>They focus heavily on:</p><ul><li>battery optimization</li><li>thermal management</li><li>background restrictions</li><li>sensor management</li></ul><p>Mobile kernels handle:</p><ul><li>GPS</li><li>accelerometer</li><li>camera pipelines</li><li>touch responsiveness</li><li>cellular networking</li></ul><p>Laptop/Desktop kernels focus more on:</p><ul><li>high-performance multitasking</li><li>external hardware</li><li>gaming</li><li>file systems</li><li>virtualization</li></ul><h3>Kernel Mode vs User Mode Crashes</h3><p>When a normal application crashes:</p><ul><li>usually only the app closes</li></ul><p>When the kernel crashes:</p><ul><li>entire system may crash</li></ul><p>Examples:</p><ul><li>Windows Blue Screen of Death (BSOD)</li><li>Linux kernel panic</li></ul><p>Because the kernel controls everything.</p><h3>What is a System Call?</h3><p>Applications cannot directly access kernel functionality.</p><p>Instead, they use <strong>System Calls</strong>.</p><p>Examples:</p><ul><li>open()</li><li>read()</li><li>write()</li><li>fork()</li></ul><p>System calls act like controlled gateways into kernel services.</p><h3>Kernel and Performance</h3><p>Kernel design directly affects:</p><ul><li>battery life</li><li>responsiveness</li><li>multitasking</li><li>gaming performance</li><li>server scalability</li></ul><p>Optimized kernels improve:</p><ul><li>scheduling</li><li>memory usage</li><li>I/O operations</li></ul><p>This is why operating system engineering is highly specialized.</p><h3>Why Kernel Development is Difficult</h3><p>Kernel programming is extremely challenging because:</p><ul><li>low-level hardware interaction</li><li>concurrency issues</li><li>memory safety</li><li>race conditions</li><li>performance constraints</li></ul><p>Even small bugs can:</p><ul><li>freeze systems</li><li>corrupt memory</li><li>crash devices</li></ul><p>Kernel developers often work using:</p><ul><li>C</li><li>C++</li><li>Rust (modern systems)</li><li>Assembly</li></ul><h3>Modern Trends in Kernel Development</h3><p>Modern kernels are evolving toward:</p><ul><li>better security</li><li>sandboxing</li><li>virtualization</li><li>container support</li><li>energy efficiency</li></ul><p>Examples:</p><ul><li>Linux supports containers via namespaces/cgroups</li><li>Android improves process isolation</li><li>Apple focuses heavily on security and efficiency</li></ul><h3>Why Developers Should Understand Kernels</h3><p>Even application developers benefit from understanding kernels.</p><p>It helps explain:</p><ul><li>threading</li><li>concurrency</li><li>memory management</li><li>process lifecycle</li><li>file systems</li><li>networking</li><li>performance bottlenecks</li></ul><p>For mobile developers:<br> understanding kernels helps explain:</p><ul><li>app lifecycle</li><li>background execution</li><li>battery optimization</li><li>thread scheduling</li></ul><h3>Final Thoughts</h3><p>The kernel is one of the most important pieces of software ever created.</p><p>It silently manages:</p><ul><li>hardware</li><li>applications</li><li>memory</li><li>security</li><li>multitasking</li></ul><p>Every smartphone, laptop, server, smart TV, and embedded device depends on a kernel to function.</p><p>Although users rarely see it directly, the kernel is the invisible foundation powering modern computing.</p><p>Without kernels:<br> modern operating systems simply could not exist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e27ce21fe0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Networking & The Internet — Part 1]]></title>
            <link>https://medium.com/@aksingh20feb/computer-networking-the-internet-part-1-de86082dd8e6?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/de86082dd8e6</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[ip]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Tue, 12 May 2026 11:09:26 GMT</pubDate>
            <atom:updated>2026-05-12T12:38:49.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoasCURbErwVJB4ZglcG_Q.png" /></figure><h3>Introduction</h3><p>The Internet has become one of the most important technologies in modern life. From sending messages and attending online classes to streaming videos and using cloud applications, almost everything today depends on computer networks.</p><p>At its core, the Internet is a massive network that connects billions of devices worldwide and allows them to exchange information efficiently. Understanding how the Internet works is the foundation of computer networking.</p><p>This chapter introduces the fundamental building blocks of the Internet, including hosts, routers, protocols, packet switching, ISPs, and access networks.</p><h3>What Is the Internet?</h3><p>The Internet can be understood in two ways:</p><ol><li><strong>A nuts-and-bolts description</strong><br> Focuses on physical components such as routers, cables, servers, and switches.</li><li><strong>A services description</strong><br> Focuses on applications and services provided to users such as web browsing, email, streaming, and gaming.</li></ol><p>The Internet is essentially a global collection of interconnected computer networks that communicate using standardized protocols.</p><h3>Main Components of the Internet</h3><p>The Internet is built using several important components working together.</p><h4>1. End Systems (Hosts)</h4><p>End systems are devices connected to the Internet. These devices run applications and communicate with other systems.</p><p>Examples include:</p><ul><li>Desktop computers</li><li>Laptops</li><li>Smartphones</li><li>Tablets</li><li>Smart TVs</li><li>Gaming consoles</li><li>Servers</li><li>IoT devices</li></ul><p>These systems are also called <strong>hosts</strong> because they host applications like browsers, games, and messaging services.</p><h4>2. Communication Links</h4><p>Communication links are the physical or wireless paths through which data travels.</p><p>Different technologies are used for communication:</p><ul><li>Fiber optic cables</li><li>Copper wires</li><li>Coaxial cables</li><li>Wi-Fi</li><li>Cellular networks</li><li>Satellite communication</li></ul><p>Each link has a transmission rate, commonly called <strong>bandwidth</strong>, measured in:</p><ul><li>bits/sec</li><li>Mbps</li><li>Gbps</li></ul><p>Higher bandwidth allows faster data transmission.</p><h4>3. Packet Switches</h4><p>Instead of sending large files as one huge block, the Internet divides data into smaller units called <strong>packets</strong>.</p><p>Devices called packet switches help move packets across networks.</p><p>Two major packet-switching devices are:</p><ul><li>Routers</li><li>Link-layer switches</li></ul><p><strong>a) Routers</strong></p><p>Routers connect different networks together and determine the best path for packets.</p><p><strong>b) Switches</strong></p><p>Switches are commonly used inside local networks like offices and homes.</p><h3>Packet Switching</h3><p>Packet switching is one of the most important concepts in networking.</p><p>Instead of reserving a dedicated communication line, data is broken into packets and transmitted independently through the network.</p><p><strong>How Packet Switching Works</strong></p><ol><li>A large message is divided into packets</li><li>Each packet contains source and destination information</li><li>Routers forward packets toward their destination</li><li>Packets may travel through different paths</li><li>Destination system reassembles the original message</li></ol><p>This method makes the Internet:</p><ul><li>Efficient</li><li>Scalable</li><li>Reliable</li></ul><p>For example, when sending a WhatsApp message or streaming a YouTube video, the data is divided into thousands of packets. These packets may travel through different routes before reaching the destination device.</p><h4>Why Packet Switching Is Efficient</h4><ul><li>Multiple users share the same network</li><li>No dedicated line needed</li><li>Better bandwidth utilization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HoOzbhWPfm8ivPwvqfTFA.png" /></figure><h3>Internet Service Providers (ISPs)</h3><p>Users cannot directly connect to the entire Internet. They connect through organizations called <strong>Internet Service Providers (ISPs)</strong>.</p><p>Examples:</p><ul><li>Jio</li><li>Airtel</li><li>BSNL</li><li>AT&amp;T</li></ul><p>ISPs provide:</p><ul><li>Internet connectivity</li><li>Routing services</li><li>Network infrastructure</li></ul><h4>ISP Hierarchy</h4><p>The Internet has a layered ISP structure:</p><ul><li>Local ISP</li><li>Regional ISP</li><li>National ISP</li><li>Global ISP</li></ul><p>All these networks interconnect to form the global Internet.</p><h3>Protocols</h3><p>Protocols are the rules that govern communication between devices.</p><p>Without protocols, systems developed by different companies would not understand each other.</p><p>A protocol defines:</p><ul><li>Message format</li><li>Order of communication</li><li>Actions taken after sending/receiving data</li></ul><h3>Important Internet Protocols</h3><h4>1. TCP (Transmission Control Protocol)</h4><p>TCP guarantees that packets arrive correctly and in order.</p><p>TCP ensures:</p><ul><li>Reliable delivery</li><li>Ordered packets</li><li>Error checking</li></ul><p>It is widely used for:</p><ul><li>Web browsing</li><li>File transfers</li><li>Email</li></ul><p><strong>Example</strong>: websites, banking</p><p>When downloading files or opening websites, TCP ensures that all packets arrive correctly and in order.</p><p>If packets are lost during transmission, TCP retransmits them automatically.</p><h4>2. IP (Internet Protocol)</h4><p>IP is responsible for:</p><ul><li>Addressing devices</li><li>Routing packets</li></ul><p>Every device on the Internet has an IP address.</p><p>IP addresses work similarly to home addresses. They help identify where data should be delivered on the Internet.</p><h4>3. HTTP (HyperText Transfer Protocol)</h4><p>HTTP is used for web communication between:</p><ul><li>Browsers</li><li>Web servers</li></ul><p>When you open a website, your browser sends HTTP requests to the server.</p><h4>4. Wi-Fi Protocols (IEEE 802.11)</h4><p>These protocols define wireless communication standards used in homes, offices, and public hotspots.</p><h3>Internet Standards</h3><p>The Internet works globally because organizations create common standards.</p><h4>IETF (Internet Engineering Task Force)</h4><p>The IETF develops Internet standards called:</p><ul><li>RFCs (Request for Comments)</li></ul><p>These documents define protocols and networking practices.</p><h4>IEEE</h4><p>IEEE creates standards for:</p><ul><li>Ethernet</li><li>Wi-Fi</li><li>Networking hardware</li></ul><p>Example:</p><ul><li>IEEE 802.11 → Wi-Fi</li><li>IEEE 802.3 → Ethernet</li></ul><h3>Internet Applications</h3><p>The Internet supports many distributed applications.</p><p>Examples:</p><ul><li>Web browsing</li><li>Video streaming</li><li>Voice calls (VoIP)</li><li>Social media</li><li>Online gaming</li><li>Cloud storage</li><li>Video conferencing</li></ul><p>These applications involve multiple systems communicating over networks.</p><h3>What Is a Protocol? — Human Analogy</h3><p>Protocols in networking are similar to rules in human conversations.</p><p>Example conversation:</p><ul><li>Person A: “Hi”</li><li>Person B: “Hi”</li><li>Person A: “What’s the time?”</li><li>Person B: “2 PM”</li></ul><p>There are expected patterns:</p><ul><li>When to speak</li><li>How to respond</li><li>What happens if no reply comes</li></ul><p>Computer protocols work in the same way.</p><h4>Example: Accessing a Web Page</h4><p>When you open a website:</p><ol><li>Browser creates a TCP connection</li><li>Server accepts the connection</li><li>Browser sends an HTTP request</li><li>Server sends webpage data</li><li>Browser displays the webpage</li></ol><p>This entire process happens within seconds.</p><h3>The Network Edge</h3><p>The network edge refers to devices located at the boundary of the Internet.</p><p>Examples:</p><ul><li>Computers</li><li>Phones</li><li>Servers</li><li>Data centers</li></ul><p>Applications mainly run at the network edge.</p><h3>Clients and Servers</h3><p>Internet applications generally follow the <strong>client-server model</strong>.</p><h4>Client</h4><p>Requests services.</p><p>Examples:</p><ul><li>Web browser</li><li>Mobile app</li></ul><h4>Server</h4><p>Provides services.</p><p>Examples:</p><ul><li>Web server</li><li>Email server</li><li>Database server</li></ul><h3>Data Centers</h3><p>Modern Internet services rely heavily on data centers.</p><p>A data center contains thousands of servers working together.</p><p>Companies like Google, Amazon, and Netflix use data centers to:</p><ul><li>Store data</li><li>Process requests</li><li>Stream videos</li><li>Provide cloud computing</li></ul><h3>Access Networks</h3><p>Access networks connect end users to the Internet.</p><p>Different technologies are used depending on:</p><ul><li>Location</li><li>Speed requirements</li><li>Cost</li></ul><h3>Home Access Networks</h3><h4>1. DSL (Digital Subscriber Line)</h4><p>DSL uses existing telephone lines.</p><p><strong>Features</strong></p><ul><li>Simultaneous phone and Internet</li><li>DSL modem required</li><li>Connected through DSLAM</li></ul><p><strong>Frequency Division</strong></p><p>Telephone lines carry:</p><ul><li>Voice signals</li><li>Upstream Internet data</li><li>Downstream Internet data</li></ul><p>using different frequencies.</p><h4>2. Cable Internet</h4><p>Cable Internet uses cable television infrastructure.</p><p><strong>a) Hybrid Fiber Coax (HFC)</strong></p><p>HFC combines:</p><ul><li>Fiber optics</li><li>Coaxial cable</li></ul><p>Components:</p><ul><li>Cable modem</li><li>CMTS (Cable Modem Termination System)</li></ul><p>Key Characteristic:</p><p>Bandwidth is shared among users.</p><p><strong>b) FTTH (Fiber To The Home)</strong></p><p>FTTH provides fiber optic connections directly to homes.</p><p>Advantages:</p><ul><li>Extremely high speed</li><li>Reliable communication</li><li>Low latency</li><li>Better future scalability</li></ul><p>Architectures:</p><ul><li>AON (Active Optical Network)</li><li>PON (Passive Optical Network)</li></ul><h3>Enterprise Networks</h3><p>Organizations use enterprise networks to connect employees and systems.</p><h4>Ethernet</h4><p>Ethernet is the most widely used wired LAN technology.</p><p>Advantages:</p><ul><li>High speed</li><li>Reliable</li><li>Cost effective</li></ul><h4>Wi-Fi</h4><p>Wi-Fi enables wireless communication within local areas.</p><p>Common places:</p><ul><li>Homes</li><li>Offices</li><li>Cafes</li><li>Airports</li></ul><p>Standard:</p><ul><li>IEEE 802.11</li></ul><h4>Mobile Networks</h4><p>Mobile devices connect using:</p><ul><li>3G</li><li>4G</li><li>5G</li></ul><p>Communication occurs through:</p><ul><li>Cellular towers</li><li>Base stations</li></ul><p>Modern mobile networks support:</p><ul><li>Video streaming</li><li>Online gaming</li><li>Cloud applications</li><li>Real-time communication</li></ul><h3>Why Developers Should Learn Networking</h3><p>Modern applications heavily depend on networking.</p><p>Every mobile app, website, cloud platform, streaming service, and API communication works because devices exchange data over networks.</p><p>Understanding networking helps developers:</p><ul><li>Build scalable applications</li><li>Debug API and connectivity issues</li><li>Improve performance</li><li>Understand distributed systems</li><li>Learn security fundamentals</li></ul><h3>The Internet Backbone</h3><p>The Internet backbone consists of extremely high-speed networks that connect major ISPs, data centers, and countries together.</p><p>These backbone networks mainly use fiber optic communication and undersea submarine cables to transfer data globally.</p><p>Large companies such as Google, Amazon, and Microsoft operate massive backbone infrastructure to support Internet communication worldwide.</p><h3>Circuit Switching vs Packet Switching</h3><p>Traditional telephone systems used <strong>circuit switching</strong>, where a dedicated communication path was reserved for the entire conversation.</p><p>The Internet uses <strong>packet switching</strong> instead.</p><h4>Circuit Switching</h4><ul><li>Dedicated communication path</li><li>Resources remain reserved during the entire communication</li><li>More predictable connection</li><li>Lower overall efficiency</li><li>Mainly used in traditional telephone networks</li></ul><h4>Packet Switching</h4><ul><li>Data is divided into small packets</li><li>Multiple users share the same network infrastructure</li><li>Packets can travel through different paths</li><li>Higher bandwidth utilization</li><li>More scalable and efficient</li><li>Used by the modern Internet</li></ul><h4>Key Differences</h4><p><strong>Connection Type</strong></p><ul><li>Circuit Switching → Dedicated connection</li><li>Packet Switching → Shared connection</li></ul><p><strong>Efficiency</strong></p><ul><li>Circuit Switching → Lower</li><li>Packet Switching → Higher</li></ul><p><strong>Resource Usage</strong></p><ul><li>Circuit Switching → Reserved resources</li><li>Packet Switching → Shared resources</li></ul><p><strong>Common Usage</strong></p><ul><li>Circuit Switching → Traditional telephone systems</li><li>Packet Switching → Internet communication</li></ul><p><strong>Why the Internet Uses Packet Switching</strong></p><p>Packet switching allows millions of users to efficiently share the same network infrastructure without reserving dedicated communication paths. This makes the Internet more scalable, cost-effective, and efficient.</p><h3>What Happens When You Open Website?</h3><ol><li>Browser checks the domain name</li><li>DNS converts the domain into an IP address</li><li>TCP connection is established</li><li>Browser sends an HTTP request</li><li>Server responds with webpage data</li><li>Browser renders the webpage</li></ol><h3>TCP vs UDP</h3><p>The Internet mainly uses two transport protocols:</p><h4>TCP</h4><ul><li>Reliable</li><li>Ordered delivery</li><li>Error checking</li></ul><p><strong>Used for:</strong></p><ul><li>Websites</li><li>File transfers</li><li>Email</li></ul><h4>UDP</h4><ul><li>Faster</li><li>No guaranteed delivery</li><li>Lower overhead</li></ul><p><strong>Used for:</strong></p><ul><li>Online gaming</li><li>Video calls</li><li>Live streaming</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euWpDuiFfClQsnU4V0J1CQ.png" /></figure><h3>Network Performance Metrics</h3><h4>Bandwidth</h4><p>Maximum data transfer capacity.</p><h4>Latency</h4><p>Time taken for data to travel across the network.</p><h4>Throughput</h4><p>Actual amount of data transferred successfully.</p><h4>Packet Loss</h4><p>Packets lost during transmission due to congestion or errors.</p><h3>DNS (Domain Name System)</h3><p>DNS translates human-readable domain names like google.com into IP addresses that computers can understand.</p><p>It acts like the phonebook of the Internet.</p><h3>Key Networking Terms</h3><p>Host -&gt; Device connected to Internet</p><p>Packet -&gt; Small data unit</p><p>Router -&gt; Device forwarding packets</p><p>Protocol -&gt; Communication rules</p><p>ISP -&gt; Internet Service Provider</p><p>Bandwidth -&gt; Data transfer capacity</p><p>DSLAM -&gt; DSL access multiplexer</p><p>CMTS -&gt; Cable modem controller</p><p>LAN -&gt; Local Area Network</p><p>FTTH -&gt; Fiber to the home</p><h3>Key Takeaways</h3><ul><li>The Internet is a network of interconnected networks</li><li>Data travels in small packets</li><li>Routers forward packets across networks</li><li>Protocols define communication rules</li><li>ISPs provide Internet access</li><li>TCP/IP are the foundation of Internet communication</li></ul><h3>Conclusion</h3><p>The Internet is a massive interconnected system built using hosts, routers, communication links, protocols, and packet-switching technologies.</p><p>Understanding these foundational concepts is essential before diving deeper into advanced networking topics such as routing, transport protocols, congestion control, cloud networking, and network security.</p><p>In Part 2, we will explore the network core, delay, throughput, packet loss, and how data moves efficiently across the Internet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de86082dd8e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency Architecture Explained]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@aksingh20feb/swift-concurrency-architecture-explained-ee1c831b6031?source=rss-12293b6c4473------2"><img src="https://cdn-images-1.medium.com/max/1536/1*GL6EGXq1yH4LJx_64SP_zQ.png" width="1536"></a></p><p class="medium-feed-snippet">Cooperative Thread Pool, Work Stealing, Structured Concurrency and Runtime Scheduling</p><p class="medium-feed-link"><a href="https://medium.com/@aksingh20feb/swift-concurrency-architecture-explained-ee1c831b6031?source=rss-12293b6c4473------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@aksingh20feb/swift-concurrency-architecture-explained-ee1c831b6031?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1c831b6031</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 07:59:15 GMT</pubDate>
            <atom:updated>2026-03-13T07:59:56.572Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency Async Await Deep Dive: Suspension Points, Threading, async let, and Real-World…]]></title>
            <link>https://medium.com/@aksingh20feb/swift-concurrency-async-await-how-it-really-works-suspension-points-concurrency-and-memory-0f2894d9777d?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f2894d9777d</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 08:57:35 GMT</pubDate>
            <atom:updated>2026-03-13T08:03:44.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Concurrency Async Await Deep Dive: Suspension Points, Threading, async let, and Real-World Edge Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbHvtQ_WGmd4dX6NjO6veQ.png" /></figure><p>Swift concurrency introduced <em>async</em> and <em>await</em> to make asynchronous programming safer and easier to reason about. Before Swift 5.5, developers had to rely on completion handlers, nested closures, or Combine pipelines. These approaches often led to <strong>callback pyramids, hard-to-trace execution flow, and memory management issues</strong>.</p><p><strong>Async/await</strong> changes that by allowing asynchronous code to look almost like synchronous code.</p><p>But under the hood, a lot is happening.</p><p>In this article we will deeply explore:</p><ul><li>What <em>async</em> functions are</li><li>Suspension points</li><li>Await vs blocking</li><li>Sequential vs concurrent awaits</li><li><em>async let</em></li><li>Error handling with async functions</li><li>Memory management implications</li><li>Real world edge cases</li></ul><h3>What is Structured Concurrency</h3><p>Swift concurrency follows <strong>structured concurrency</strong>, meaning child tasks are tied to the lifecycle of their parent task.</p><p>Example:</p><pre>func loadDashboard() async {<br>    async let user = fetchUser()<br>    async let posts = fetchPosts()<br><br>    let result = await (user, posts)<br>}</pre><p>Here:</p><ul><li><em>user</em> and <em>posts</em> are <strong>child tasks</strong></li><li>They <strong>cannot outlive the parent scope</strong></li><li>Swift <strong>automatically cancels them if the parent task is cancelled</strong></li></ul><p>This prevents <strong>task leaks and runaway background work</strong>.</p><p>Without structured concurrency, tasks could continue running indefinitely.</p><p>Why it matters:</p><ul><li>Predictable lifecycle</li><li>Safer concurrency</li><li>No orphaned tasks</li></ul><h3>What is an Async Function</h3><p>An async function is a function that <strong>can suspend execution and resume later without blocking the thread</strong>.</p><p>Example:</p><pre>func fetchUser() async -&gt; User {<br>    let url = URL(string: &quot;https://api.example.com/user&quot;)!<br>    let (data, _) = try! await URLSession.shared.data(from: url)<br>    return try! JSONDecoder().decode(User.self, from: data)<br>}</pre><p>Notice two things:</p><p>The function is marked <em>async</em>.</p><p>Inside the function we can use <em>await</em>.</p><p>Calling this function requires <em>await</em>:</p><pre>let user = await fetchUser()</pre><p>This tells Swift:</p><p>“Execution might pause here and resume later.”</p><h3>Why Async/Await Was Introduced</h3><p>Before Swift introduced async/await, asynchronous networking was typically implemented using <strong>completion handlers and Grand Central Dispatch (GCD)</strong>.</p><p>Example generic networking function with GCD:</p><pre>func fetchAPI&lt;T: Decodable&gt;(<br>    url: String,<br>    request: [String: Any]? = nil,<br>    body: Data? = nil,<br>    completionHandler: @escaping (Result&lt;T, Error&gt;) -&gt; Void<br>) {<br><br>  guard let url = URL(string: url) else {<br>        completionHandler(.failure(NetworkError.invalidURL))<br>        return<br>    }<br>    var urlRequest = URLRequest(url: url)<br>    urlRequest.httpMethod = &quot;POST&quot;<br>    urlRequest.httpBody = body<br>    urlRequest.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>    URLSession.shared.dataTask(with: urlRequest) { data, response, error in<br>        if let error = error {<br>            DispatchQueue.main.async {<br>                completionHandler(.failure(error))<br>            }<br>            return<br>        }<br>        guard let data = data else {<br>            DispatchQueue.main.async {<br>                completionHandler(.failure(NetworkError.noData))<br>            }<br>            return<br>        }<br>        DispatchQueue.global(qos: .background).async {<br>            do {<br>                let decoded = try JSONDecoder().decode(T.self, from: data)<br>                DispatchQueue.main.async {<br>                    completionHandler(.success(decoded))<br>                }<br>            } catch {<br>                DispatchQueue.main.async {<br>                    completionHandler(.failure(error))<br>                }<br>            }<br>        }<br>    }.resume()<br>}</pre><p>Custom error:</p><pre>enum NetworkError: Error {<br>    case invalidURL<br>    case noData<br>}</pre><h4>Using the Function</h4><p>Example usage:</p><pre>fetchAPI(url: &quot;https://api.example.com/users&quot;) { (result: Result&lt;[User], Error&gt;) in<br><br>  switch result {<br>    case .success(let users):<br>        print(users)<br>    case .failure(let error):<br>        print(error)<br>    }<br>}</pre><p>This works, but notice several issues:</p><ul><li>Nested closures</li><li>Multiple thread switches</li><li>Harder to read execution flow</li><li>Error handling inside closures</li><li>Potential memory capture issues</li></ul><p>This is exactly the problem <strong>async/await was designed to solve.</strong></p><h3>Suspension Points</h3><p>The keyword <em>await</em> creates a <strong>suspension point</strong>.</p><p>A suspension point means:</p><p>The function may pause execution and allow other tasks to run.</p><p>Example:</p><pre>func loadProfile() async {<br>    let user = await fetchUser()<br>    let posts = await fetchPosts(user.id)<br>    print(posts)<br>}</pre><p>At each <em>await</em>, the function may suspend.</p><p>But here is the important detail:</p><p>Suspension does <strong>not block the thread</strong>.</p><p>Swift stores the current state of the function and resumes it later when the result is ready.</p><p>Think of it like bookmarking a page in a book.</p><h3>Await Does Not Block the Thread</h3><p>This is one of the biggest misunderstandings.</p><p><em>await</em> does not block the thread.</p><p>Example:</p><pre>func example() async {<br>    print(&quot;Start&quot;)<br>    await Task.sleep(nanoseconds: 2_000_000_000)<br>    print(&quot;End&quot;)<br>}</pre><p>While waiting for the sleep to complete, the thread is free to execute other tasks.</p><p>If this were a blocking operation like <em>Thread.sleep</em>, the thread would remain occupied.</p><p>This difference is critical for scalability.</p><p>Blocking ties up threads.</p><p>Suspension frees them.</p><h3>Thread Is NOT Guaranteed After Await</h3><p>One of the <strong>most asked Swift concurrency questions</strong> is:</p><p><strong><em>Does execution continue on the same thread after await?</em></strong></p><p>The answer is <strong>NO</strong>.</p><p>Swift only guarantees <strong>actor isolation</strong>, not thread affinity.</p><p>Example:</p><pre>func example() async {<br>    print(Thread.current)<br><br>    await Task.sleep(nanoseconds: 1_000_000)<br>    print(Thread.current)<br>}</pre><p>The second print may show <strong>a different thread</strong>.</p><p>Key explanation:</p><ul><li>Swift uses a <strong>cooperative thread pool</strong></li><li>Tasks may <strong>resume on a different thread</strong></li></ul><p><strong>Await Does Not Guarantee Same Thread</strong></p><p>After a suspension point, Swift may resume execution on a <strong>different thread</strong>.</p><p>The concurrency runtime decides which thread executes the resumed task.</p><p>This is why <strong>UI updates must be done on <em>MainActor</em></strong>.</p><p>This concept is very important for interviews.</p><h3>Sequential Await Execution</h3><p>Multiple awaits written one after another run sequentially.</p><p>Example:</p><pre>func loadData() async {<br>    let user = await fetchUser()<br>    let posts = await fetchPosts(user.id)<br>    let comments = await fetchComments(posts.first!.id)<br>    print(comments)<br>}</pre><p>Execution order:</p><ol><li>Fetch user</li><li>Wait until complete</li><li>Fetch posts</li><li>Wait until complete</li><li>Fetch comments</li></ol><p>Each operation starts <strong>only after the previous finishes</strong>.</p><p>This is simple but may be slower if tasks are independent.</p><h3>Cancellation with Async/Await</h3><h4>Task Cancellation with Async Functions</h4><p>Example:</p><pre>func fetchData() async throws -&gt; Data {<br><br>    if Task.isCancelled {<br>        throw CancellationError()<br>    }<br><br>    let (data, _) = try await URLSession.shared.data(from: url)<br><br>    return data<br>}</pre><p>Usage:</p><pre>let task = Task {<br>    try await fetchData()<br>}<br><br>task.cancel()</pre><p>Important concept:</p><p>Cancellation in Swift is <strong>cooperative</strong>.</p><p>Tasks must check:</p><pre>Task.isCancelled</pre><p>or</p><pre>try Task.checkCancellation()</pre><p>This is <strong>frequently asked in interviews</strong>.</p><h3>Concurrent Execution with async let</h3><p>If tasks are independent, they can run concurrently.</p><p>Swift provides <em>async let</em> for this.</p><p>Example:</p><pre>func loadDashboard() async {<br>    async let user = fetchUser()<br>    async let notifications = fetchNotifications()<br>    async let messages = fetchMessages()<br><br>    let resultUser = await user<br>    let resultNotifications = await notifications<br>    let resultMessages = await messages<br>    print(resultUser, resultNotifications, resultMessages)<br>}</pre><p>Here:</p><p>All three network requests start <strong>at the same time</strong>.</p><p>Execution suspends only when awaiting their results.</p><p>This improves performance when tasks do not depend on each other.</p><h3>Important Rule of async let</h3><p>All <em>async let </em>variables must be awaited before leaving the scope.</p><p>This code will produce a compiler error:</p><pre>func example() async {<br>    async let user = fetchUser()<br>}</pre><p>Swift requires:</p><pre>let result = await user</pre><p>This rule exists because <em>async let </em>is part of <strong>structured concurrency</strong>.</p><p>Swift ensures that child tasks complete before exiting the scope.</p><h3>Error Handling with Async Functions</h3><p>Async functions can also throw errors.</p><p>Example:</p><pre>func fetchUser() async throws -&gt; User {<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return try JSONDecoder().decode(User.self, from: data)<br>}</pre><p>Calling code must handle both <em>await</em> and <em>try</em>.</p><pre>do {<br>    let user = try await fetchUser()<br>    print(user)<br>} catch {<br>    print(error)<br>}</pre><p>This keeps asynchronous error handling <strong>consistent with Swift’s existing error system</strong>.</p><h3>Real World Example in iOS</h3><p>Loading multiple API resources for a screen:</p><pre>func loadHomeScreen() async throws -&gt; HomeData {<br>    async let user = fetchUser()<br>    async let feed = fetchFeed()<br>    async let stories = fetchStories()<br>    return try await HomeData(<br>        user: user,<br>        feed: feed,<br>        stories: stories<br>    )<br>}</pre><p>All requests start immediately, improving loading performance.</p><p>This pattern is very common in production apps.</p><h3>Memory Management in Async/Await</h3><p>One important question developers ask is:</p><p>Does async/await introduce retain cycles?</p><p>The answer depends on how closures capture <em>self</em>.</p><p>Example:</p><pre>class ViewModel {<br>    func loadData() {<br>        Task {<br>            await fetchData()<br>        }<br>    }<br>    func fetchData() async {<br>        print(&quot;Fetching data&quot;)<br>    }<br>}</pre><p>Here the task captures <em>self</em>.</p><p>If the task runs long enough, the object may stay alive longer than expected.</p><p>This is similar to closures.</p><p>If needed, we can use weak references:</p><pre>Task { [weak self] in<br>    await self?.fetchData()<br>}</pre><p>This avoids retaining the object.</p><h3>Edge Case: Tasks Outliving the Object</h3><p>Consider this example:</p><pre>class ViewModel {<br>    func loadData() {<br>        Task {<br>            await fetchLargeData()<br>        }<br>    }<br>}</pre><p>If the view model is deallocated while the task is running, the task continues.</p><p>This can lead to unexpected behavior if the task tries to update UI afterward.</p><p>Better approach:</p><pre>Task { [weak self] in<br>    guard let self else { return }<br>    await fetchLargeData()<br>}</pre><p>This ensures work stops when the object disappears.</p><h3>Edge Case: Await Inside Loops</h3><p>Developers often write code like this:</p><pre>for id in ids {<br>    let user = await fetchUser(id)<br>    print(user)<br>}</pre><p>This executes sequentially.</p><p>If there are many requests, performance will suffer.</p><p>Better approach:</p><pre>await withTaskGroup(of: User.self) { group in<br>    for id in ids {<br>        group.addTask {<br>            await fetchUser(id)<br>        }<br>    }<br><br>    for await user in group {<br>        print(user)<br>    }<br>}</pre><p>This executes tasks concurrently.</p><h3>Edge Case: Suspension Points and State Changes</h3><p>Because async functions can suspend, program state may change between suspension points.</p><p>Example:</p><pre>func updateUser() async {<br>    let user = await fetchUser()<br><br>    await saveUser(user)<br>}</pre><p>Between <em>fetchUser</em> and <em>saveUser</em>, other tasks may run and modify shared state.</p><p>This is why Swift introduced <strong>actors</strong> for data isolation.</p><h3>When Not to Use Async Let</h3><p><em>async let</em> works best for <strong>small fixed sets of tasks</strong>.</p><p>If the number of tasks is dynamic, use <strong>Task Groups</strong> instead.</p><p>Example:</p><pre>await withTaskGroup(of: Data.self) { group in<br>    for url in urls {<br>        group.addTask {<br>            await fetch(url)<br>        }<br>    }<br>}</pre><h3>Key Takeaways</h3><p>Async functions allow Swift code to suspend execution without blocking threads.</p><p><em>await</em> marks suspension points where execution may pause.</p><p>Sequential awaits run tasks one after another.</p><p><em>async let</em> allows concurrent execution of independent tasks.</p><p><em>Async</em> functions integrate with Swift’s existing error handling.</p><p>Memory management still follows normal closure capture rules.</p><p>Suspension points introduce new edge cases where program state may change.</p><h3>Final Thoughts</h3><p>Async/await dramatically improves how asynchronous code is written in Swift. It makes code easier to read, reduces callback complexity, and integrates deeply with Swift’s structured concurrency model.</p><p>However, understanding suspension points, concurrency behavior, and memory management is essential to avoid subtle bugs in production systems.</p><p>Mastering these concepts will not only help you write better Swift code but will also prepare you for <strong>advanced iOS interview discussions around Swift concurrency</strong>.</p><p>Article in this series:</p><p><a href="https://medium.com/@aksingh20feb/dispatchqueue-in-ios-the-complete-interview-q-a-guide-swift-gcd-concurrency-1817e59b51e2">DispatchQueue &amp; GCD</a></p><p><a href="https://medium.com/@aksingh20feb/swift-concurrency-architecture-explained-ee1c831b6031">Swift Concurrency Architecture</a></p><p>Async Await Deep Dive(this article)</p><p><a href="https://medium.com/@aksingh20feb/swift-concurrency-deep-dive-task-task-detached-memory-management-cancellation-and-edge-cases-baec260c0171">Task &amp; Task.detached Deep Dive</a></p><p>If you enjoyed this deep dive, you might also like:</p><ul><li>My deep dive on <a href="https://medium.com/@aksingh20feb/understanding-swift-structs-value-types-memory-behavior-and-when-to-use-them-a3e37ea0196f"><strong>Swift structs and value semantics</strong></a></li><li><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8">Why Your Swift Struct Array Isn’t Mutating</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f2894d9777d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency: Task, Task.detached, Memory Management, Cancellation, and Edge Cases]]></title>
            <link>https://medium.com/@aksingh20feb/swift-concurrency-deep-dive-task-task-detached-memory-management-cancellation-and-edge-cases-baec260c0171?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/baec260c0171</guid>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 13:22:18 GMT</pubDate>
            <atom:updated>2026-03-19T11:34:43.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift 5.5 introduced a completely new concurrency model built around <strong>async/await, tasks, and actors</strong>.</p><p>Before Swift concurrency, asynchronous programming in iOS was mostly done using:</p><ul><li>Grand Central Dispatch (GCD)</li><li>completion handlers</li><li>OperationQueue</li></ul><p>While powerful, these approaches often resulted in:</p><ul><li>callback pyramids</li><li>complicated thread management</li><li>race conditions</li><li>memory management issues</li></ul><p>Swift concurrency introduces <strong>structured concurrency</strong>, which makes asynchronous code easier to read, safer, and more predictable.</p><p>At the center of this system is the <strong>Task</strong>.</p><p>In this article we will deeply explore:</p><ul><li>What a Task is in Swift</li><li>Task vs Thread</li><li>The lifecycle of a Task</li><li>Structured concurrency</li><li>Task hierarchy</li><li>Task cancellation</li><li>Task priorities</li><li>Task handles</li><li>SwiftUI .task Modifier</li><li>Task vs GCD</li><li>Task.detached</li><li>Memory Risks with Task.detached</li><li>Safe Pattern for Detached Tasks</li><li>Difference Between Task and Task.detached</li><li>Difference Between TaskGroup vs Task</li><li>Memory Management in Tasks</li><li>Memory Graph Explanation</li><li>Retain Cycle Example</li><li>Fixing Retain Cycles</li><li>Debugging with Memory Graph in Xcode</li><li>Edge Case: Actor Isolation Violation</li><li>Reentrancy with Tasks and Actors</li><li>Edge Case: UI Updates in Detached Tasks</li><li>Edge Case: Tasks Outliving View Controllers</li><li>Edge Case: Task.sleep</li><li>Edge Case: Tasks Outliving Scope</li></ul><p>This is a <strong>complete deep dive intended for serious Swift developers and interview preparation</strong>.</p><h3>What is a Task in Swift?</h3><p>A <strong>Task</strong> represents a unit of asynchronous work managed by Swift’s concurrency runtime.</p><p>When you create a task, Swift schedules that work to run concurrently.</p><p>Example:</p><pre>Task {<br>    let users = await fetchUsers()<br>    print(users)<br>}</pre><p>Here’s what happens internally:</p><ol><li>A task is created.</li><li>The Swift runtime schedules the task.</li><li>The task executes asynchronously.</li><li>If the task hits an <strong>await</strong>, it suspends without blocking a thread.</li><li>When the awaited operation completes, the task resumes.</li></ol><p>The important idea is that <strong>tasks are lightweight units of work</strong>, not operating system threads.</p><h3>Task vs Thread (how Swift schedules tasks)</h3><p>Many developers assume a task is just another name for a thread. This is not correct.</p><p>A <strong>thread</strong> is an OS-level execution unit created and managed by the operating system.</p><p>A <strong>task</strong> is a higher-level abstraction created and managed by the Swift concurrency runtime.</p><p>Threads are expensive resources. Creating too many threads can hurt performance and memory usage.</p><p>Tasks are lightweight and can be created in large numbers because they are scheduled onto a shared thread pool.</p><p>Conceptually the execution model looks like this:</p><pre>Task<br>  ↓<br>Swift Concurrency Runtime<br>  ↓<br>Thread Pool<br>  ↓<br>CPU Core</pre><p>Multiple tasks can execute on a single thread over time.</p><p>When a task reaches an <strong>await</strong>, it <strong>suspends</strong>, allowing the thread to execute other tasks.</p><p>This is one of the major performance benefits of Swift concurrency.</p><h3>The lifecycle of a Task</h3><p>Every task goes through several stages during its lifetime.</p><p>A simplified lifecycle looks like this:</p><pre>Task Created<br>      ↓<br>Scheduled by Runtime<br>      ↓<br>Running<br>      ↓<br>Suspended (await)<br>      ↓<br>Resumed<br>      ↓<br>Completed or Cancelled</pre><p>Example:</p><pre>Task {<br>    let user = await fetchUser()<br>    print(user)<br>}</pre><p>Execution flow:</p><ol><li>Task is created.</li><li>Swift runtime schedules the task.</li><li>Task starts executing.</li><li>When it reaches <strong>await</strong>, it suspends.</li><li>The thread becomes available for other work.</li><li>Once the awaited operation finishes, the task resumes.</li><li>Task finishes execution.</li></ol><p>The key difference from traditional threads is that <strong>tasks suspend rather than block threads</strong>.</p><h3>Structured Concurrency</h3><p>Structured concurrency ensures that tasks are organized in a predictable hierarchy.</p><p>Instead of creating random background work that lives forever, Swift ensures tasks belong to a structured tree.</p><p>Example:</p><pre>Parent Task<br>   ├── Child Task<br>   ├── Child Task<br>   └── Child Task</pre><p>Swift provides structured concurrency using constructs like:</p><ul><li>async let</li><li>TaskGroup</li></ul><p>Example:</p><pre>async let user = fetchUser()<br>async let posts = fetchPosts()<br><br>let result = await (user, posts)</pre><p>Here Swift automatically manages:</p><ul><li>task lifecycle</li><li>cancellation propagation</li><li>synchronization</li></ul><p>The parent task waits until its child tasks finish.</p><p>This greatly improves <strong>predictability and safety</strong>.</p><h3>Task Hierarchy</h3><p>Tasks can form hierarchical relationships.</p><p>Example hierarchy:</p><pre>Parent Task<br>   ├── Child Task A<br>   ├── Child Task B<br>   │      └── Grandchild Task<br>   └── Child Task C</pre><p>Child tasks inherit important properties from their parent, including:</p><ul><li>task priority</li><li>cancellation state</li><li>task-local values</li></ul><p>Example:</p><pre>Task(priority: .high) {<br><br>    Task {<br>        print(Task.currentPriority)<br>    }<br><br>}</pre><p>The child task inherits the parent’s priority.</p><h3>Task Cancellation</h3><p>Swift uses <strong>cooperative cancellation</strong>.</p><p>This means cancelling a task does not forcibly stop it. The task must check whether cancellation has occurred.</p><p>Example:</p><pre>let task = Task {<br>    for i in 1...100 {<br>        if Task.isCancelled {<br>            return<br>        }<br>        print(i)<br>    }<br>}<br><br>task.cancel()</pre><p>A better pattern is:</p><pre>try Task.checkCancellation()</pre><p>Example:</p><pre>Task {<br>    try Task.checkCancellation()<br>    await performWork()<br>}</pre><p>If the task is cancelled, <strong>checkCancellation</strong>() throws <strong>CancellationError</strong>.</p><h3>Task Priority</h3><p>Tasks can be assigned priorities to influence scheduling.</p><p>Example:</p><pre>Task(priority: .userInitiated) {<br>    await fetchProfile()<br>}</pre><p>Common priorities include:</p><ul><li>userInitiated (user triggered work)</li><li>utility (background work)</li><li>background (low priority tasks)</li></ul><p>Higher priority tasks are scheduled sooner by the runtime.</p><h3>Task Handles</h3><p>This is a <strong>very practical real-world concept</strong>.</p><p>Example:</p><pre>let task = Task {<br>    return await fetchUser()<br>}</pre><p>Here Task is actually a <strong>Task handle</strong></p><p>Type:</p><pre>Task&lt;Success, Failure&gt;</pre><p>Example:</p><pre>Task&lt;String, Error&gt;<br>Task&lt;Void, Never&gt;</pre><p>You can interact with it like this:</p><pre>task.cancel()<br><br>let value = await task.value<br><br>let result = await task.result</pre><p>Why this matters:</p><ul><li>it allows cancellation</li><li>it allows awaiting task results</li><li>it allows coordination between tasks</li></ul><p>This concept is <strong>fundamental to using tasks properly</strong>.</p><h3>SwiftUI .task modifier</h3><p>Example:</p><pre>Text(&quot;Hello&quot;)<br>.task {<br>    await viewModel.loadData()<br>}</pre><p>Important detail:</p><p>SwiftUI automatically <strong>cancels the task when the view disappears</strong>.</p><p>This ties tasks to the <strong>view lifecycle</strong>.</p><h3>Task vs GCD (Grand Central Dispatch)</h3><p>Before Swift concurrency, developers relied heavily on <strong>Grand Central Dispatch</strong>.</p><p>Example using GCD:</p><pre>DispatchQueue.global().async {<br><br>    let data = fetchData()<br><br>    DispatchQueue.main.async {<br>        updateUI(data)<br>    }<br><br>}</pre><p>Problems with this approach include:</p><ul><li>nested callbacks</li><li>manual thread switching</li><li>no built-in cancellation</li><li>difficult debugging</li></ul><p>The Swift concurrency equivalent:</p><pre>Task {<br>    let data = await fetchData()<br>    updateUI(data)<br>}</pre><p>Benefits include:</p><ul><li>readable code</li><li>structured concurrency</li><li>automatic thread management</li><li>built-in cancellation</li><li>actor isolation safety</li></ul><h3>Task.detached</h3><p>Task.detached creates a completely independent task.</p><p>Example:</p><pre>Task.detached {<br>    await processLargeFile()<br>}</pre><p>Detached tasks do <strong>not inherit context</strong> from the caller.</p><p>They do not inherit:</p><ul><li>actor isolation</li><li>task priority</li><li>cancellation state</li><li>task local values</li></ul><p>This makes them powerful but also dangerous if misused.</p><h3>Memory Risks with Task.detached</h3><p>Detached tasks are even more dangerous.</p><p>Example:</p><pre>Task.detached {<br>    await self.processData()<br>}</pre><p>Detached tasks may outlive the object that created them.</p><p>Memory graph may look like this:</p><pre>Detached Task<br>      ↓<br>Strong reference<br>      ↓<br>ViewModel<br>      ↓<br>ViewController</pre><p>Even if the UI disappears, the task continues running.</p><p>This may lead to:</p><ul><li>unexpected memory retention</li><li>unnecessary background work</li><li>crashes if UI is accessed</li></ul><h3>Safe Pattern for Detached Tasks</h3><p>Always capture weak references.</p><p>Example:</p><pre>Task.detached { [weak self] in<br>    guard let self else { return }<br>    await self.processData()<br>}</pre><h3>Difference Between Task and Task.detached</h3><p>A normal Task inherits execution context from the caller.</p><p>Example:</p><pre>@MainActor<br>func updateUI() {<br><br>    Task {<br>        print(Thread.isMainThread)<br>    }<br><br>}</pre><p>This prints true because the task inherits the <em>MainActor</em> context.</p><p>Now look at a detached task:</p><pre>@MainActor<br>func updateUI() {<br><br>    Task.detached {<br>        print(Thread.isMainThread)<br>    }<br><br>}</pre><p>This prints <em>false</em>.</p><p>Detached tasks run outside the caller’s actor context.</p><p>But the difference between <em>Task</em> and <em>Task.detached</em> goes much deeper.</p><h4>1. Actor Context Inheritance</h4><p><em>Task</em> inherits the <strong>actor context</strong> of the caller.</p><p>If the task is created inside a <em>@MainActor </em>function, it runs on the main actor unless it hops to another actor.</p><p>This makes it safe to perform UI work.</p><p><em>Task.detached</em> does <strong>not inherit any actor context</strong>, so it runs independently on the Swift’s cooperative thread pool.</p><p>This means UI-related work inside a detached task must explicitly switch back to the main actor.</p><p>Example:</p><pre>Task.detached {<br><br>    let data = await fetchData()<br><br>    await MainActor.run {<br>        updateUI(data)<br>    }<br><br>}</pre><p>If you forget to hop back to the main actor, you may introduce <strong>UI thread violations</strong>.</p><h4>2. Priority Inheritance</h4><p>Normal tasks inherit priority from their parent.</p><p>Example:</p><pre>Task(priority: .high) {<br>    Task {<br>        print(Task.currentPriority) // high<br>    }<br>}</pre><p>The child task inherits the parent priority.</p><p>But detached tasks do <strong>not inherit priority</strong>.</p><p>Example:</p><pre>Task.detached {<br>    print(Task.currentPriority) // default priority<br>}</pre><p>This usually prints <strong>default priority</strong> unless explicitly specified.</p><p>You can manually set priority:</p><pre>Task.detached(priority: .background) {<br>    performBackgroundWork()<br>}</pre><h4>3. Task-Local Value Inheritance</h4><p>Swift concurrency provides <strong>Task Local Values</strong>, which allow contextual information to flow through tasks.</p><p>Normal tasks inherit these values.</p><p>Example:</p><pre>enum RequestID {<br>    @TaskLocal static var current: String?<br>}<br><br>Task {<br>    await RequestID.$current.withValue(&quot;ABC123&quot;) {<br><br>        Task {<br>            print(RequestID.current) // ABC123<br>        }<br><br>    }<br>}</pre><p>The inner task inherits the task-local value.</p><p>But a detached task <strong>does not inherit task-local values</strong>.</p><pre>Task.detached {<br>    print(RequestID.current) // nil<br>}</pre><p>This happens because detached tasks <strong>do not belong to the same task hierarchy</strong>.</p><h4>4. Task Hierarchy and Structured Concurrency</h4><p>A normal Task created inside another task becomes part of the <strong>task hierarchy</strong>.</p><p>This means:</p><ul><li>Parent tasks are aware of child tasks</li><li>Cancellation can propagate</li><li>Task lifetimes are better structured</li></ul><p>Example:</p><pre>Task {<br><br>    let child = Task {<br>        await work()<br>    }<br><br>}</pre><p>This child task belongs to the parent task’s <strong>execution tree</strong>.</p><p>Detached tasks are <strong>not part of this hierarchy</strong>.</p><pre>Task.detached {<br>    await work()<br>}</pre><p>This task runs independently and is <strong>not connected to any parent task</strong>.</p><p>Detached tasks behave more like <strong>fire-and-forget background work</strong>.</p><h4>5. Cancellation Propagation</h4><p>Because normal tasks are part of the hierarchy, <strong>cancellation propagates automatically</strong>.</p><p>Example:</p><pre>let parent = Task {<br>    Task {<br>        await longRunningTask()<br>    }<br>}<br><br>parent.cancel()</pre><p>When the parent task is cancelled, the child task can observe the cancellation.</p><p>But detached tasks <strong>do not receive cancellation automatically</strong>.</p><p>Example:</p><pre>let parent = Task {<br>    Task.detached {<br>        await longRunningTask()<br>    }<br>}<br><br>parent.cancel()</pre><p>The detached task <strong>keeps running</strong> unless you manually check for cancellation.</p><h4>6. Memory and Lifetime Behavior</h4><p>Because detached tasks are not tied to a parent task, they may <strong>outlive the scope that created them</strong>.</p><p>Example:</p><pre>class DataLoader {<br>    func load() {<br>        Task.detached {<br>            await fetchData()<br>        }<br>    }<br>}</pre><p>Even if the <em>DataLoader</em> instance is deallocated, the detached task <strong>may continue running</strong>.</p><p>This can cause unexpected memory retention or resource usage if the task strongly captures objects.</p><p>Normal tasks are safer because their lifetime is more closely tied to the task hierarchy.</p><h4>7. When Should You Use Task.detached?</h4><p>Detached tasks should be used <strong>rarely</strong> and only when you intentionally want to break out of the structured concurrency system.</p><p>Typical use cases include:</p><ul><li>Background cleanup work</li><li>Fire-and-forget analytics logging</li><li>Independent background processing</li><li>Work that should not inherit actor context</li></ul><p>Example:</p><pre>Task.detached(priority: .background) {<br>    await analyticsService.uploadLogs()<br>}</pre><h4>8. When You Should NOT Use Task.detached</h4><p>Avoid detached tasks when:</p><ul><li>You need cancellation propagation</li><li>You need actor isolation</li><li>You rely on task-local values</li><li>The work should belong to a parent task</li></ul><p>In most application code, <strong>a normal Task is the safer choice</strong>.</p><h3>Difference Between TaskGroup vs Task</h3><p>Since you’re explaining <strong>structured concurrency</strong>, you should briefly show the <strong>correct structured alternative</strong> to spawning tasks.</p><p>Example:</p><p>Instead of doing this:</p><pre>Task {<br>    Task {<br>        await fetchA()<br>    }<br><br>    Task {<br>        await fetchB()<br>    }<br>}</pre><p>Structured approach:</p><pre>await withTaskGroup(of: Void.self) { group in<br>    group.addTask {<br>        await fetchA()<br>    }<br><br>    group.addTask {<br>        await fetchB()<br>    }<br>}</pre><p>Explain:</p><ul><li>TaskGroup ensures <strong>lifecycle management</strong></li><li>Tasks automatically cancel when parent finishes</li><li>Avoids orphan tasks</li></ul><h3>Memory Management in Tasks</h3><p>Tasks themselves don’t create retain cycles automatically. However, <strong>closures inside tasks capture references strongly by default</strong>, which can lead to retain cycles when tasks are stored as properties.</p><p>Example:</p><pre>class ViewModel {<br><br>    func fetchData() {<br><br>        Task {<br>            await loadData()<br>        }<br><br>    }<br><br>}</pre><p>Here the task captures <em>self</em> strongly.</p><p>This means the task keeps the object alive until the task finishes.</p><h3>Memory Graph Explanation</h3><p>Consider this structure:</p><pre>ViewController<br>      ↓<br>ViewModel<br>      ↓<br>Task<br>      ↓<br>Closure<br>      ↓<br>Strong reference to ViewModel</pre><p>Because the closure holds a strong reference to the ViewModel, the object cannot be deallocated while the task is running.</p><p>If the task is long running, this may keep the entire UI hierarchy alive.</p><h3>Retain Cycle Example</h3><p>Example:</p><pre>class ViewModel {<br><br>    var task: Task&lt;Void, Never&gt;?<br><br>    func start() {<br><br>        task = Task {<br>            await self.loadData()<br>        }<br><br>    }<br><br>}</pre><p>Memory graph looks like this:</p><pre>ViewModel<br>   ↓<br>Task property<br>   ↓<br>Task<br>   ↓<br>Closure<br>   ↓<br>ViewModel</pre><p>This creates a <strong>retain cycle</strong>.</p><p>The ViewModel owns the task, and the task owns the ViewModel.</p><p>Neither can be deallocated.</p><h3>Fixing Retain Cycles</h3><p>Use weak references when capturing self.</p><p>Example:</p><pre>task = Task { [weak self] in<br>    guard let self else { return }<br>    await self.loadData()<br>}</pre><p>Memory graph now becomes:</p><pre>ViewModel<br>   ↓<br>Task<br>   ↓<br>Closure<br>   ↓<br>Weak reference to ViewModel</pre><p>This breaks the retain cycle.</p><h3>Debugging with Memory Graph in Xcode</h3><p>Xcode provides a powerful <strong>Memory Graph Debugger</strong>.</p><p>You can open it from:</p><pre>Debug Navigator → Memory Graph</pre><p>If a task is retaining an object, you might see something like:</p><pre>Task<br> ↓<br>Closure Context<br> ↓<br>ViewModel<br> ↓<br>ViewController</pre><p>This indicates the task is preventing deallocation.</p><h3>Edge Case: Actor Isolation Violation</h3><p>Example:</p><pre>actor DataStore {<br><br>    var value = 0<br><br>    func update() {<br><br>        Task.detached {<br>            value = 10<br>        }<br><br>    }<br><br>}</pre><p>This breaks actor isolation rules.</p><p>Correct solution:</p><pre>Task.detached {<br>    await self.setValue()<br>}</pre><h3>Reentrancy with Tasks and Actors</h3><p>Since your article talks about actors and tasks, you should mention <strong>actor reentrancy</strong>.</p><p>This is a <strong>very common interview question</strong>.</p><p>Example:</p><pre>actor Counter {<br><br>    var value = 0<br><br>    func increment() async {<br>        value += 1<br>        await Task.sleep(1_000_000)<br>        value += 1<br>    }<br><br>}</pre><p>During the await , the actor <strong>may process other tasks</strong>, causing unexpected interleaving.</p><p>Example:</p><pre>Task A → increment()<br>Task B → increment()</pre><p>Possible execution order:</p><pre>value += 1  (Task A)<br>value += 1  (Task B)<br>resume A<br>value += 1<br>resume B<br>value += 1</pre><p>This is called <strong>actor reentrancy</strong>.</p><h3>Edge Case: UI Updates in Detached Tasks</h3><p>Incorrect:</p><pre>Task.detached {<br>    label.text = &quot;Updated&quot;<br>}</pre><p>This can cause race conditions.</p><p>Correct approach:</p><pre>Task.detached {<br>    await MainActor.run {<br>        label.text = &quot;Updated&quot;<br>    }<br>}</pre><h3>Edge Case: Tasks Outliving View Controllers</h3><p>Example:</p><pre>class ViewController: UIViewController {<br><br>    override func viewDidLoad() {<br><br>        Task.detached {<br>            await longRunningTask()<br>        }<br><br>    }<br><br>}</pre><p>If the user navigates away from the screen, the task continues running.</p><p>This can lead to unnecessary work and memory retention.</p><h3>Edge Case: Task.sleep</h3><p>This is a <strong>very common mistake</strong>.</p><p>Example:</p><pre>Task {<br>    try await Task.sleep(nanoseconds: 2_000_000_000)<br>}</pre><p>Important detail:</p><p>Task.sleep <strong>throws if task is cancelled</strong>.</p><p>Example:</p><pre>do {<br>    try await Task.sleep(nanoseconds: 2_000_000_000)<br>} catch {<br>    print(&quot;Task cancelled during sleep&quot;)<br>}</pre><h3>Edge Case: Tasks Outliving Scope</h3><p>Another important edge case is <strong>tasks continuing after the parent scope ends</strong>.</p><p>Example:</p><pre>func startTask() {<br>    Task {<br>        await longRunningOperation()<br>    }<br>}</pre><p>Even if the function returns, the task continues running.</p><p>This can lead to:</p><ul><li>background work continuing unexpectedly</li><li>memory retention</li><li>difficult debugging</li></ul><p>This is why <strong>structured concurrency is preferred when possible</strong>.</p><h3>Advanced Edge Cases with Task and Task.detached</h3><p>While <strong>Task</strong> and <strong>Task.detached</strong> look simple, their behavior in complex applications can lead to subtle issues. Understanding these edge cases helps avoid difficult debugging scenarios in production apps.</p><h4>1. Actor Context Loss with Task.detached</h4><p>One of the biggest pitfalls of <strong>Task.detached </strong>is that it <strong>does not inherit actor context</strong>.</p><p>Example:</p><pre>@MainActor<br>class ViewModel {<br><br>    func update() {<br><br>        Task.detached {<br>            print(Thread.isMainThread)<br>        }<br><br>    }<br><br>}</pre><p>Many developers expect this to run on the main thread, but it does not.</p><p>Because <strong>Task.detached </strong>ignores the caller’s actor, it runs on the <strong>global executor instead of the MainActor</strong>.</p><p>Output:</p><pre>false</pre><p>If you need to update UI safely, you must explicitly hop back to the main actor.</p><p>Correct approach:</p><pre>Task.detached {<br>    await MainActor.run {<br>        print(&quot;UI update&quot;)<br>    }<br>}</pre><p>Failing to do this may cause <strong>UI race conditions or crashes</strong>.</p><h4>2. Priority Inheritance Differences</h4><p>Normal tasks inherit priority from their parent.</p><p>Example:</p><pre>Task(priority: .userInitiated) {<br><br>    Task {<br>        print(Task.currentPriority)<br>    }<br><br>}</pre><p>Output:</p><pre>userInitiated</pre><p>But detached tasks do <strong>not inherit priority</strong>.</p><p>Example:</p><pre>Task(priority: .userInitiated) {<br><br>    Task.detached {<br>        print(Task.currentPriority)<br>    }<br><br>}</pre><p>Output may be:</p><pre>default</pre><p>This means detached tasks might run <strong>slower than expected</strong> if priority is not explicitly specified.</p><p>Correct approach:</p><pre>Task.detached(priority: .userInitiated) {<br>    await performWork()<br>}</pre><h4>3. Detached Tasks Can Become Orphan Tasks</h4><p>Because detached tasks are independent, they may continue running <strong>long after the originating scope is gone</strong>.</p><p>Example:</p><pre>func startProcessing() {<br><br>    Task.detached {<br>        await longRunningWork()<br>    }<br><br>}</pre><p>Once <em>startProcessing()</em> returns, the detached task <strong>still continues executing</strong>.</p><p>This creates what is known as an <strong>orphan task</strong>.</p><p>Potential problems include:</p><ul><li>background work continuing unnecessarily</li><li>increased CPU usage</li><li>memory retention</li><li>difficult debugging</li></ul><p>This is why detached tasks should be used <strong>only when truly independent work is required</strong>.</p><h4>4. Unexpected Retention When Capturing Self</h4><p>Tasks capture variables strongly by default.</p><p>Example:</p><pre>class DataManager {<br><br>    func load() {<br><br>        Task {<br>            await self.fetchData()<br>        }<br><br>    }<br><br>}</pre><p>If the task runs for a long time, the object cannot be deallocated.</p><p>The memory graph may look like this:</p><pre>ViewController<br>      ↓<br>DataManager<br>      ↓<br>Task<br>      ↓<br>Closure<br>      ↓<br>DataManager</pre><p>If the task is stored as a property, this may create a <strong>retain cycle</strong>.</p><p>Correct approach:</p><pre>Task { [weak self] in<br>    guard let self else { return }<br>    await self.fetchData()<br>}</pre><h4>5. Tasks Outliving UI Components</h4><p>Another subtle issue occurs when tasks outlive UI components.</p><p>Example:</p><pre>class ViewController: UIViewController {<br><br>    override func viewDidLoad() {<br><br>        Task {<br>            await loadLargeData()<br>        }<br><br>    }<br><br>}</pre><p>If the user navigates away from the screen, the task may still be running.</p><p>If the task later tries to update UI, it can cause unexpected behavior.</p><p>This is why tasks should often be <strong>cancelled when the owning object is deallocated</strong>.</p><p>Example:</p><pre>deinit {<br>    task?.cancel()<br>}</pre><h3>When Should You Use Task.detached?</h3><p>Use <strong>Task.detached </strong>only when:</p><ul><li>the work is completely independent</li><li>it should not inherit actor context</li><li>it should not inherit cancellation</li><li>it should run outside the structured concurrency tree</li></ul><p>In most application code, <strong>regular Task {} is the safer choice</strong>.</p><h3>Best Practices</h3><p>Prefer using <strong>Task</strong> over <strong>Task.detached</strong>.</p><p>Use <strong>Task.detached </strong>only for independent background work.</p><p>Always consider weak references when tasks capture objects.</p><p>Check for cancellation in long-running tasks.</p><p>Never update UI directly inside detached tasks.</p><h3>Final Thoughts</h3><p>Swift’s concurrency model introduces a powerful abstraction called <strong>Task</strong> that simplifies asynchronous programming.</p><p>Understanding tasks deeply is important because they affect:</p><ul><li>performance</li><li>memory management</li><li>thread safety</li><li>app architecture</li></ul><p>Key takeaways:</p><p>Tasks are lightweight asynchronous units managed by the Swift runtime.</p><p>They suspend instead of blocking threads.</p><p>Structured concurrency provides predictable task lifecycles.</p><p><strong>Task.detached</strong> creates independent tasks but must be used carefully.</p><p>Tasks capture references strongly by default, which can cause retain cycles.</p><p>Understanding these behaviors helps you build <strong>safe, performant, and scalable Swift applications</strong>.</p><p>Article in this series:</p><p><a href="https://medium.com/@aksingh20feb/dispatchqueue-in-ios-the-complete-interview-q-a-guide-swift-gcd-concurrency-1817e59b51e2">DispatchQueue &amp; GCD</a></p><p><a href="https://medium.com/@aksingh20feb/swift-concurrency-architecture-explained-ee1c831b6031">Swift Concurrency Architecture</a></p><p><a href="https://medium.com/@aksingh20feb/swift-concurrency-async-await-how-it-really-works-suspension-points-concurrency-and-memory-0f2894d9777d">Async Await Deep Dive</a></p><p>Task &amp; Task.detached Deep Dive(This Article)</p><p>If you enjoyed this deep dive, you might also like:</p><ul><li>My deep dive on <a href="https://medium.com/@aksingh20feb/understanding-swift-structs-value-types-memory-behavior-and-when-to-use-them-a3e37ea0196f"><strong>Swift structs and value semantics</strong></a></li><li><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8">Why Your Swift Struct Array Isn’t Mutating</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baec260c0171" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Swift Structs: Value Types, Memory Behavior, and When to Use Them]]></title>
            <link>https://medium.com/@aksingh20feb/understanding-swift-structs-value-types-memory-behavior-and-when-to-use-them-a3e37ea0196f?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e37ea0196f</guid>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[value-type]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 18:52:26 GMT</pubDate>
            <atom:updated>2026-03-09T07:15:39.110Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift uses <strong>structs everywhere</strong>.</p><p>From <em>String</em>, <em>Array</em>, and <em>Dictionary</em> to <em>CGRect</em>, <em>URL</em>, and <em>Date</em>, many of Swift’s most important types are implemented as <strong>structs</strong>.</p><p>But why?</p><p>Why did Swift choose structs so heavily compared to many other languages?</p><p>And what actually happens in memory when structs are copied?</p><p>In this article, we’ll deeply explore:</p><ul><li>What structs are</li><li>Struct initializers (memberwise initializer)</li><li>Mutating functions in structs</li><li>How value semantics work</li><li>Memory behavior of structs</li><li>Structs inside collections</li><li>Structs containing reference types</li><li>Real examples of structs in Swift</li><li>When to use structs in real applications</li></ul><p>This article is part of the <strong>Swift Memory &amp; Type System Series</strong>.</p><h3>Swift Memory &amp; Type System Series</h3><p>1. <strong>Understanding Swift Structs</strong> <em>(this article)</em></p><p>2. <strong>Classes vs Structs in iOS (Interview Guide)</strong><br><a href="https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021">https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021</a></p><p>3. <strong>Why Your Swift Struct Array Isn’t Mutating</strong><br><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8">https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8</a></p><p>4. <strong>Understanding Swift Classes</strong><br><a href="https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e">https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e</a></p><p>5. <strong>Understanding ARC in Swift (Strong / Weak / Unowned)</strong><br><a href="https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9">https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9</a></p><p>6. <strong>ARC in Classes vs Structs — Runtime Deep Dive</strong><br><a href="https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2">https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2</a></p><h3>What is a Struct in Swift?</h3><p>A <strong>struct</strong> is a <strong>value type</strong> in Swift.</p><p>Value types mean that <strong>the entire value is copied when assigned or passed to another variable or function</strong>.</p><p>Example:</p><pre>struct User {<br>    var name: String<br>}<br><br>var user1 = User(name: &quot;Akanksha&quot;)<br>var user2 = user1<br>user2.name = &quot;Singh&quot;<br>print(user1.name) // Akanksha<br>print(user2.name) // Singh</pre><p>Here:</p><pre>user1 and user2 are independent values</pre><p>Changing user2 <strong>does not affect</strong> user1 .</p><p>This behavior is called <strong>Value Semantics</strong>.</p><h3>Struct Initializers (Memberwise initializer)</h3><p>This is another <strong>very common interview question</strong>.</p><p>Example:</p><pre>struct User {<br>    var name: String<br>    var age: Int<br>}<br><br>let user = User(name: &quot;Akanksha&quot;, age: 30)</pre><p>Explain:</p><p>Swift automatically provides <strong>memberwise initializer</strong> for structs.</p><p>You can customize:</p><pre>struct User {<br>    var name: String<br>    var age: Int<br>    <br>    init(name: String) {<br>        self.name = name<br>        self.age = 18<br>    }<br>}</pre><h3>Mutating Functions in Structs</h3><p>If a struct function modifies its own properties, it must be marked <em>mutating</em>.</p><p>Example:</p><pre>struct Counter {<br>    var value = 0<br>    <br>    mutating func increment() {<br>        value += 1<br>    }<br>}<br>var counter = Counter()<br>counter.increment()<br>print(counter.value) // 1</pre><p>Why is <em>mutating </em>required?</p><ul><li>Struct methods <strong>cannot modify properties</strong> unless marked <em>mutating</em></li><li>Because structs follow <strong>value semantics</strong></li><li>Because modifying a struct means <strong>replacing the entire value</strong>, not modifying a reference.</li></ul><p>Since structs are value types, Swift requires explicit permission to modify <em>self</em>. The <em>mutating </em>keyword tells the compiler that the method will change the struct’s stored properties.</p><h3>How value semantics work</h3><p>Structs are typically stored <strong>directly where the variable lives</strong>, often on the <strong>stack</strong>.</p><p>Example:</p><pre>struct Point {<br>    var x: Int<br>    var y: Int<br>}<br><br>var p1 = Point(x: 10, y: 20)<br>var p2 = p1</pre><p>Conceptual memory layout:</p><pre>Stack<br><br>p1 → (10,20)<br>p2 → (10,20)</pre><p>When p2 = p1, Swift copies the value.</p><p>Advantages:</p><ul><li>predictable behavior</li><li>thread safety</li><li>no shared mutation</li></ul><h3>Memory Behavior of Structs in Swift</h3><p>Understanding how structs behave in memory is important to truly understand <strong>value semantics in Swift</strong>.</p><p>Structs are <strong>value types</strong>, which means when you assign or pass them, <strong>a copy of the value is created</strong> instead of sharing the same memory reference.</p><p>This behavior makes structs <strong>predictable and safer</strong>, because modifying one instance does not affect another.</p><p>Example</p><pre>struct User {<br>    var name: String<br>    var age: Int<br>}<br><br>var user1 = User(name: &quot;Akanksha&quot;, age: 30)<br>var user2 = user1<br><br>user2.name = &quot;Singh&quot;<br><br>print(user1.name) // Akanksha<br>print(user2.name) // Singh</pre><p>Here:</p><ul><li><em>user2</em> receives a <strong>copy</strong> of <em>user1</em></li><li>Changing <em>user2 </em><strong>does not affect</strong> <em>user1</em></li></ul><p>This happens because structs follow <strong>value semantics</strong>.</p><h3>Stack vs Heap Allocation</h3><p>Many developers assume that structs are always stored on the <strong>stack</strong>, but that is not strictly true.</p><p>Swift uses <strong>compiler optimizations</strong> to decide where a value should live.</p><p>In most cases:</p><ul><li>Small value types are <strong>stored on the stack</strong></li><li>Larger values or escaped values may be <strong>allocated on the heap</strong></li></ul><p>For example:</p><ul><li>Local struct variables are often placed on the <strong>stack</strong></li><li>Structs captured by <strong>escaping closures</strong> may move to the <strong>heap</strong></li></ul><p>Example:</p><pre>struct DataHolder {<br>    var value: Int<br>}<br><br>var closures: [() -&gt; Void] = []<br><br>let data = DataHolder(value: 10)<br><br>closures.append {<br>    print(data.value)<br>}</pre><p>Because the closure <strong>escapes the current scope</strong>, Swift may allocate the struct on the <strong>heap</strong>.</p><p>The key point is:</p><blockquote><em>Structs are value types, but their exact memory location (stack or heap) is determined by Swift’s compiler optimizations.</em></blockquote><h3>Why Value Types Improve Safety</h3><p>Value semantics provide several benefits:</p><p><strong>1. No shared mutable state</strong></p><p>Each variable holds its <strong>own copy</strong> of data.</p><p><strong>2. Safer concurrency</strong></p><p>Multiple threads can work with independent copies without unexpected side effects.</p><p><strong>3. Predictable behavior</strong></p><p>Modifying one instance never changes another instance accidentally.</p><p>This is one reason Swift encourages developers to prefer <strong>structs for data models</strong>.</p><h3>Structs Inside Collections</h3><p>Structs are commonly stored inside Swift collections such as:</p><ul><li>Array</li><li>Dictionary</li><li>Set</li></ul><p>Since structs are value types, <strong>collections store copies of struct values</strong> rather than references.</p><h3>Struct Immutability</h3><p>Structs declared with let cannot be modified.</p><p>Example:</p><pre>let user = User(name: &quot;Akanksha&quot;)<br>user.name = &quot;Singh&quot;</pre><p>Compiler error:</p><pre>Cannot assign to property: &#39;user&#39; is a &#39;let&#39; constant</pre><p>Correct version:</p><pre>var user = User(name: &quot;Akanksha&quot;)<br>user.name = &quot;Singh&quot;</pre><p>This rule enforces <strong>data safety and immutability</strong>.</p><h3>Structs Passed Into Functions</h3><p>When structs are passed to functions, they are <strong>copied by default</strong>.</p><p>Example:</p><pre>struct Score {<br>    var value: Int<br>}<br><br>func updateScore(_ score: Score) {<br>    var score = score<br>    score.value = 100<br>}<br>var playerScore = Score(value: 10)<br>updateScore(playerScore)<br>print(playerScore.value) // 10</pre><p>The original value remains unchanged.</p><h3>Structs Inside Arrays</h3><p>Structs behave differently inside arrays.</p><p>Example:</p><pre>struct Product {<br>    var price: Double<br>}<br><br>var products = [<br>    Product(price: 100),<br>    Product(price: 200)<br>]</pre><p>Attempting mutation inside forEach:</p><pre>products.forEach { product in<br>    // product.price += 10<br>}</pre><p>This will <strong>not mutate the array elements</strong>.</p><p>Why?</p><p>Because product is a <strong>copy of the struct</strong>.</p><p>Correct approach:</p><pre>for index in products.indices {<br>    products[index].price += 10<br>}</pre><p>This topic is explained deeply in this article:</p><p><strong>Why Your Swift Struct Array Isn’t Mutating</strong></p><p><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8">https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8</a></p><h3>Structs Containing Reference Types</h3><p><strong><em>When Structs may be stored on Heap</em></strong></p><p>Most articles incorrectly say <strong>“struct = stack”</strong> which is <strong>not always true</strong>.</p><p>Important edge cases:</p><p>Structs can move to heap when:</p><ol><li>Captured by escaping closures</li><li>Large value types</li><li>Stored inside reference types</li><li>Copy-on-Write collections</li></ol><p>Even though structs are value types, they can <strong>store references to classes</strong>.</p><p>Example:</p><pre>class Address {<br>    var city: String<br>    init(city: String) {<br>        self.city = city<br>    }<br>}<br><br>struct Person {<br>    var name: String<br>    var address: Address<br>}<br>let addr = Address(city: &quot;Delhi&quot;)<br>var p1 = Person(name: &quot;A&quot;, address: addr)<br>var p2 = p1<br>p2.address.city = &quot;Mumbai&quot;</pre><p>Result:</p><pre>p1.address.city → Mumbai<br>p2.address.city → Mumbai</pre><p>Why?</p><p>Because the <strong>class reference is shared</strong>.</p><p>Memory model:</p><pre>Stack<br><br>p1 → reference<br>p2 → reference<br>Heap<br>Address object<br>city = Mumbai</pre><p>This behavior becomes important when understanding <strong>ARC behavior</strong>.</p><p>Learn more here:</p><p><strong>ARC in Classes vs Structs</strong></p><p><a href="https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2">https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2</a></p><h3>Struct Copying in Collections (Copy-on-Write)</h3><p>Swift collections like <em>Array, Dictionary </em>and<em> String </em>use <strong>Copy-on-Write (CoW), </strong>optimization, meaning copies are only created when the data is modified. This keeps structs efficient even with large data.</p><p>Example:</p><pre>var numbers = [1,2,3]<br>var numbersCopy = numbers</pre><p>Initially both arrays share memory.</p><pre>numbers<br>numbersCopy<br>   ↓<br>Shared Storage</pre><p>When one array changes:</p><pre>numbers.append(4)</pre><p>Swift creates a <strong>new copy</strong>.</p><pre>numbers → new storage<br>numbersCopy → old storage</pre><p>This gives the <strong>performance of references with safety of value types</strong>.</p><h3>Protocol Conformance with Structs</h3><p>Very common in Swift architecture.</p><p>Example:</p><pre>protocol IdentifiableUser {<br>    var id: Int { get }<br>}<br><br>struct User: IdentifiableUser {<br>    let id: Int<br>}</pre><p>Swift promotes <strong>Protocol-Oriented Programming</strong>.</p><h3>Immutability Advantage</h3><pre>struct User {<br>    let name: String<br>    let age: Int<br>}</pre><p>Benefits:</p><ul><li>thread safety</li><li>predictable state</li><li>easier debugging</li></ul><h3>Real Examples of Structs in Swift</h3><p>Apple frameworks heavily use structs.</p><p>Examples:</p><pre>String<br>Array<br>Dictionary<br>URL<br>Date<br>CGRect<br>CGSize<br>CGPoint</pre><p>Example:</p><pre>var rect1 = CGRect(x: 0, y: 0, width: 100, height: 100)<br>var rect2 = rect1<br><br>rect2.size.width = 200<br>print(rect1.size.width) // 100</pre><p>The values are copied.</p><h3>When Should You Use Structs?</h3><p>Structs are ideal for:</p><ul><li>Data models</li><li>Network responses</li><li>Configuration values</li><li>UI layout values</li><li>Immutable objects</li></ul><p>Example:</p><pre>struct APIResponse {<br>    let id: Int<br>    let name: String<br>    let email: String<br>}</pre><h3>When Structs Are Not Ideal</h3><p>Structs are not suitable when you need:</p><ul><li>Shared mutable state</li><li>Identity semantics</li><li>Inheritance</li><li>Reference-based lifecycle</li></ul><p>These cases are better suited for <strong>classes</strong>.</p><p>You can learn more here:</p><p><strong>Classes vs Structs</strong></p><p><a href="https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021">https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021</a></p><h3>Final Thoughts</h3><p>Structs are one of Swift’s most powerful design choices.</p><p>They provide:</p><ul><li>Predictability</li><li>Safety</li><li>Performance</li></ul><p>Understanding structs deeply helps you reason about:</p><ul><li>memory behavior</li><li>mutation bugs</li><li>concurrency safety</li><li>data modeling</li></ul><p>Mastering structs is the <strong>first step to understanding Swift’s memory model and runtime behavior</strong>.</p><p>Follow the series to continue exploring <strong>Swift memory management and advanced runtime concepts</strong>.</p><h3>Swift Struct Interview Questions</h3><p>Example:</p><p><strong>Q1: What is the difference between struct and class in Swift?</strong></p><p>Answer briefly.</p><p><strong>Q2: Why are structs safer for concurrency?</strong></p><p>Because:</p><ul><li>value semantics</li><li>no shared mutable state</li></ul><p><strong>Q3: Why are Array and String structs even though they are large?</strong></p><p>Answer:</p><ul><li>Copy-on-write optimization.</li></ul><h3>Next Article in the Series</h3><p>Now that we understand <strong>struct behavior</strong>, the next step is comparing them with reference types.</p><p>Next article:</p><p><strong>Classes vs Structs in Swift</strong></p><p><a href="https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021">https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021</a></p><p>In that article we explore:</p><ul><li>value vs reference semantics</li><li>stack vs heap behavior</li><li>identity vs equality</li><li>performance differences</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e37ea0196f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ARC in Classes vs Structs in Swift — Deep Dive with Runtime Behavior & Edge Cases]]></title>
            <link>https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c37064690b2</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[arc-in-swift]]></category>
            <category><![CDATA[automatic-reference-count]]></category>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[retain-cycle]]></category>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 08:01:18 GMT</pubDate>
            <atom:updated>2026-03-06T08:36:55.891Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swift Memory &amp; Value Semantics Deep Dive Series</strong></p><p>This article is part of a series exploring how Swift handles value types, reference types, and memory management.</p><p>Start with the foundation or continue the series:</p><ol><li>Classes vs Structs in Swift (Interview Guide)<br><a href="https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021">https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021</a></li><li>Understanding Swift Classes: Properties, Initializers, Memory Management &amp; ARC<br><a href="https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e">https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e</a></li><li>ARC in Classes vs Structs in Swift — Deep Dive with Runtime Behavior &amp; Edge Cases<br><a href="https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2">https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2</a></li><li>Understanding ARC in Swift: Strong, Weak, and Unowned Explained Deeply<br><a href="https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9">https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9</a></li><li>Why Your Swift Struct Array Isn’t Mutating<br><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8">https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8</a></li></ol><p>In the previous article, we explored understanding Swift Classes.</p><p>Now we extend that understanding to something more foundational:</p><p>Why ARC exists only for classes, and what actually happens with structs.</p><p>This distinction affects performance, thread safety, architecture decisions, and SwiftUI design patterns.</p><h3>1. The Fundamental Rule</h3><p>ARC applies only to reference types.</p><p>In Swift:</p><ul><li>class is a reference type and uses ARC</li><li>struct is a value type and is not reference counted</li></ul><p>That rule defines the entire behavior difference.</p><h3>2. ARC with Classes — Runtime Behavior</h3><p>Consider:</p><pre>class Person {<br>    var name: String<br>    <br>    init(name: String) {<br>        self.name = name<br>    }<br>    <br>    deinit {<br>        print(&quot;Person deallocated&quot;)<br>    }<br>}<br><br>var p1: Person? = Person(name: &quot;Akanksha&quot;)</pre><h4>What Happens Internally</h4><ol><li>Memory for the Person instance is allocated on the heap.</li><li>The variable p1 is stored on the stack.</li><li>p1 stores a pointer to the heap object.</li><li>The reference count becomes 1.</li></ol><p>Graph:</p><pre>STACK                              HEAP<br>-------------------------------------------------<br>p1  ---------------------&gt;   [ Person object ]<br>                                 name: &quot;Akanksha&quot;<br>                                 RC = 1</pre><p>Now:</p><pre>var p2 = p1</pre><p>The pointer is copied.</p><p>The compiler inserts a retain call.</p><p>The reference count becomes 2.</p><pre>STACK                              HEAP<br>-------------------------------------------------<br>p1 --------┐<br>           │<br>p2 --------┘----------------&gt; [ Person object ]<br>                                    name: &quot;Akanksha&quot;<br>                                    RC = 2</pre><p>If:</p><pre>p1 = nil</pre><p>The compiler inserts a release call.</p><p>The reference count becomes 1.</p><p>The object remains alive.</p><p>If:</p><pre>p2 = nil</pre><p>The reference count becomes 0.</p><p>The deinitializer runs.</p><p>The memory is freed.</p><h3>3. Structs — Value Semantics</h3><p>Now consider:</p><pre>struct Person {<br>    var name: String<br>}<br><br>var p1 = Person(name: &quot;Akanksha&quot;)</pre><p>What happens:</p><ul><li>The struct is allocated on the stack.</li><li>No heap allocation occurs.</li><li>No reference count is created.</li><li>No retain or release calls exist.</li></ul><p>Now:</p><pre>var p2 = p1</pre><p>This performs a value copy.</p><p>Graph:</p><pre>STACK<br>--------------------------------<br>p1: Person(name: &quot;Akanksha&quot;)<br><br>p2: Person(name: &quot;Akanksha&quot;)</pre><p>Two independent values exist.</p><p>If:</p><pre>p2.name = &quot;New&quot;</pre><pre>p1: &quot;Akanksha&quot;<br>p2: &quot;New&quot;</pre><p>No shared state exists.</p><p>ARC is not involved.</p><h3>4. Edge Case — Struct Containing a Class</h3><pre>class Address {<br>    var city: String<br>    init(city: String) {<br>        self.city = city<br>    }<br>}<br><br>struct Person {<br>    var name: String<br>    var address: Address<br>}</pre><p>Now:</p><pre>let addr = Address(city: &quot;Delhi&quot;)<br>var p1 = Person(name: &quot;A&quot;, address: addr)<br>var p2 = p1</pre><p>The struct is copied.</p><p>The Address reference is copied.</p><p>No deep copy of Address occurs.</p><p>Graph:</p><pre>STACK<br>-----------------------------------------<br>p1 --------┐<br>           │<br>p2 --------┘<br><br><br><br>Both contain:<br>address ---------------------&gt; [ Address ]<br>                                     city: &quot;Delhi&quot;<br>                                     RC = 1 or 2 depending</pre><p>If:</p><pre>p2.address.city = &quot;Mumbai&quot;</pre><p>Both p1 and p2 observe the updated city value.</p><pre>print(p1.address.city) // Mumbai<br>print(p2.address.city) // Mumbai</pre><p>ARC manages Address.</p><p>It does not manage Person.</p><h3>5. Edge Case — Struct Stored Inside a Class</h3><pre>struct Salary {<br>    var amount: Int<br>}<br><br>class Employee {<br>    var salary: Salary<br>    init(salary: Salary) {<br>        self.salary = salary<br>    }<br>}</pre><p>Memory layout:</p><pre>HEAP<br>---------------------------------<br>[ Employee object ]<br>    salary.amount</pre><p>The struct is stored inline inside the heap memory of the class.</p><p>No separate allocation occurs for Salary.</p><p>No reference counting applies to Salary.</p><p>ARC manages only the Employee object.</p><h3>6. Copy-on-Write — Hybrid Behavior</h3><p>Swift collections such as Array, String, and Dictionary are structs.</p><p>Example:</p><pre>var arr1 = [1, 2, 3]<br>var arr2 = arr1</pre><p>At this point, the underlying storage is shared.</p><p>Graph:</p><pre>STACK<br>--------------------------------<br>arr1 --------┐<br>             │<br>arr2 --------┘<br><br><br>HEAP<br>--------------------------------<br>[ Array Storage ]<br>    elements: [1,2,3]<br>    RC = 2<br></pre><p>When:</p><pre>arr2.append(4)</pre><p>Swift checks whether the storage is uniquely referenced.</p><p>It is not.</p><p>A new copy of the storage is created.</p><p>The mutation occurs on the new storage.</p><p>After mutation:</p><pre>STACK<br>--------------------------------<br>arr1 ------------------&gt; [1,2,3]<br><br>arr2 ------------------&gt; [1,2,3,4]</pre><p>The struct itself remains a value type.</p><p>ARC is used internally for the shared storage.</p><h3>7. Lifetime Differences</h3><p>Class lifetime:</p><ul><li>Controlled by reference count</li><li>Ends when count reaches zero</li><li>Can outlive scope</li><li>Can leak if reference cycles exist</li></ul><p>Struct lifetime:</p><ul><li>Tied to scope</li><li>Destroyed when stack frame ends</li><li>Deterministic</li><li>Cannot leak by itself</li></ul><h3>8. When Structs May Use the Heap</h3><p>Structs may be heap allocated when:</p><ul><li>Captured by escaping closures</li><li>Stored inside a class</li><li>Used in generic contexts</li></ul><p>Even in those cases:</p><p>They are still value types.</p><p>ARC does not track the struct instance itself.</p><h3>9. Identity vs Value</h3><p>Classes represent identity.</p><p>Structs represent value.</p><p>If two variables must refer to the same instance, use a class.</p><p>If two variables should hold independent copies, use a struct.</p><p>ARC exists to manage shared identity.</p><p>When identity is removed, ARC complexity disappears.</p><h3>10. Conceptual Lifecycle View</h3><p>Class lifecycle:</p><pre>allocate heap memory<br>retain<br>retain<br>release<br>release<br>deinit<br>free memory</pre><p>Struct lifecycle:</p><pre>enter scope<br>allocate stack memory<br>copy value when assigned<br>leave scope<br>memory destroyed automatically</pre><h3>11. Structs Do Not Guarantee Stack Allocation</h3><p>A very common misconception is that structs always live on the stack.</p><p>That is not guaranteed.</p><p>Example:</p><pre>struct BigData {<br>    var numbers: [Int]<br>}<br><br>func makeData() -&gt; BigData {<br>    return BigData(numbers: Array(0...1000))<br>}</pre><p>The struct itself is a value type.</p><p>But:</p><ul><li>The array storage is on the heap.</li><li>The struct contains a reference to heap storage.</li><li>ARC manages the array storage.</li></ul><p>Graph:</p><pre>STACK<br>-------------------------<br>BigData<br>   numbers  -----------┐<br>                       │<br>HEAP                   │<br>-----------------------┘<br>[ Array Storage ]<br>    elements: 0...1000<br>    RC = 1</pre><p>The struct is not reference counted.</p><p>The storage it holds may be.</p><p>Important takeaway: Value semantics does not mean “no heap usage”.</p><h3>12. Escaping Structs Can Be Heap Allocated</h3><p>If a struct escapes its defining scope, the compiler may allocate it on the heap.</p><p>Example:</p><pre>struct User {<br>    var name: String<br>}<br><br>func makeClosure() -&gt; () -&gt; User {<br>    var user = User(name: &quot;A&quot;)<br>    return {<br>        return user<br>    }<br>}</pre><p>Here:</p><ul><li>The struct is captured by an escaping closure.</li><li>The compiler may box it on the heap.</li><li>Still no ARC on the struct itself.</li><li>ARC applies to the closure context.</li></ul><p>Graph:</p><pre>HEAP<br>---------------------------------<br>[ Closure Context ]<br>    user: User(name: &quot;A&quot;)<br>    RC = 1</pre><p>Struct behavior remains value-based.</p><p>The container holding it is reference-counted.</p><h3>13. Classes Stored in Structs Across Threads</h3><p>Consider:</p><pre>class Counter {<br>    var value = 0<br>}<br><br>struct Wrapper {<br>    var counter: Counter<br>}</pre><p>Now:</p><pre>let counter = Counter()<br>var w1 = Wrapper(counter: counter)<br>var w2 = w1</pre><p>Both wrappers reference the same Counter.</p><p>If used across threads:</p><pre>DispatchQueue.global().async {<br>    w1.counter.value += 1<br>}<br><br>DispatchQueue.global().async {<br>    w2.counter.value += 1<br>}</pre><p>You have a race condition.</p><p>Even though Wrapper is a struct, it contains shared mutable state.</p><p>Graph:</p><pre>w1 ----------┐<br>             │<br>w2 ----------┘----------&gt; [ Counter ]<br>                                 value: ?</pre><p>Struct does not guarantee thread safety if it contains references.</p><h3>14. Mutating Methods in Structs vs Classes</h3><p>Struct mutation requires exclusive access.</p><p>Example:</p><pre>struct Counter {<br>    var value = 0<br>    <br>    mutating func increment() {<br>        value += 1<br>    }<br>}</pre><p>The compiler enforces exclusive access at runtime.</p><p>Two simultaneous mutations cause a crash.</p><p>Classes do not enforce this automatically.</p><p>Example:</p><pre>class Counter {<br>    var value = 0<br>    <br>    func increment() {<br>        value += 1<br>    }<br>}</pre><p>No exclusivity checking.</p><p>You must manually synchronize.</p><p>This is a major safety difference.</p><h3>15. Self Inside Struct vs Class</h3><p>In classes:</p><ul><li>self is a reference.</li><li>Mutating properties modifies shared instance.</li></ul><p>In structs:</p><ul><li>self is a value.</li><li>Reassignment replaces entire value.</li></ul><p>Example:</p><pre>struct Point {<br>    var x: Int<br>    var y: Int<br>    <br>    mutating func move() {<br>        self = Point(x: x + 1, y: y + 1)<br>    }<br>}</pre><p>This replaces the entire struct value.</p><p>No ARC involvement.</p><h3>16. Weak and Unowned Are Not Allowed in Structs</h3><p>You cannot write:</p><pre>struct Test {<br>    weak var obj: SomeClass?<br>}</pre><p>Because:</p><ul><li>weak requires reference counting</li><li>struct itself is not reference counted</li></ul><p>Weak and unowned only apply to classes.</p><p>This reinforces that ARC is fundamentally a class mechanism.</p><h3>17. Identity Comparison</h3><p>Classes have identity.</p><pre>let p1 = Person(name: &quot;A&quot;)<br>let p2 = p1<br><br>print(p1 === p2)</pre><p>This checks memory identity.</p><p>Structs do not support identity comparison.</p><p>They support value equality only.</p><p>This is because:</p><p>Structs do not have shared identity.</p><h3>18. Inheritance and ARC</h3><p>Only classes support inheritance.</p><p>With inheritance:</p><ul><li>Retain/release happens per instance.</li><li>vtable dispatch is used.</li><li>Deinitializers chain upward.</li></ul><p>Structs:</p><ul><li>No inheritance</li><li>No dynamic dispatch</li><li>No polymorphic lifetime management</li></ul><p>This reduces ARC complexity significantly.</p><h3>19. Generic Code and ARC</h3><p>When using generics:</p><pre>func process&lt;T&gt;(_ value: T) {<br>    print(value)<br>}</pre><p>If T is:</p><ul><li>a struct → no ARC</li><li>a class → retain/release may be inserted</li></ul><p>The compiler specializes generics differently depending on type constraints.</p><p>ARC cost can exist in generic code even if not obvious.</p><h3>20. Bridging with Objective-C</h3><p>Classes that inherit from NSObject:</p><ul><li>Use ARC</li><li>May interact with Objective-C runtime</li><li>Have different retain semantics in some bridging cases</li></ul><p>Structs:</p><ul><li>Do not bridge directly</li><li>Are copied when passed to Objective-C APIs</li></ul><p>This can create hidden performance costs.</p><h3>21. Memory Layout Differences</h3><p>Class memory layout:</p><pre>HEAP<br>---------------------------------<br>[ metadata pointer ]<br>[ reference count ]<br>[ stored properties ]</pre><p>Struct memory layout:</p><pre>STACK or inline<br>---------------------------------<br>[ stored properties directly ]</pre><p>Classes carry runtime overhead.</p><p>Structs do not carry metadata pointers per instance.</p><h3>22. Large Struct Performance Pitfall</h3><p>If a struct is very large:</p><pre>struct HugeData {<br>    var a: [Int]<br>    var b: [Int]<br>    var c: [Int]<br>}</pre><p>Copying this struct copies three references.</p><p>If those arrays are uniquely referenced, no deep copy occurs.</p><p>If mutated, deep copy may occur.</p><p>Large structs can still be efficient due to Copy-on-Write.</p><p>But blindly copying large value types can be expensive if they contain non-COW data.</p><h3>23. When a Class Is the Correct Choice</h3><p>Use class when:</p><ul><li>Identity matters</li><li>Shared mutable state is required</li><li>Deinitialization logic is important</li><li>Polymorphism is required</li><li>You need weak references</li></ul><p>Use struct when:</p><ul><li>Modeling data</li><li>Predictable lifetimes are desired</li><li>Avoiding retain cycles</li><li>Encouraging immutability</li><li>Reducing ARC overhead</li></ul><h3>24. Conceptual Summary Graph</h3><p>Class behavior:</p><pre>multiple owners<br>retain<br>release<br>dynamic lifetime<br>possible retain cycle<br>deinit at RC = 0</pre><p>Struct behavior:</p><pre>copied on assignment<br>no shared identity<br>scope-based lifetime<br>no retain cycle possible<br>deterministic destruction</pre><h3>25. Most Overlooked Insight</h3><p>ARC exists because identity can be shared.</p><p>Structs eliminate shared identity.</p><p>That is why:</p><ul><li>They eliminate entire categories of memory bugs.</li><li>They reduce runtime overhead.</li><li>They are preferred in SwiftUI and modern Swift architecture.</li></ul><p>Previous →<br>Understanding Swift Classes</p><p><a href="https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e">https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e</a></p><p>Next →<br>Understanding ARC in Swift: Strong, Weak, and Unowned Explained Deeply<br><a href="https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9">https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c37064690b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Swift Struct Array Isn’t Mutating: A Deep Dive into Value Semantics, forEach, map, and…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Swift Memory &amp; Value Semantics Deep Dive Series</p><p class="medium-feed-link"><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8?source=rss-12293b6c4473------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/f35a764823d8</guid>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 07:26:47 GMT</pubDate>
            <atom:updated>2026-03-06T08:40:38.143Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding ARC in Swift: Strong, Weak, and Unowned Explained Deeply]]></title>
            <link>https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9?source=rss-12293b6c4473------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bd970f15bd9</guid>
            <dc:creator><![CDATA[Akanksha Singh]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 10:47:27 GMT</pubDate>
            <atom:updated>2026-03-06T08:39:32.497Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swift Memory &amp; Value Semantics Deep Dive Series</strong></p><p>This article is part of a series exploring how Swift handles value types, reference types, and memory management.</p><p>Start with the foundation or continue the series:</p><ol><li>Classes vs Structs in Swift (Interview Guide)<br><a href="https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021">https://medium.com/@aksingh20feb/ios-difference-between-classes-vs-structs-for-interview-e9557feff021</a></li><li>Understanding Swift Classes: Properties, Initializers, Memory Management &amp; ARC<br><a href="https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e">https://medium.com/@aksingh20feb/understanding-swift-classes-properties-initializers-memory-management-and-arc-308ecb27f91e</a></li><li>ARC in Classes vs Structs in Swift — Deep Dive with Runtime Behavior &amp; Edge Cases<br><a href="https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2">https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2</a></li><li>Understanding ARC in Swift: Strong, Weak, and Unowned Explained Deeply<br><a href="https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9">https://medium.com/@aksingh20feb/understanding-arc-in-swift-strong-weak-and-unowned-explained-deeply-6bd970f15bd9</a></li><li>Why Your Swift Struct Array Isn’t Mutating<br><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8">https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8</a></li></ol><p>If you’re working with Swift — especially at a senior level — you cannot treat <strong>ARC (Automatic Reference Counting)</strong> as a “basic concept.”<br> It directly affects memory safety, app performance, leaks, and even architecture decisions.</p><p>This article focuses only on:</p><ul><li>Strong references</li><li>Weak references</li><li>Unowned references</li></ul><p>With deep explanation, runtime behavior, memory graphs, and practical examples.</p><h3>What is ARC Really?</h3><p>ARC is a <strong>compile-time memory management system</strong> that inserts <em>retain</em> and <em>release</em> calls into your code.</p><p>It works only for <strong>class instances</strong> (reference types).<br>Structs and enums are value types and live on the stack (in most cases).</p><p>When a class instance is created:</p><ul><li>Memory is allocated on the <strong>heap</strong></li><li>Reference count is set to <strong>1</strong></li><li>Every strong reference increments the count</li><li>When reference count reaches <strong>0</strong>, <em>denit</em> is called</li></ul><p>ARC is deterministic.<br>It is NOT a garbage collector.<br>It does NOT detect cycles automatically.</p><h3>1. Strong References</h3><p>A strong reference is the default behavior in Swift.</p><pre>class Person {<br>    let name: String<br>    init(name: String) {<br>        self.name = name<br>        print(&quot;\(name) initialized&quot;)<br>    }<br>    deinit {<br>        print(&quot;\(name) deallocated&quot;)<br>    }<br>}</pre><p>This does <strong>NOT</strong> create an object.</p><p>It only:</p><ul><li>Defines a type</li><li>Registers type metadata</li><li>Sets up runtime information</li><li>Prepares method table (vtable)</li><li>Prepares layout description</li></ul><p>No heap allocation at the time of Person class.</p><p>Think of it as a blueprint.</p><p>At runtime, Swift runtime now knows:</p><pre>Type: Person<br>Size: X bytes<br>Methods: ...<br>Metadata pointer: ...</pre><p>But when we create a instance of Person Class then:</p><pre>var p1: Person? = Person(name: &quot;Akanksha&quot;)</pre><h4><strong>What Happens Internally</strong></h4><ul><li>Heap allocation occurs (Person() allocates memory on heap)</li><li>Reference count = 1</li><li><em>p1</em> strongly owns the object</li></ul><p>This triggers:</p><pre>swift_allocObject(...)</pre><p>Heap memory allocated.</p><p>Layout in heap:</p><pre>Heap:<br>-----------------------<br>| metadata pointer     |<br>| refCount             |<br>| stored properties    |<br>-----------------------</pre><pre>Heap:<br>[ Person instance | refCount = 1 ]<br><br>Stack:<br>p1 → heap object</pre><p>Now:</p><pre>var p2 = p1</pre><p>This copies the <strong>reference</strong>, not the object</p><p>ARC inserts:</p><pre>retain(person)</pre><p>Reference count = 2</p><pre>Heap:<br>[ Person | refCount = 2 ]<br><br>Stack:<br>p1 → object<br>p2 → same object</pre><p>If:</p><pre>p1 = nil</pre><p>ARC inserts:</p><pre>release(person)</pre><p>Reference count = 1</p><p>Object still alive (because p2 holds it).</p><p>If:</p><pre>p2 = nil</pre><pre><br>release(person)</pre><p>Reference count = 0</p><ul><li>Object deallocates.</li><li>Memory freed immediately</li></ul><p>This is why ARC is <strong>deterministic</strong>.</p><p>Unlike Garbage Collection:</p><ul><li>Memory is freed immediately when refCount hits 0.</li><li>No background cleanup cycle.</li></ul><h4>Strong Reference Cycle (Memory Leak)</h4><p>Problem appears when two objects strongly reference each other.</p><pre>class Person {<br>    var apartment: Apartment?<br>}<br><br>class Apartment {<br>    var tenant: Person?<br>}</pre><p>Usage:</p><pre>var john: Person? = Person()<br>var flat: Apartment? = Apartment()<br><br>john?.apartment = flat<br>flat?.tenant = john<br>john = nil<br>flat = nil</pre><p>Neither object deallocates.</p><h4><strong>Why?</strong></h4><p>Because:</p><pre>Person ───strong──▶ Apartment<br>   ▲                  │<br>   └─────strong───────┘</pre><p>Even after setting external references to nil:</p><ul><li>Person still has 1 reference (from Apartment)</li><li>Apartment still has 1 reference (from Person)</li></ul><p>Reference count never reaches zero.</p><p>This is called a <strong>retain cycle</strong>.</p><p>ARC cannot break it automatically.</p><h3>2. Weak References</h3><p>A weak reference does NOT increase the reference count.</p><p>It does NOT express ownership.</p><p>It means:</p><blockquote><em>“I refer to you, but I do not own you.”</em></blockquote><h4><strong>Fixing the Previous Example</strong></h4><pre>class Apartment {<br>    weak var tenant: Person?<br>}</pre><p>Now the graph becomes:</p><pre>Person ───strong──▶ Apartment<br>   ▲<br>   └──── weak ─────</pre><p>What happens when:</p><pre>john = nil</pre><ul><li>Reference count of Person = 0</li><li>Person deallocates</li><li>Weak reference in Apartment automatically becomes nil</li></ul><p>This is called <strong>zeroing weak reference</strong>.</p><h4><strong>Why Weak Must Be Optional</strong></h4><p>Because when the referenced object deallocates:</p><ul><li>Swift sets weak reference to <em>nil</em></li><li>That means it must be <em>optional</em></li></ul><pre>weak var delegate: MyDelegate?</pre><h4>How Weak References Are Implemented Internally</h4><blockquote>This explains why weak has overhead and must be optional.</blockquote><p>In Swift, weak references are not stored the same way as strong or unowned references.</p><p>When you declare:</p><pre>weak var delegate: MyDelegate?</pre><p>the compiler and runtime:</p><ul><li>Create a <strong>side table</strong> entry for the object</li><li>Store the weak reference pointing to that side table, <strong>not directly to the object</strong></li></ul><p>Conceptually:</p><pre>weakPointer → SideTable → ActualObject</pre><p>This extra indirection exists because Swift must keep track of <strong>all weak references</strong> to an object so it can set them to nil when that object deallocates.<br> This capability (called <strong>zeroing weak references</strong>) is what makes weak safe.</p><p>In contrast:</p><ul><li><strong>Strong &amp; unowned references</strong> point directly to the object</li><li>They don’t require side-table registration unless a weak reference <em>ever</em> exists</li></ul><p>This explains why weak has <em>extra runtime overhead and atomic updates</em>, whereas unowned does not.</p><h4>Weak in Delegate Pattern</h4><p>Classic example:</p><pre>protocol ChildDelegate: AnyObject {<br>}<br><br>class Parent: ChildDelegate {<br>    var child: Child?<br>}<br>class Child {<br>    weak var delegate: ChildDelegate?<br>}</pre><p>Graph:</p><pre>Parent ──strong──▶ Child<br>Child ──weak────▶ Parent</pre><p>Why weak?</p><p>Because parent already owns child.<br>If child strongly owned parent, you’d create a cycle.</p><h4>Weak in Closures</h4><p>Closures capture strongly by default.</p><pre>class ViewModel {<br>    func fetch() {<br>        networkCall {<br>            self.handle()<br>        }<br>    }<br>}</pre><p>If <em>networkCall</em> retains the closure strongly:</p><pre>ViewModel ───strong──▶ Closure<br>     ▲                     │<br>     └────────strong───────┘</pre><p>Cycle.</p><p>Fix:</p><pre>networkCall { [weak self] in<br>    self?.handle()<br>}</pre><p>Now:</p><ul><li>Closure does not increase reference count of self</li><li>If ViewModel deallocates, closure does not keep it alive</li></ul><h3>3. Unowned References</h3><p>Unowned also does NOT increase reference count.</p><p>But unlike weak:</p><ul><li>It is non-optional</li><li>It is NOT automatically <em>nilled</em></li><li>Accessing after deallocation → crash</li></ul><h4>Example: Credit Card &amp; Customer</h4><pre>class Customer {<br>    var card: CreditCard?<br>}<br><br>class CreditCard {<br>    unowned let customer: Customer<br>    <br>    init(customer: Customer) {<br>        self.customer = customer<br>    }<br>}</pre><p>Graph:</p><pre>Customer ──strong──▶ CreditCard<br>     ▲<br>     └──unowned────</pre><p>Why unowned?</p><p>Because:</p><ul><li>CreditCard cannot exist without Customer</li><li>Card lifetime ≤ Customer lifetime</li></ul><p>There is a <strong>lifetime guarantee</strong>.</p><h4>What Happens If You Violate It</h4><pre>unowned var person: Person</pre><p>If person deallocates and you access:</p><pre>person.name</pre><p>App crashes:</p><pre>EXC_BAD_ACCESS</pre><p>Because unowned does NOT become nil.</p><h3>4. Weak vs Unowned Conceptually</h3><p>Weak means:</p><blockquote><em>“This reference might become nil at runtime.”</em></blockquote><p>Unowned means:</p><blockquote><em>“This reference will always be valid while I exist.”</em></blockquote><p>Weak is safe.<br> Unowned is performance-oriented and assumes correctness.</p><h4>Unowned in Closures</h4><p>Example:</p><pre>class Controller {<br>    lazy var button: UIButton = {<br>        [unowned self] in<br>        return UIButton()<br>    }()<br>}</pre><p>Why safe?</p><p>Because:</p><ul><li>Button is owned by Controller</li><li>Closure runs only during initialization</li><li>Controller will outlive closure</li></ul><h3>5. Why Is unowned Faster Than weak?</h3><p>It comes down to <strong>runtime bookkeeping</strong>.</p><h4>How Weak Works Internally</h4><p>When you declare:</p><pre>weak var delegate: MyDelegate?</pre><p>Swift must:</p><ol><li>Register this reference in a <strong>weak reference table</strong></li><li>Track it separately from strong references</li><li>When the object deallocates:</li></ol><ul><li>Traverse weak reference list</li><li>Set all weak references to <em>nil</em></li></ul><p>This is called <strong>zeroing weak reference</strong>.</p><p>So weak requires:</p><ul><li>Extra memory metadata</li><li>Side table tracking</li><li>Runtime cleanup work</li><li>Atomic operations (thread safety)</li></ul><p>Accessing a weak reference also involves:</p><ul><li>Indirection through runtime</li><li>Checking whether object still exists</li></ul><p>So weak is slightly heavier.</p><h4>How Unowned Works Internally</h4><p>When you declare:</p><pre>unowned var owner: OwnerSwift does NOT:</pre><ul><li>Add it to weak reference table</li><li>Track it for zeroing</li><li>Perform cleanup on deallocation</li></ul><p>It is just a raw non-retained pointer with a safety check.</p><p>When accessed:</p><ul><li>Swift performs a quick runtime check</li><li>If object exists → use it</li><li>If not → crash</li></ul><p>No zeroing.<br>No side table.<br>No cleanup traversal.</p><p>So unowned is faster because:</p><ul><li>No weak table registration</li><li>No nil assignment on deallocation</li><li>No atomic zeroing</li><li>Less runtime bookkeeping</li></ul><h4>Does This Performance Matter?</h4><p>Most of times: No.</p><p>The difference is micro-level.</p><p>It only matters if:</p><ul><li>You have thousands of references</li><li>High-frequency access</li><li>Performance-critical code paths</li></ul><p>Example: Core data structures or tight loops.</p><p>Otherwise, safety &gt; micro-optimization.</p><h3>6. Deeper Concept: Ownership vs Lifetime Contract</h3><p>Strong = Ownership<br>Weak = Optional non-ownership<br>Unowned = Guaranteed non-ownership</p><p>The real difference is not syntax.</p><p>It is <strong>lifetime contract design</strong>.</p><h3>7. How ARC Inserts Code</h3><p>For strong references, Swift inserts:</p><ul><li><em>strong_retain</em></li><li><em>string_release</em></li></ul><p>For weak:</p><ul><li><em>weak_init</em></li><li><em>weak_destroy</em></li></ul><p>Unowned:</p><ul><li>No retain</li><li>Runtime safety check when accessed</li></ul><p>ARC operates at compile time via SIL (Swift Intermediate Language).</p><h3>8. Additional Senior-Level Points</h3><h4>1. Deterministic Destruction</h4><p>ARC deallocates immediately when reference count hits zero.</p><p>Unlike garbage collection:</p><ul><li>No background sweep</li><li>No unpredictable cleanup</li></ul><p>This is why retain cycles are dangerous — ARC will never clean them.</p><h4>2. ARC Is Compile-Time Inserted</h4><p>Swift inserts:</p><pre>strong_retain<br>strong_release</pre><p>Weak uses:</p><pre>weak_init<br>weak_destroy</pre><p>Unowned:</p><ul><li>No retain</li><li>Minimal metadata</li><li>Runtime access check</li></ul><h4>3. Thread Safety Considerations</h4><p>Weak references involve atomic operations for zeroing.</p><p>Unowned does not require that level of tracking.</p><p>That’s another reason for slight performance difference.</p><h4>4. Why Weak Must Be Optional But Unowned Is Not</h4><p>Weak:</p><p>Swift uses the optional type system to <strong>prevent runtime crashes</strong></p><p>By making weak always an Optional, Swift ensures that any usage forces unwrapping or safe binding (<em>if let, guard let</em>), which acknowledges that the object <em>might not exist anymore</em></p><ul><li>Object may disappear</li><li>Must become nil</li><li>Therefore optional</li></ul><p>Unowned:</p><p>because it does not nil out and will crash if invalid, is allowed to be non-optional because it’s the developer’s guarantee that the referenced object <em>will always exist while this reference exists.</em></p><p>This links the type system (Optional) directly to memory safety — a key Swift design principle.</p><ul><li>Assumes object will never disappear first</li><li>No need to be optional</li><li>Crash is expected if violated</li></ul><h4>5. What Happens at the Object Level with Weak/Unowned</h4><p>Beyond reference counts, Swift actually tracks three different counts internally:</p><ul><li><strong>Strong count</strong></li><li><strong>Weak count</strong></li><li><strong>Unowned count</strong></li></ul><p>So the full deallocation process is a bit more nuanced:</p><ol><li>When the <strong>strong count reaches 0</strong>, the object’s <em>deinit</em> runs.</li><li>If there are unowned references still pointing to it, the object’s memory remains allocated until the unowned count also reaches zero.</li><li>If weak references exist, a side table persists to handle zeroing while the object is alive.</li></ol><p>This lifecycle nuance is important because unowned references can keep the memory alive <em>just long enough</em> to avoid dangling pointers, even though they don’t participate in ARC ownership.</p><h4>6. Why Weak Is Slower Than Unowned (More Than You Think)</h4><p>Because weak pointers go through a side table, <strong>every access involves:</strong></p><ul><li>An extra pointer dereference</li><li>A check against the side table</li><li>Atomic memory operations for thread safety</li></ul><p>Meanwhile</p><ul><li>Unowned references <em>point directly</em> to the object</li><li>Therefore no side-table indirection and fewer atomic operations</li></ul><p>This is more than micro-optimization — in very performance-sensitive code (e.g., hot loops or low-level systems code) this indirection can matter.</p><h4>7. Risk Philosophy: Safety vs Strict Guarantees</h4><ul><li><strong>Weak references</strong> favor <em>safety</em> — they avoid crashes by becoming nil</li><li><strong>Unowned references</strong> favor <em>correctness enforcement</em> — they crash early when the lifetime assumption is violated</li></ul><p>This means:</p><blockquote><em>Using unowned is a way of </em>documenting a guarantee in code<em> rather than a way to optimize performance.</em></blockquote><p>It communicates intent:</p><blockquote>“I am sure this object will outlive me.”</blockquote><p>Weak communicates:</p><blockquote>“This object might go away, and that’s okay.”</blockquote><p>This mindset is high-value for senior engineers.</p><h4>8. Historical Context: Before ARC, There Was No Weak Safety</h4><p>Before ARC, Swift/Objective-C developers used “assign” references (similar to unowned) that could <em>immediately</em> lead to dangling pointers and crashes when the object was freed.</p><p>Weak references were introduced to solve this:</p><ul><li>To avoid retain cycles</li><li>While maintaining safety (no dangling pointers)</li><li>With zeroing semantics</li></ul><p>Unowned is in a sense “bringing back” that older pattern, <em>intentionally</em> and with explicit guarantees.</p><h3>9. When To Choose What (Architect Thinking)</h3><p>Use Strong when:</p><ul><li>You own the object</li><li>You control its lifetime</li></ul><p>Use Weak when:</p><ul><li>Lifetime is uncertain</li><li>Object may deallocate independently</li><li>Delegate patterns</li><li>Closures with async operations</li></ul><p>Use Unowned when:</p><ul><li>Lifetimes are tightly coupled</li><li>Child cannot exist without parent</li><li>You want non-optional access</li><li>You’re 100% sure about lifecycle</li></ul><h3>10. Final Mental Model</h3><p>Now let’s refine your summary with deeper understanding.</p><h4>Strong Reference</h4><p><strong>What It Means</strong></p><ul><li>Expresses <strong>ownership</strong></li><li>Increases reference count</li><li>Keeps object alive</li></ul><p><strong>Runtime Behavior</strong></p><ul><li>ARC inserts <em>retain</em></li><li>ARC inserts <em>release</em></li><li>Deterministic destruction</li></ul><p><strong>Risk</strong></p><ul><li>Retain cycles</li><li>Memory leaks</li></ul><h4>Weak Reference</h4><p><strong>What It Means</strong></p><ul><li>Non-owning relationship</li><li>Object may disappear anytime</li><li>Automatically becomes nil</li></ul><p><strong>Runtime Behavior</strong></p><ul><li>Stored in weak reference side table</li><li>Zeroed automatically on deallocation</li><li>Optional by design</li></ul><p><strong>Overhead</strong></p><ul><li>Side table tracking</li><li>Atomic zeroing</li><li>Slightly slower access</li></ul><h4>Unowned Reference</h4><p><strong>What It Means</strong></p><ul><li>Non-owning</li><li>Assumes lifetime guarantee</li><li>Never nil</li></ul><p><strong>Runtime Behavior</strong></p><ul><li>Not tracked in weak table</li><li>Not zeroed</li><li>Fast access</li><li>Crash if accessed after deallocation</li></ul><p><strong>Performance</strong></p><ul><li>Slightly faster than weak</li><li>Less runtime bookkeeping</li></ul><h3>Closing Thought</h3><p>ARC is not just a memory management feature.</p><p>It is a tool for modeling ownership.</p><p>Strong, weak, and unowned are not keywords you memorize — <br> they are decisions you make about <strong>lifetime guarantees</strong> and <strong>responsibility</strong>.</p><p>When ownership is modeled correctly:</p><ul><li>Objects deallocate deterministically</li><li>Retain cycles disappear</li><li>Asynchronous code behaves predictably</li><li>Architectural boundaries remain clean</li><li>The memory graph reflects your design intent</li></ul><p>When ownership is modeled incorrectly, ARC doesn’t fail — <br> your architecture does.</p><p>At a senior or tech lead level, understanding ARC isn’t about avoiding leaks.<br>It’s about designing systems where lifetime relationships are intentional, explicit, and safe.</p><p>That level of clarity is not optional — it’s expected.</p><p>Previous →<br>ARC in Classes vs Structs in Swift — Deep Dive with Runtime Behavior &amp; Edge Cases<br><a href="https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2">https://medium.com/@aksingh20feb/arc-in-classes-vs-structs-in-swift-deep-dive-with-runtime-behavior-edge-cases-4c37064690b2</a></p><p>Next →<br>Why Your Swift Struct Array Isn’t Mutating<br><a href="https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8">https://medium.com/@aksingh20feb/why-your-swift-struct-array-isnt-mutating-a-deep-dive-into-value-semantics-foreach-map-and-f35a764823d8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bd970f15bd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>