<?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 Botirjon Nasridinov on Medium]]></title>
        <description><![CDATA[Stories by Botirjon Nasridinov on Medium]]></description>
        <link>https://medium.com/@botirjon.nasridinov?source=rss-a59d3d152776------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0c06ECYUHJ4s3in7</url>
            <title>Stories by Botirjon Nasridinov on Medium</title>
            <link>https://medium.com/@botirjon.nasridinov?source=rss-a59d3d152776------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:29:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@botirjon.nasridinov/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[Understanding Message Dispatch: The Objective-C Runtime Explained]]></title>
            <link>https://medium.com/@botirjon.nasridinov/understanding-message-dispatch-the-objective-c-runtime-explained-4dc475b7e374?source=rss-a59d3d152776------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dc475b7e374</guid>
            <dc:creator><![CDATA[Botirjon Nasridinov]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 13:22:50 GMT</pubDate>
            <atom:updated>2025-12-14T13:22:50.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLhNlwSvwocATAPIUedEew.png" /></figure><h3>Part 2 of the Method Dispatch Series</h3><p>In <a href="https://medium.com/@botirjon.nasridinov/understanding-static-and-dynamic-dispatch-a-deep-dive-for-swift-developers-9fd9a3124a1b?source=your_stories_outbox---writer_outbox_published-----------------------------------------">Part 1</a>, we explored static dispatch and vtable dispatch. We saw how the compiler resolves method calls either at compile time (static) or through a lookup table at runtime (vtable).</p><p>But there’s a third mechanism that powers much of iOS development: <strong>message dispatch</strong>. This is the Objective-C runtime at work, and even as Swift developers, we use it every day — often without realizing it.</p><p>When I first tried to understand message dispatch, I kept hitting walls. What <em>is</em> a “runtime” anyway? Why is it different from vtable dispatch if both happen at runtime? It took me a while to untangle these concepts, so let me share what finally made it click.</p><h3>First: What Even Is a “Runtime”?</h3><p>This confused me for a long time. Let’s clear it up.</p><p>Term When It Runs What It Does <strong>Compiler</strong> Before your app runs (on your Mac) Transforms source code → binary <strong>Runtime</strong> While your app runs (on user’s device) A library that handles dynamic features</p><p>A <strong>runtime</strong> is just code — a library that ships with your app and handles things that can’t be decided at compile time.</p><pre>Your Swift Code<br>      ↓<br>  [Compiler]          ← Runs during build<br>      ↓<br>  Your App Binary<br>      +<br>  Runtime Library     ← Ships inside your app<br>      ↓<br>  [Runs on iPhone]</pre><p>The <strong>Objective-C runtime</strong> is a C library called libobjc. It&#39;s the engine that powers Objective-C&#39;s dynamic features. Think of it as the &quot;operating system&quot; for dynamic method calls.</p><h3>The Key Difference: Function Calls vs Messages</h3><p>This analogy helped me finally understand the distinction:</p><p><strong>Static/vtable dispatch</strong> is like knowing your friend’s exact GPS coordinates. You drive straight there. Fast, direct, no surprises.</p><p><strong>Message dispatch</strong> is like sending a letter. You write the recipient’s name on the envelope and drop it in the mailbox. You don’t know exactly where they are or how they’ll handle it. The postal system (the runtime) figures out the delivery.</p><p>In code terms:</p><pre>// vtable dispatch: &quot;Call the function at index 3&quot;<br>vtable[3]()</pre><pre>// Message dispatch: &quot;Hey object, do you respond to &#39;speak&#39;? If so, run it.&quot;<br>objc_msgSend(object, &quot;speak&quot;)</pre><p>This might seem like a subtle distinction, but it changes everything.</p><h3>The Heart of It: objc_msgSend</h3><p>Every Objective-C method call gets transformed by the compiler into a call to objc_msgSend:</p><pre>// What you write:<br>[dog speak];</pre><pre>// What the compiler generates:<br>objc_msgSend(dog, @selector(speak));</pre><p>In Swift, when calling an @objc method:</p><pre>// What you write:<br>dog.speak()</pre><pre>// Under the hood (if @objc):<br>objc_msgSend(dog, @selector(speak))</pre><p>The function signature looks like this:</p><pre>id objc_msgSend(id self, SEL selector, ...)</pre><ul><li><strong>self</strong>: The object receiving the message (“dog”)</li><li><strong>selector</strong>: The method name as a unique identifier (“speak”)</li><li><strong>…</strong>: Any arguments the method takes</li></ul><p>So the runtime is literally asking: <em>“Find the method named ‘speak’ for this object and call it.”</em></p><h3>The isa Pointer: &quot;I Am A...&quot;</h3><p>Every Objective-C object has a hidden pointer as its very first property: <strong>isa</strong>.</p><p>Yes, it’s short for <strong>“is a”</strong> — as in “this object <em>is a</em> Dog.”</p><pre>┌─────────────────────┐<br>│    Dog Instance     │<br>├─────────────────────┤<br>│ isa ────────────────┼───→ Dog Class (&quot;I am a Dog&quot;)<br>│ name: &quot;Buddy&quot;       │<br>│ age: 3              │<br>└─────────────────────┘</pre><p>When you call type(of: dog) in Swift or [dog class] in Objective-C, it follows that isa pointer.</p><p>This is similar to the vptr we discussed in Part 1, but instead of pointing to a vtable, it points to a <strong>Class object</strong>.</p><h3>The Class Object: Where Methods Live</h3><p>Here’s where it gets interesting. In Objective-C, classes themselves are objects in memory:</p><pre>┌──────────────────────────────────────────┐<br>│           Dog Class Object               │<br>├──────────────────────────────────────────┤<br>│ isa ─────────────────────────────────────┼──→ Dog Meta Class<br>│ superclass ──────────────────────────────┼──→ Animal Class Object  <br>│ cache ───────────────────────────────────┼──→ Recently called methods<br>│ methodList ──────────────────────────────┼──→ Methods defined in Dog<br>│   • &quot;speak&quot; → 0x2000                     │<br>│   • &quot;fetch&quot; → 0x2100                     │<br>│   • &quot;bark&quot;  → 0x2200                     │<br>└──────────────────────────────────────────┘</pre><p>Notice the differences from a vtable:</p><p>vtable Class Object Methods stored by <strong>index</strong> Methods stored by <strong>name</strong> No inheritance info Has <strong>superclass</strong> pointer No caching Has <strong>cache</strong> for performance</p><h3>The Lookup Process: Step by Step</h3><p>When objc_msgSend(dog, @selector(speak)) runs:</p><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                    MESSAGE DISPATCH FLOW                        │<br>└─────────────────────────────────────────────────────────────────┘</pre><pre>Step 1: Nil Check<br>        Is dog == nil?<br>        → Yes: Return zero, do nothing (no crash!)<br>        → No: Continue</pre><pre>Step 2: Find the Class<br>        Follow dog&#39;s isa pointer → Dog Class</pre><pre>Step 3: Cache Lookup (Fast Path)<br>        Is &quot;speak&quot; in Dog&#39;s method cache?<br>        → Yes: Jump to cached address ✓ Done!<br>        → No: Continue</pre><pre>Step 4: Method List Search<br>        Search Dog&#39;s methodList for &quot;speak&quot;<br>        → Found: Cache it, jump to address ✓ Done!<br>        → Not found: Continue</pre><pre>Step 5: Walk Inheritance Chain<br>        Follow superclass → Animal Class<br>        Search Animal&#39;s methodList for &quot;speak&quot;<br>        → Found: Cache it, jump to address ✓ Done!<br>        → Not found: Continue up to NSObject</pre><pre>Step 6: Method Not Found Anywhere?<br>        → Enter Message Forwarding...</pre><h3>Message Forwarding: The Safety Net</h3><p>Here’s something vtable dispatch can’t do. If a method isn’t found anywhere in the inheritance chain, Objective-C doesn’t immediately crash. It gives you multiple chances to handle it:</p><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                    MESSAGE FORWARDING                           │<br>├─────────────────────────────────────────────────────────────────┤<br>│                                                                 │<br>│  1. +resolveInstanceMethod:                                     │<br>│     &quot;Want to add this method dynamically right now?&quot;            │<br>│     → You can inject a method implementation at runtime         │<br>│                                                                 │<br>│  2. -forwardingTargetForSelector:                               │<br>│     &quot;Want to redirect this to another object?&quot;                  │<br>│     → Return a different object that can handle it              │<br>│                                                                 │<br>│  3. -forwardInvocation:                                         │<br>│     &quot;Here&#39;s the full invocation, do whatever you want&quot;          │<br>│     → Complete control over how to handle it                    │<br>│                                                                 │<br>│  4. All else fails                                              │<br>│     💥 &quot;unrecognized selector sent to instance&quot;                 │<br>│                                                                 │<br>└─────────────────────────────────────────────────────────────────┘</pre><p>This is incredibly powerful. You can add methods at runtime, redirect messages to other objects, or intercept any method call.</p><h3>The Cache: Why It’s Not As Slow As It Sounds</h3><p>You might think: “Searching by name every time? That must be slow!”</p><p>The cache makes it fast. After a method is called once, it’s stored in a hash table:</p><pre>┌───────────────────────────────┐<br>│       Method Cache            │<br>├───────────────────────────────┤<br>│ hash(&quot;speak&quot;) → 0x2000        │  ← O(1) lookup<br>│ hash(&quot;fetch&quot;) → 0x2100        │<br>└───────────────────────────────┘</pre><p>In practice, most calls hit the cache, making message dispatch only about 2–4x slower than vtable dispatch — not the 20x you might expect.</p><h3>Why Does Any of This Matter for Swift?</h3><p>Here’s the key insight: <strong>Swift is a hybrid language</strong>.</p><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                     SWIFT DISPATCH                              │<br>├─────────────────────────────────────────────────────────────────┤<br>│                                                                 │<br>│   Pure Swift (uses Swift runtime)                               │<br>│   ├── struct, enum ──────────────→ Static dispatch              │<br>│   ├── final class ───────────────→ Static dispatch              │<br>│   ├── class methods ─────────────→ Swift vtable                 │<br>│   └── protocol existentials ─────→ Witness table                │<br>│                                                                 │<br>│   Objective-C Interop (uses Objective-C runtime)                │<br>│   ├── @objc methods ─────────────→ Message dispatch             │<br>│   ├── dynamic methods ───────────→ Message dispatch             │<br>│   └── UIKit/Foundation calls ────→ Message dispatch             │<br>│                                                                 │<br>└─────────────────────────────────────────────────────────────────┘</pre><p>Almost all of Apple’s frameworks — UIKit, AppKit, Foundation, Core Data — are written in Objective-C. When your Swift code interacts with them, the Objective-C runtime is involved.</p><h3>The Two Keywords: @objc vs dynamic</h3><p><strong>@objc</strong>: Makes your Swift method visible to the Objective-C runtime. Required for selectors, IBActions, and Objective-C interop.</p><pre>class MyViewController: UIViewController {<br>    @objc func buttonTapped() { }  // Visible to Obj-C<br>}</pre><p>But @objc alone doesn&#39;t force message dispatch. Swift might still use vtable if it knows the exact type.</p><p><strong>dynamic</strong>: Forces message dispatch every time. Always goes through objc_msgSend.</p><pre>class Analytics: NSObject {<br>    @objc dynamic func trackEvent(_ name: String) { }<br>    // Always uses message dispatch — can be swizzled<br>}</pre><h3>What Message Dispatch Enables</h3><p>These powerful features are only possible because of the Objective-C runtime:</p><h3>1. Method Swizzling</h3><p>Swap method implementations at runtime:</p><pre>// Swap viewDidLoad implementations<br>let original = class_getInstanceMethod(UIViewController.self, #selector(viewDidLoad))<br>let swizzled = class_getInstanceMethod(UIViewController.self, #selector(myViewDidLoad))<br>method_exchangeImplementations(original!, swizzled!)</pre><pre>// Now EVERY UIViewController calls your code!</pre><p>This is how analytics SDKs auto-track screen views without you writing code in every view controller.</p><h3>2. Key-Value Observing (KVO)</h3><p>When you observe a property, the runtime:</p><ol><li>Creates a new subclass dynamically (NSKVONotifying_Dog)</li><li>Overrides the setter to notify observers</li><li>Swaps your object’s isa to point to this new class</li></ol><pre>dog.addObserver(self, forKeyPath: &quot;name&quot;, ...)</pre><pre>// Behind the scenes:<br>// dog.isa now points to NSKVONotifying_Dog<br>// The setter notifies you, then calls the original</pre><h3>3. Core Data Magic</h3><p>@NSManaged properties have no implementation in your code:</p><pre>class Person: NSManagedObject {<br>    @NSManaged var name: String  // No getter/setter written!<br>}</pre><p>The runtime creates them dynamically based on your data model.</p><h3>4. Interface Builder Connections</h3><p>IBActions and IBOutlets work because the runtime can look up methods by name (the selector string in your storyboard).</p><h3>Performance: The Real Numbers</h3><pre>Static Dispatch       ████                        ~1 ns<br>                      Direct jump</pre><pre>vtable Dispatch       ██████                      ~1.5-2 ns<br>                      Load vptr → index → jump</pre><pre>Message (cached)      ████████████                ~3-4 ns<br>                      isa → cache lookup → jump</pre><pre>Message (uncached)    ████████████████████████    ~15-20 ns<br>                      Full inheritance search</pre><p>For most code, this difference is negligible. But in tight loops or performance-critical paths, it adds up.</p><h3>The Mental Model</h3><p>Dispatch How It Works Analogy <strong>Static</strong> Address hardcoded at compile time Friend’s number memorized <strong>vtable</strong> Look up index in a table Contact list: position → number <strong>Message</strong> Search for method by name Ask operator: “Connect me to ‘John’”</p><h3>Summary</h3><p>Concept What It Is <strong>Objective-C Runtime</strong> C library that handles dynamic method dispatch <strong>isa pointer</strong> Hidden pointer in every object → &quot;I am a [Class]&quot; <strong>objc_msgSend</strong> The function that performs message dispatch <strong>Selector</strong> A unique identifier for a method name <strong>Method Cache</strong> Hash table for fast repeated lookups <strong>Message Forwarding</strong> Safety net when methods aren&#39;t found <strong>@objc</strong> Makes Swift methods visible to Obj-C runtime <strong>dynamic</strong> Forces message dispatch every time</p><p><strong>objc_msgSend</strong> The function that performs message dispatch <strong>Selector</strong> A unique identifier for a method name <strong>Method Cache</strong> Hash table for fast repeated lookups <strong>Message Forwarding</strong> Safety net when methods aren&#39;t found <strong>@objc</strong> Makes Swift methods visible to Obj-C runtime <strong>dynamic</strong> Forces message dispatch every time</p><h3>Final Thoughts</h3><p>Understanding the Objective-C runtime helped me finally grasp <em>why</em> Swift works the way it does. Why can’t you swizzle pure Swift methods? Why does KVO require @objc dynamic? Why do IBActions need @objc?</p><p>It’s all because of this 40-year-old C library humming along under the hood.</p><p>Swift gives us the best of both worlds: the safety and performance of static typing, with access to the dynamic power of the Objective-C runtime when we need it. Understanding when and why each system is used makes you a better iOS developer.</p><h3>Further Reading</h3><ul><li><a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/">Apple: Objective-C Runtime Programming Guide</a></li><li><a href="https://nshipster.com/objc_msgsend/">NSHipster: objc_msgSend</a></li><li><a href="https://www.mikeash.com/pyblog/">Mike Ash: Friday Q&amp;A on the Objective-C Runtime</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dc475b7e374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Static and Dynamic Dispatch: A Deep Dive for Swift Developers]]></title>
            <link>https://medium.com/@botirjon.nasridinov/understanding-static-and-dynamic-dispatch-a-deep-dive-for-swift-developers-9fd9a3124a1b?source=rss-a59d3d152776------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fd9a3124a1b</guid>
            <dc:creator><![CDATA[Botirjon Nasridinov]]></dc:creator>
            <pubDate>Sun, 14 Dec 2025 09:43:13 GMT</pubDate>
            <atom:updated>2026-08-25T07:11:57.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLhNlwSvwocATAPIUedEew.png" /><figcaption>Generated using Gemini</figcaption></figure><h3>A Confession</h3><p>I’ve read countless articles about static and dynamic dispatch. I studied it at university. I’ve used these concepts in interviews. And for years, I thought I understood them.</p><p>I didn’t. Not really.</p><p>I knew the surface-level definitions — “static dispatch is resolved at compile time, dynamic dispatch at runtime.” I could recite that vtables exist. But when someone asked me <em>how</em> a vtable lookup actually works at the memory level, or <em>why</em> Swift extension methods can’t be overridden, I’d fumble. The knowledge was shallow, memorized rather than understood.</p><p>Recently, I decided to dig deeper. I went back to my university notes on memory layout and pointers. I read the Swift compiler source code. I experimented in playgrounds. And crucially, with AI tools now available, I could instantly clarify every ambiguity that came up — “wait, where exactly does the vptr live in memory?” or “what happens when a subclass doesn’t override a method?”</p><p>That process of re-learning, of finally <em>getting it</em>, is why I’m writing this article.</p><p><strong>If you’re struggling with these concepts</strong> — this is the article I wish I had. I’ll explain things the way I needed them explained, with diagrams and concrete examples.</p><p><strong>If you already know this stuff</strong> — consider this a refresher, a reference you can bookmark and come back to.</p><p>Let’s dig in.</p><h3>What is Method Dispatch?</h3><p>Method dispatch is the mechanism a program uses to determine which implementation of a method to call at any given moment.</p><p>Consider this simple scenario:</p><pre>class Animal {<br>    func speak() { print(&quot;...&quot;) }<br>}</pre><pre>class Dog: Animal {<br>    override func speak() { print(&quot;Woof!&quot;) }<br>}</pre><pre>let animal: Animal = Dog()<br>animal.speak() // Which speak() gets called?</pre><p>The variable animal is typed as Animal, but holds a Dog. When we call speak(), the program needs to figure out: should it call Animal.speak() or Dog.speak()?</p><p>The answer depends on the <strong>dispatch mechanism</strong> being used.</p><h3>Static Dispatch: Decided at Compile Time</h3><p>With <strong>static dispatch</strong> (also called <em>direct dispatch</em>), the compiler determines exactly which function to call at compile time. The compiled binary contains a direct jump to that specific function’s memory address.</p><h3>How It Works</h3><pre>Source Code          Compile Time           Runtime<br>─────────────────────────────────────────────────────<br>greet()      →     &quot;Jump to 0x1000&quot;    →    Execute code at 0x1000</pre><p>The compiler sees the call, knows exactly which function it refers to, and hardcodes the function’s address directly into the binary.</p><h3>Characteristics</h3><ul><li><strong>Fast</strong>: No runtime lookup needed — it’s just a direct jump to a memory address</li><li><strong>Inlinable</strong>: The compiler can even copy the function’s code directly into the call site (inlining)</li><li><strong>Inflexible</strong>: The decision is baked in; you can’t change it at runtime</li></ul><h3>When Swift Uses Static Dispatch</h3><pre>// 1. Structs and Enums (value types)<br>struct Point {<br>    func draw() { } // Static dispatch<br>}</pre><pre>// 2. Final classes and methods<br>final class Logger {<br>    func log() { } // Static dispatch — can&#39;t be overridden<br>}</pre><pre>class Service {<br>    final func validate() { } // Static dispatch<br>}</pre><pre>// 3. Private methods<br>class Parser {<br>    private func tokenize() { } // Static dispatch — compiler knows it can&#39;t be overridden<br>}</pre><pre>// 4. Methods in extensions (without @objc)<br>extension String {<br>    func customTrim() { } // Static dispatch<br>}</pre><h3>Dynamic Dispatch: Decided at Runtime</h3><p>With <strong>dynamic dispatch</strong>, the program determines which function to call <em>while the app is running</em>, based on the actual type of the object.</p><h3>How It Works (Conceptual)</h3><pre>Source Code          Compile Time              Runtime<br>─────────────────────────────────────────────────────────────<br>animal.speak()  →  &quot;Look up speak()    →   Check actual type (Dog)<br>                    in object&#39;s table&quot;      Find Dog&#39;s speak()<br>                                            Jump to that address</pre><p>The compiler doesn’t hardcode the function address. Instead, it generates code that says: “At runtime, look up which speak() implementation this object has.&quot;</p><h3>Characteristics</h3><ul><li><strong>Flexible</strong>: Enables polymorphism — the same code can work with different types</li><li><strong>Slower</strong>: Requires a runtime lookup (though modern CPUs make this very fast)</li><li><strong>Not inlinable</strong>: The compiler can’t inline something it doesn’t know at compile time</li></ul><h3>The Machinery: vtable and vptr</h3><p>Now let’s look under the hood. How does dynamic dispatch actually work at the memory level?</p><h3>The Virtual Table (vtable)</h3><p>A <strong>vtable</strong> (virtual method table) is a data structure that maps method names to their implementations for a specific class.</p><p>Think of it as a lookup table:</p><pre>┌─────────────────────────────────────┐<br>│         Animal&#39;s vtable             │<br>├─────────────────────────────────────┤<br>│  Index 0: speak() → 0x1000 (Animal) │<br>│  Index 1: eat()   → 0x1100 (Animal) │<br>└─────────────────────────────────────┘</pre><pre>┌─────────────────────────────────────┐<br>│          Dog&#39;s vtable               │<br>├─────────────────────────────────────┤<br>│  Index 0: speak() → 0x2000 (Dog)    │  ← Overridden! Points to Dog&#39;s implementation<br>│  Index 1: eat()   → 0x1100 (Animal) │  ← Not overridden, same as Animal<br>└─────────────────────────────────────┘</pre><p>Key insight: <strong>Each class has its own vtable</strong>, stored once in memory. When a subclass overrides a method, its vtable entry points to the new implementation.</p><h3>The Virtual Pointer (vptr)</h3><p>Every <em>instance</em> of a class contains a hidden pointer called the <strong>vptr</strong> (virtual pointer). This pointer points to the class’s vtable.</p><pre>┌────────────────────────┐<br>│     Dog Instance       │<br>├────────────────────────┤<br>│  vptr ─────────────────┼──────→ Dog&#39;s vtable<br>│  name: &quot;Buddy&quot;         │<br>│  age: 3                │<br>└────────────────────────┘</pre><h3>How a Method Call Works</h3><p>When you write animal.speak():</p><ol><li><strong>Follow the vptr</strong>: Go to the object in memory, read its hidden vptr</li><li><strong>Find the vtable</strong>: The vptr points to the class’s vtable</li><li><strong>Look up the method</strong>: Find speak() in the vtable (it&#39;s at index 0)</li><li><strong>Jump to the address</strong>: The vtable entry tells us the actual function address</li><li><strong>Execute</strong>: Jump to that address and run the code</li></ol><pre>animal.speak()</pre><pre>Step 1: animal.vptr → Dog&#39;s vtable<br>Step 2: Dog&#39;s vtable[0] → 0x2000<br>Step 3: Jump to 0x2000, execute Dog.speak()</pre><pre>Output: &quot;Woof!&quot;</pre><p>This is why polymorphism works! Even though animal is typed as Animal, its vptr points to Dog&#39;s vtable, so we get Dog&#39;s implementation.</p><h3>Swift’s Dispatch Mechanisms</h3><p>Swift is more nuanced than languages like Java or C++. It uses <strong>three</strong> dispatch mechanisms:</p><h3>1. Static Dispatch (Direct)</h3><p>Used for value types and final/private methods.</p><pre>struct Calculator {<br>    func add(_ a: Int, _ b: Int) -&gt; Int { a + b }<br>}</pre><pre>let calc = Calculator()<br>calc.add(2, 3) // Direct jump to Calculator.add</pre><h3>2. Table Dispatch (vtable)</h3><p>Used for class methods that can be overridden.</p><pre>class Vehicle {<br>    func start() { print(&quot;Starting...&quot;) }<br>}</pre><pre>class Car: Vehicle {<br>    override func start() { print(&quot;Vroom!&quot;) }<br>}</pre><pre>let v: Vehicle = Car()<br>v.start() // vtable lookup → Car.start()</pre><p>Swift’s vtable is called the <strong>witness table</strong> for classes. Each class has one, and the mechanism works exactly as described above.</p><h3>3. Message Dispatch (Objective-C Runtime)</h3><p>Used for @objc methods and interaction with Objective-C frameworks.</p><pre>class ViewController: UIViewController {<br>    @objc func buttonTapped() { } // Message dispatch<br>}</pre><p>Message dispatch uses Objective-C’s objc_msgSend — it&#39;s even more dynamic (and slower) than vtable dispatch, but enables features like method swizzling and KVO.</p><h3>Swift Dispatch Rules Cheat Sheet</h3><ul><li><strong>Value types (</strong><strong>struct, </strong><strong>enum): </strong>Static Dispatch</li><li><strong>final class or </strong><strong>final func:</strong> Static Dispatch</li><li><strong>private / </strong><strong>fileprivate methods:</strong> Static Dispatch</li><li><strong>Extension methods (without </strong><strong>@objc):</strong> Static Dispatch</li><li><strong>Class methods (can be overridden):</strong> Table Dispatch (vtable)</li><li><strong>@objc methods:</strong> Message Dispatch</li><li><strong>dynamic methods:</strong> Message Dispatch</li><li><strong>Protocol methods (concrete type known):</strong> Static Dispatch</li><li><strong>Protocol methods (</strong><strong>existential any P):</strong> Witness Table</li></ul><h3>Performance Implications</h3><p>Let’s put real numbers to this. Consider a tight loop:</p><pre>protocol Drawable {<br>    func draw()<br>}</pre><pre>struct Circle: Drawable {<br>    func draw() { /* ... */ }<br>}</pre><pre>class Shape: Drawable {<br>    func draw() { /* ... */ }<br>}</pre><pre>// Test 1: Static dispatch (struct, concrete type)<br>let circle = Circle()<br>for _ in 0..&lt;1_000_000 {<br>    circle.draw()<br>}</pre><pre>// Test 2: Table dispatch (class)<br>let shape: Shape = Shape()<br>for _ in 0..&lt;1_000_000 {<br>    shape.draw()<br>}</pre><pre>// Test 3: Witness table (protocol existential)<br>let drawable: any Drawable = Circle()<br>for _ in 0..&lt;1_000_000 {<br>    drawable.draw()<br>}</pre><p>Typical relative performance:</p><ul><li><strong>Static dispatch</strong>: ~1x (baseline)</li><li><strong>Table dispatch</strong>: ~1.2–2x slower</li><li><strong>Witness table</strong>: ~2–4x slower</li><li><strong>Message dispatch</strong>: ~4–10x slower</li></ul><p>In most apps, this difference is negligible. But in performance-critical code (tight loops, rendering, audio processing), it matters.</p><h3>Practical Optimizations</h3><h3>1. Use final When You Don&#39;t Need Inheritance</h3><pre>// Before: Table dispatch<br>class APIClient {<br>    func fetch() { }<br>}</pre><pre>// After: Static dispatch<br>final class APIClient {<br>    func fetch() { }<br>}</pre><h3>2. Prefer Concrete Types Over Protocols in Hot Paths</h3><pre>// Slower: Witness table dispatch<br>func render(items: [any Drawable]) {<br>    items.forEach { $0.draw() }<br>}</pre><pre>// Faster: Static dispatch with generics<br>func render&lt;T: Drawable&gt;(items: [T]) {<br>    items.forEach { $0.draw() }<br>}</pre><h3>3. Whole Module Optimization</h3><p>Enable “Whole Module Optimization” in your build settings. This lets Swift see all your code at once and:</p><ul><li>Automatically infer final for classes that aren&#39;t subclassed</li><li>Inline more aggressively</li><li>Devirtualize method calls where possible</li></ul><h3>4. Use private / fileprivate Appropriately</h3><pre>class Parser {<br>    // Public API — table dispatch (subclasses might override)<br>    func parse(_ input: String) -&gt; AST {<br>        let tokens = tokenize(input)<br>        return buildTree(tokens)<br>    }<br>    <br>    // Internal helpers — static dispatch (private can&#39;t be overridden)<br>    private func tokenize(_ input: String) -&gt; [Token] { }<br>    private func buildTree(_ tokens: [Token]) -&gt; AST { }<br>}</pre><h3>Why This Matters Beyond Performance</h3><p>Understanding dispatch helps explain Swift’s design decisions. These were the “aha!” moments that made everything click for me:</p><p><strong>Q: Why can’t I override extension methods?</strong> A: Extensions use static dispatch. The method to call is determined at compile time based on the declared type, not the runtime type.</p><pre>class Animal { }<br>class Dog: Animal { }</pre><pre>extension Animal {<br>    func greet() { print(&quot;Hello from Animal&quot;) }<br>}</pre><pre>extension Dog {<br>    func greet() { print(&quot;Hello from Dog&quot;) } // This is a NEW method, not an override<br>}</pre><pre>let pet: Animal = Dog()<br>pet.greet() // &quot;Hello from Animal&quot; — static dispatch uses declared type</pre><p><strong>Q: Why do protocols with </strong><strong>Self or associated types behave differently?</strong> A: They require the compiler to know the concrete type for static dispatch, which is why you can&#39;t use them as existentials (without any).</p><p><strong>Q: Why is </strong><strong>@objc required for selectors?</strong> A: Selectors are a runtime lookup mechanism that depends on Objective-C&#39;s message dispatch.</p><h3>Summary</h3><p>Concept What It Is <strong>Static Dispatch</strong> Compiler knows the exact function at compile time. Fast, inlinable. <strong>Dynamic Dispatch</strong> Function determined at runtime based on actual object type. Enables polymorphism. <strong>vtable</strong> Per-class table mapping method slots to implementation addresses <strong>vptr</strong> Per-instance hidden pointer to the class’s vtable <strong>Witness Table</strong> Swift’s vtable equivalent for protocols</p><p>The beauty of Swift is that it gives you control. Use classes and protocols when you need flexibility; use structs, final, and concrete types when you need speed. Understanding dispatch helps you make that tradeoff intentionally.</p><h3>Final Thoughts</h3><p>When I started re-learning this topic, I realized something: the gap between “knowing” and “understanding” is vast. I had memorized definitions for years without truly grasping what happens at the memory level.</p><p>The turning point for me was forcing myself to explain it — to draw the diagrams, to trace through a method call step by step, to answer my own “but why?” questions instead of glossing over them.</p><p>If this article helped bridge that gap for you, I’ve done my job. If something still doesn’t click, drop a comment — teaching is how I learn best, and your questions might reveal gaps in my own understanding that I need to fill.</p><p>Keep digging. The fundamentals are worth it.</p><h3>Further Reading</h3><ul><li><a href="https://www.swift.org/blog/whole-module-optimizations/">Swift.org: Whole Module Optimization</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2016/416/">WWDC 2016: Understanding Swift Performance</a></li><li><a href="https://www.mikeash.com/pyblog/">Mike Ash: Friday Q&amp;A on vtables</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fd9a3124a1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GCD Main Queue vs. Main Thread: Understanding the Subtle Difference]]></title>
            <link>https://medium.com/@botirjon.nasridinov/gcd-main-queue-vs-main-thread-understanding-the-subtle-difference-83f26c18b632?source=rss-a59d3d152776------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f26c18b632</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[dispatchqueue]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Botirjon Nasridinov]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 10:54:46 GMT</pubDate>
            <atom:updated>2025-02-13T10:54:46.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRqpQIUO7PQThuL7XYHClA.jpeg" /></figure><p>When working with concurrency in iOS development, the terms <strong>Main Queue</strong> and <strong>Main Thread</strong> often come up. They are closely related but not identical, and misunderstanding their distinction can lead to subtle bugs in your apps. This article will explore the difference, explain why relying solely on Thread.isMainThread can be problematic, and show you how to properly check if you’re on the main queue.</p><h4>What is the Main Queue?</h4><p>DispatchQueue.main represents the main dispatch queue in <strong>Grand Central Dispatch (GCD)</strong>. It is a serial queue that executes tasks on the main thread. This queue is crucial because many UI-related operations must be performed on it.</p><h4>What is the Main Thread?</h4><p>The main thread is the primary thread of your application. It is responsible for handling user interface updates and event processing.</p><h4>The Key Difference</h4><p>While the main queue schedules work on the main thread, the main thread can execute work from any queue when it is idle. This is where confusion often arises:</p><ul><li><strong>Main Queue guarantees Main Thread execution.</strong></li><li><strong>Main Thread does not guarantee execution from the Main Queue.</strong></li></ul><h4><strong>Why Does This Matter?</strong></h4><p>Some developers check Thread.isMainThread to ensure their code is running on the main thread before doing some work that requires to be run on the main queue. However, this check is not sufficient in all cases. You may be on the main thread but not on the main queue if the main thread is executing work from a different queue while idle.</p><h4>When You Need the Main Queue</h4><p>There are several scenarios where you must explicitly schedule work on the main queue:</p><ul><li><em>UI Updates (UIKit and SwiftUI require the main queue)</em></li><li><em>CoreAnimation operations</em></li><li><em>Certain Apple APIs (e.g., UIApplication.shared, NotificationCenter observers)</em></li></ul><p>Failing to use the main queue in these cases can lead to crashes or undefined behavior.</p><p><strong>Why</strong> Thread.isMainThread <strong>Can Fail You</strong></p><p>Consider this example:</p><pre>if Thread.isMainThread {<br>    print(&quot;On main thread&quot;)<br>}</pre><p>This tells you that you are on the main thread, but it says nothing about the main queue. The main thread could be servicing a task from a background queue during idle time.</p><h4>How to Properly Check If You’re on the Main Queue</h4><p>Apple does not provide a built in function to check if we are on the main queue. However, you can still check if you’re on the main queue using dispatch specific keys:</p><pre>extension DispatchQueue {<br>    private static var mainQueueKey: DispatchSpecificKey&lt;()&gt; = {<br>        let key = DispatchSpecificKey&lt;()&gt;()<br>        DispatchQueue.main.setSpecific(key: key, value: ())<br>        return key<br>    }()<br><br>    static var isCurrentQueueMain: Bool {<br>        return DispatchQueue.getSpecific(key: mainQueueKey) != nil<br>    }<br>}</pre><p>Usage:</p><pre>if DispatchQueue.isCurrentQueueMain {<br>    print(&quot;On main queue&quot;)<br>} else {<br>    print(&quot;Not on main queue&quot;)<br>}</pre><p>This approach is more reliable because it checks the queue context instead of just the thread.</p><h4>Final Thoughts</h4><p>Use DispatchQueue.main.async whenever you need to ensure code runs on the main queue.</p><p>Avoid relying solely on Thread.isMainThread for critical main queue operations.</p><p>Use <strong><em>dispatch-specific keys</em></strong> if you need to check your current queue.</p><p>Understanding this distinction can save you from subtle concurrency bugs and ensure that your UI remains smooth and responsive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f26c18b632" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Composite Pattern in Swift: A Practical Guide]]></title>
            <link>https://medium.com/@botirjon.nasridinov/mastering-the-composite-pattern-in-swift-a-practical-guide-3ba7d88768dd?source=rss-a59d3d152776------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ba7d88768dd</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[composite-pattern]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Botirjon Nasridinov]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 18:49:02 GMT</pubDate>
            <atom:updated>2025-02-12T19:14:11.826Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgTyq9z0Gj6OClWjt-ccVQ.jpeg" /><figcaption>Photo by Aiman Inam: <a href="https://www.pexels.com/photo/multi-colored-click-pen-on-white-background-4693488/">https://www.pexels.com/photo/multi-colored-click-pen-on-white-background-4693488/</a></figcaption></figure><h4><strong>Introduction</strong></h4><p>Design patterns provide reusable solutions to common programming challenges. One of the most powerful structural patterns is the <strong>Composite Pattern</strong>, which allows you to handle groups of objects and individual objects uniformly.</p><p>In this article, we will explore the Composite Pattern in depth, starting with a <strong>file system analogy</strong> to build foundational understanding. Then, we will implement a real-world example using a <strong>DataLoader</strong> system, where we create a composite loader that handles primary and fallback sources dynamically.</p><h4><strong>What is the Composite Pattern?</strong></h4><p>The <strong>Composite Pattern</strong> is a structural design pattern that allows you to treat both individual objects and groups of objects in the same way. This is useful when working with <strong>hierarchical structures</strong>, such as <strong>file systems</strong>, <strong>UI elements.</strong></p><p><strong>Key Benefits:</strong></p><ul><li>✅ Treats individual objects and collections uniformly</li><li>✅ Promotes composition over inheritance</li><li>✅ Simplifies client code</li><li>✅ Improves flexibility in handling hierarchical structures</li></ul><h4><strong>Understanding the Composite Pattern with a File System Example</strong></h4><p>A file system consists of <strong>files and folders</strong>. A folder can contain multiple files or other folders. The <strong>Composite Pattern</strong> allows us to treat both files and folders the same way by defining a common interface.</p><p><strong>Step 1: Define the Component Protocol</strong></p><pre>protocol FileSystemComponent {<br>    var name: String { get }<br>    func display(indent: String)<br>}</pre><p><strong>Step 2: Create Leaf Class (File)</strong></p><pre>class File: FileSystemComponent {<br>    let name: String<br>    <br>    init(name: String) {<br>        self.name = name<br>    }<br>    <br>    func display(indent: String = &quot;&quot;) {<br>        print(&quot;\(indent)- \(name)&quot;)<br>    }<br>}</pre><p><strong>Step 3: Create Composite Class (Folder)</strong></p><pre>class Folder: FileSystemComponent {<br>    let name: String<br>    private var children: [FileSystemComponent] = []<br>    <br>    init(name: String) {<br>        self.name = name<br>    }<br>    <br>    func add(_ component: FileSystemComponent) {<br>        children.append(component)<br>    }<br>    <br>    func display(indent: String = &quot;&quot;) {<br>        print(&quot;\(indent)+ \(name)&quot;)<br>        for child in children {<br>            child.display(indent: indent + &quot;  &quot;)<br>        }<br>    }<br>}</pre><p><strong>Step 4: Testing the File System Composite</strong></p><pre>let root = Folder(name: &quot;Root&quot;)<br>let file1 = File(name: &quot;File1.txt&quot;)<br>let file2 = File(name: &quot;File2.txt&quot;)<br>let subFolder = Folder(name: &quot;SubFolder&quot;)<br><br>subFolder.add(File(name: &quot;NestedFile1.txt&quot;))<br>subFolder.add(File(name: &quot;NestedFile2.txt&quot;))<br><br>root.add(file1)<br>root.add(file2)<br>root.add(subFolder)<br><br>root.display()</pre><p><strong>Output:</strong></p><pre>+ Root<br>  - File1.txt<br>  - File2.txt<br>  + SubFolder<br>    - NestedFile1.txt<br>    - NestedFile2.txt</pre><h3><strong>Real-World Example: Composite DataLoader with Primary and Fallback Loaders</strong></h3><p>Now that we understand the Composite Pattern, let’s apply it to a real-world scenario: a data loading system with primary and fallback loaders.</p><p><strong>Step 1: Define the DataLoader Protocol</strong></p><pre>protocol DataLoader {<br>    func loadData(completion: @escaping (String?) -&gt; Void)<br>}<br></pre><p><strong>Step 2: Create Concrete Loaders</strong></p><p><strong>Remote Data Loader</strong></p><pre>class RemoteDataLoader: DataLoader {<br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 2) {<br>            let success = Bool.random() // Simulating network success/failure<br>            completion(success ? &quot;Data from remote server&quot; : nil)<br>        }<br>    }<br>}</pre><p><strong>Local Data Loader</strong></p><pre>class LocalDataLoader: DataLoader {<br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>             DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>            completion(&quot;Data from local storage&quot;)<br>        }<br>    }<br>}</pre><p><strong>Step 3: Implement Composite Data Loader with Primary and Fallback Sources</strong></p><pre>class CompositeDataLoader: DataLoader {<br>    private let primaryLoader: DataLoader<br>    private let fallbackLoader: DataLoader<br><br>    init(primary: DataLoader, fallback: DataLoader) {<br>        self.primaryLoader = primary<br>        self.fallbackLoader = fallback<br>    }<br><br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        primaryLoader.loadData { data in<br>            if let data = data {<br>                completion(data)<br>            } else {<br>                print(&quot;Primary loader failed, using fallback…&quot;)<br>                self.fallbackLoader.loadData(completion: completion)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Step 4: Testing the Composite Data Loader</strong></p><pre>let remoteLoader = RemoteDataLoader()<br>let localLoader = LocalDataLoader()<br>let compositeLoader = CompositeDataLoader(<br>    primary: remoteLoader, <br>    fallback: localLoader<br>)<br><br>compositeLoader.loadData { data in<br>    print(&quot;Final Data: \(data ?? &quot;No Data Available&quot;)&quot;)<br>}</pre><p><strong>Possible Output</strong>:</p><pre>Primary loader failed, using fallback…<br>Final Data: Data from local storage</pre><p>In this case, if the primary (remote) loader fails, the fallback (local) loader is used, demonstrating the Composite Pattern in action.</p><p><strong>Conclusion</strong></p><p>The <strong>Composite Pattern</strong> is a powerful design pattern that allows us to treat individual objects and groups of objects uniformly. We explored it using a file system example and then applied it to a real-world data loading system with primary and fallback loaders.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ba7d88768dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Decorator Pattern in Swift: A Practical Guide]]></title>
            <link>https://medium.com/@botirjon.nasridinov/mastering-the-decorator-pattern-in-swift-a-practical-guide-856de4a5a4f6?source=rss-a59d3d152776------2</link>
            <guid isPermaLink="false">https://medium.com/p/856de4a5a4f6</guid>
            <category><![CDATA[decorator-pattern]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Botirjon Nasridinov]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 14:24:18 GMT</pubDate>
            <atom:updated>2025-02-13T06:40:25.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o76FQ_87AxLLPxMSzewUFg.jpeg" /><figcaption>Photo by Lisa Fotios: <a href="https://www.pexels.com/photo/crates-mounted-on-wall-1090638/">https://www.pexels.com/photo/crates-mounted-on-wall-1090638/</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Design patterns play a crucial role in software architecture by providing reusable solutions to common programming problems. One such pattern is the <strong>Decorator Pattern</strong>, which allows dynamic extension of an object’s behavior without modifying its source code. In this article, we will explore how the <strong>Decorator Pattern</strong> works and implement a practical example in Swift.</p><p><strong>What is the Decorator Pattern?</strong></p><p>The <strong>Decorator Pattern</strong> is a <strong>structural design pattern</strong> that allows you to attach additional responsibilities to an object dynamically. This pattern is often used when subclassing would be impractical or lead to an explosion of subclasses.</p><p><strong>Key Benefits:</strong></p><ul><li>Promotes composition over inheritance, reducing class hierarchy complexity.</li><li>Provides a flexible alternative to subclassing.</li><li>Enables runtime behavior modification without altering the original class.</li><li>Supports open-closed principle (OCP) from SOLID principles.</li></ul><p><strong>When to Use the Decorator Pattern?</strong></p><p>Use the <strong>Decorator Pattern</strong> when:</p><ul><li>You need to add behavior dynamically to objects.</li><li>You want to avoid creating multiple subclasses for different combinations of functionalities.</li><li>You need to extend the behavior of classes without modifying their existing implementation.</li></ul><h3><strong>Real-World Example: Loaders with Logging and Main Queue Dispatching Behavior</strong></h3><p>To demonstrate the Decorator Pattern, we will build a data loader system that loads data from remote or local sources while adding logging, caching, and main queue dispatching behavior dynamically.</p><p><strong>Step 1: Define the Loader Protocol</strong></p><pre>protocol DataLoader {<br>    func loadData(completion: @escaping (String?) -&gt; Void)<br>}</pre><p><strong>Step 2: Create Concrete Loader Implementation</strong></p><p><strong>Remote Data Loader</strong></p><pre>class RemoteDataLoader: DataLoader {<br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        completion(&quot;Data from remote server&quot;)<br>    }<br>}</pre><p><strong>Local Data Loader with Caching</strong></p><pre>class LocalDataLoader: DataLoader {<br>    private var cache: String?<br>    <br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        completion(cache)<br>    }<br><br>    func cache(_ data: String?) {<br>        self.cache = cache<br>    }<br>}</pre><p><strong>Step 3: Implement a Logging Decorator</strong></p><pre>class LoggingDecorator: DataLoader {<br>    private let wrappedLoader: DataLoader<br>    <br>    init(loader: DataLoader) {<br>        self.wrappedLoader = loader<br>    }<br>    <br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        wrappedLoader.loadData { data in<br>            print(&quot;[LOG] Loaded Data: \(data)&quot;)<br>            completion(data)<br>        }<br>    }<br>}</pre><p>This decorator logs every data loading event.</p><p><strong>Step 4: Implement a Main Queue Dispatch Decorator</strong></p><pre>class MainQueueDecorator: DataLoader {<br>    private let wrappedLoader: DataLoader<br>    <br>    init(loader: DataLoader) {<br>        self.wrappedLoader = loader<br>    }<br>    <br>    func loadData(completion: @escaping (String?) -&gt; Void) {<br>        wrappedLoader.loadData { data in<br>            if Thread.isMainThread {<br>                print(&quot;Already on main thread&quot;)<br>                completion(data)<br>            } else {<br>                DispatchQueue.main.async {<br>                    print(&quot;Dispatching to main queue&quot;)<br>                    completion(data)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>This ensures that the completion handler always executes on the main queue.</p><p><strong>Step 5: Testing the Loader System</strong></p><pre>// 1.<br>var loader: DataLoader = RemoteDataLoader()<br>loader = LoggingDecorator(loader: loader)<br>loader = MainQueueDecorator(loader: loader)<br><br>loader.loadData { data in<br>    print(&quot;Final Data: \(data)&quot;)<br>}<br><br>// 2.<br>var anotherLoader: DataLoader = LocalDataLoader()<br>anotherLoader.cache(&quot;Data from memory&quot;)<br>anotherLoader = LoggingDecorator(loader: anotherLoader)<br><br>anotherLoader.loadData { data in<br>    print(&quot;Final Data: \(data)&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>[LOG] Loaded Data: Data from remote server<br>Dispatching to main queue<br>Final Data: Data from remote server<br><br>[LOG] Loaded Data: Data from memory<br>Final Data: Data from memory</pre><p><strong>Conclusion</strong></p><p>By applying the Decorator Pattern, we dynamically add logging and main queue dispatching behavior to our data loaders without modifying their implementations. This approach promotes flexibility, modularity, and cleaner code in Swift applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=856de4a5a4f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>