<?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 Soma Sharma on Medium]]></title>
        <description><![CDATA[Stories by Soma Sharma on Medium]]></description>
        <link>https://medium.com/@somasharma95?source=rss-8424faeb04c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UyqejCIzll_25hg5bZUqYw@2x.jpeg</url>
            <title>Stories by Soma Sharma on Medium</title>
            <link>https://medium.com/@somasharma95?source=rss-8424faeb04c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:07:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@somasharma95/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[Mastering Memory: The Deep Tech Behind Swift ARC, Weak/Unowned, and Instruments]]></title>
            <link>https://medium.com/@somasharma95/mastering-memory-the-deep-tech-behind-swift-arc-weak-unowned-and-instruments-43498415f03b?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/43498415f03b</guid>
            <category><![CDATA[automatic-reference-count]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 13:08:39 GMT</pubDate>
            <atom:updated>2025-12-25T13:08:39.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6kbsRssq05JuHX5Nu8aUg.png" /></figure><p>Memory management in Swift is often described as “Automatic,” but that doesn’t mean it’s magic. If you’ve ever seen your app’s memory footprint climb steadily or wondered why a specific screen never seems to leave memory, you’ve encountered the limits of <strong>Automatic Reference Counting (ARC)</strong>.</p><p>In this article, we’ll go under the hood of the Swift runtime, settle the “Compile-time vs. Runtime” debate, and learn how to use Xcode Instruments to hunt down leaks like a pro.</p><h4>The Deep Dive: Is ARC Compile-Time or Runtime?</h4><p>One of the most common misconceptions in iOS development is that ARC is purely a compile-time feature. The truth is: <strong>ARC is a hybrid system.</strong></p><h4>The Compile-Time “Planner”</h4><p>During compilation, the Swift compiler (swiftc) performs a static analysis of your code’s object lifetimes. It identifies exactly where a reference starts and where it is no longer needed. It then injects retain (to increment the count) and release (to decrement it) calls directly into your binary.</p><h4>The Runtime “Executor”</h4><p>While the compiler plans the work, the <strong>Swift Runtime</strong> executes it. When your app is running, these injected calls update an internal “Reference Count” stored in the object’s header on the heap. When that count hits zero, the runtime immediately calls the object’s deinit and reclaims the memory.</p><h4>Cleaning the Heap: What are Side Tables?</h4><p>You might wonder: <em>If an object is deallocated, how does a </em><em>weak variable safely turn to </em><em>nil without pointing to &quot;garbage&quot; memory?</em></p><p>Swift uses a clever mechanism called <strong>Side Tables</strong>.</p><ol><li>Initially, an object stores its reference counts in its own header.</li><li>The moment you create a weak reference to that object, the runtime strips the counts out and puts them into a separate &quot;Side Table&quot; in memory.</li><li>The weak reference now points to the <strong>Side Table</strong>, not the object itself.</li><li>When the object dies, the Side Table remains. When you access the weak pointer, it checks the Side Table, sees the object is gone, and returns nil.</li></ol><h4>The Retain Cycle Problem</h4><p>A retain cycle occurs when two class instances hold strong references to each other.</p><p>Even if your View Controller is dismissed, if it has a strong reference to a Service, and that Service has a strong reference back to the View Controller, the reference count for both stays at 1. They become “zombie objects” trapped in memory forever.</p><p>Let’s look at an example:</p><pre>class Person {<br>    var pet: Pet?<br>}<br><br>class Pet {<br>    var owner: Person?<br>}<br><br>var john: Person? = Person()<br>var dog: Pet? = Pet()<br><br>john?.pet = dog<br>dog?.owner = john<br><br>john = nil<br>dog = nil</pre><p>You might expect both objects to be deallocated, but they’re not.<br> Here’s why:</p><ul><li>john owns dog</li><li>dog owns john</li><li>Both hold <strong>strong references</strong> → ARC can’t deallocate either<br> = <strong>Memory leak</strong></li></ul><p>You can verify this by adding:</p><pre>deinit {<br>    print(&quot;Deinit called&quot;)<br>}</pre><p>You’ll notice it never prints.</p><h4>Fixing Retain Cycles with weak and unowned:</h4><p>To break these cycles, we use “non-strong” references. But choosing the wrong one can lead to fatal error: unexpectedly found nil or memory corruption.</p><h4>weak</h4><ul><li><strong>The Safety Net:</strong> It does not keep a strong hold on the instance.</li><li><strong>Zeroing:</strong> When the object it points to is deallocated, ARC automatically sets the weak variable to nil.</li><li><strong>Requirement:</strong> Must be declared as an <strong>Optional </strong><strong>var</strong></li></ul><pre>class Person {<br>    var pet: Pet?<br>}<br><br>class Pet {<br>    weak var owner: Person?<br>}</pre><h4>unowned</h4><ul><li><strong>The Lean Link:</strong> Like weak, it doesn&#39;t increase the reference count.</li><li><strong>The Danger:</strong> It assumes the other object will <strong>outlive</strong> it. It does not zero out.</li><li><strong>Risk:</strong> If you access an unowned reference after the object is gone, your app will crash.</li></ul><pre>class Customer {<br>    var card: CreditCard?<br>}<br><br>class CreditCard {<br>    unowned let customer: Customer<br>    init(customer: Customer) {<br>        self.customer = customer<br>    }<br>}</pre><h4>Common Retain Cycle Traps</h4><p>Even experienced iOS developers run into these pitfalls:</p><ol><li>Closures capturing self strongly</li></ol><pre>class ProfileViewController: UIViewController {<br>    var onUpdate: (() -&gt; Void)?<br><br>    func setupRealtimeListener() {<br>        // This creates a retain cycle<br>        onUpdate = {<br>            self.refreshUI() <br>        }<br>    }<br>}</pre><p>By adding [weak self], you tell the closure to treat self as a weak reference.</p><pre>onUpdate = { [weak self] in <br>    guard let self = self else { return }<br>    self.refreshUI()<br>}</pre><p>Or [unowned self] when you are sure self will exist:</p><h4>Detective Work: Finding Leaks with Instruments</h4><p>Xcode provides a powerful suite of tools to find memory leaks. While the <strong>Memory Graph Debugger</strong> is great for a quick look, the <strong>Leaks Instrument</strong> is the gold standard for deep analysis.</p><p>Step-by-Step: The Leaks Instrument:</p><ol><li><strong>Launch:</strong> Press Cmd + I in Xcode and select <strong>Leaks</strong>.</li><li><strong>Record:</strong> Hit the record button and navigate through your app.</li><li><strong>The Red Diamond:</strong> If a leak occurs, a red diamond will appear in the timeline.</li><li><strong>Cycles &amp; Roots:</strong> In the bottom detail pane, switch to “Cycles &amp; Roots.” Instruments will literally draw a graph showing you exactly which objects are pointing to each other.</li></ol><p>The “Deinit” Trick:</p><p>Before reaching for Instruments, add a deinit message to your classes:</p><pre>deinit {<br>    print(&quot;\(Self.self) was successfully deallocated&quot;)<br>}</pre><p>If you dismiss a view controller and don’t see that message in the console, you have a leak.</p><h4>So today we learnt:</h4><ul><li>Use <strong>weak</strong> when the reference <em>might become nil</em> (e.g., delegates, closures).</li><li>Use <strong>unowned</strong> when the reference <em>must always exist</em> and lifecycles are tied.</li><li>Always use <strong>[weak self]</strong> in escaping closures unless you’re certain self outlives the closure.</li><li>Use <strong>Instruments</strong> regularly to detect leaks early.</li></ul><h4>At the end:</h4><p>Understanding the interplay between compile-time injections and runtime side tables transforms you from a developer who “just writes code” into an engineer who understands the machine. Swift makes memory management easier than almost any other language, but it still requires your intent.</p><p>By being intentional with your references and diligent with your tools, you ensure that your app remains as fast and responsive on day 100 as it was on day one.</p><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43498415f03b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Under the Hood: How Functions and Memory Really Work]]></title>
            <link>https://medium.com/@somasharma95/swift-under-the-hood-how-functions-and-memory-really-work-cc2ddcb91cb2?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2ddcb91cb2</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[dynamic-dispatch]]></category>
            <category><![CDATA[static-dispatch]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[structs-vs-classes]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 17:49:01 GMT</pubDate>
            <atom:updated>2025-11-18T17:50:28.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37goAeLxpO36bDutS1oXOQ.jpeg" /></figure><p>Every line of code you write in Swift involves a fundamental tradeoff between <strong>performance</strong> and <strong>flexibility</strong>. When you call a function or instantiate a type, the Swift compiler silently makes critical decisions: <strong>Where</strong> in memory should this data live (<strong>Stack vs. Heap</strong>)? And <strong>how</strong> should this function be executed (<strong>Static vs. Dynamic Dispatch</strong>)? you’ve probably heard things like:</p><p><em>“Structs are faster than classes.”</em></p><p><em>“Mark your classes as </em><em>final to improve performance.”</em></p><p><em>“Avoid protocol existentials when possible.”</em></p><p>But why are these statements true? Lets understand these concepts.</p><h4>Method Dispatch: How Swift Decides What to Run</h4><p>Dispatch is the process of deciding which piece of code (which method implementation) to execute when a function is called.</p><ol><li>Static Dispatch:</li></ol><p>Static dispatch is the <strong>fastest</strong> method. The compiler knows the exact memory address of the function to call <strong>before</strong> the program runs (at compile-time). It achieves this by embedding the function’s memory address directly into the compiled code, executing a <strong>direct jump</strong> at runtime with zero overhead.</p><p>This mechanism is typically used for:</p><ul><li><strong>Value Types:</strong> Methods on <strong>Structs</strong> and <strong>Enums</strong> are almost always statically dispatched because they don’t support inheritance.</li><li><strong>The </strong><strong>final keyword:</strong> Marking a class or a class method as final prevents overriding, allowing the compiler to commit to static dispatch.</li><li><strong>Private/Internal methods:</strong> If the method’s scope is restricted, the compiler can safely optimize it for speed.</li></ul><pre>struct Dog {<br>    func bark() {<br>        print(&quot;Woof!&quot;)<br>    }<br>}<br><br>let dog = Dog()<br>dog.bark() //Static dispatch</pre><p>2. Dynamic Dispatch:</p><p>Dynamic dispatch is essential for <strong>polymorphism</strong> but is <strong>slower</strong> than static dispatch. The method to call is determined <strong>while</strong> the program is running (at runtime), based on the object’s actual type.</p><p>Swift achieves this via:</p><ul><li><strong>V-Tables (Virtual Tables):</strong> Used for overridable methods in <strong>non-final Classes</strong>. When a method is called, the program performs a table lookup to find the correct function address.</li><li><strong>Witness Tables:</strong> Used when calling methods through a <strong>Protocol Existential</strong> (treating an object only as its protocol type, e.g., let pet: Animal).</li></ul><p>The core difference is the resolution time: Static is resolved at <strong>Compile-Time</strong>, while Dynamic is resolved at <strong>Run-Time</strong> via a lookup, adding overhead for the benefit of greater flexibility.</p><pre>class Animal {<br>    func speak() {<br>        print(&quot;Generic animal sound&quot;)<br>    }<br>}<br><br>class Cat: Animal {<br>    override func speak() {<br>        print(&quot;Meow!&quot;)<br>    }<br>}<br><br>let animal: Animal = Cat()<br>animal.speak() //Dynamic dispatch</pre><h4>Optimization Tip: The Power of final and Generics</h4><p>You can manually force static dispatch in classes using the <strong>final</strong> keyword. For protocols, using <strong>Generics</strong> (func process&lt;T: MyProtocol&gt;(item: T)) allows the compiler to know the concrete type, often converting a dynamic protocol call into a faster static one.</p><pre>protocol Animal {<br>    func makeSound()<br>}<br><br>struct Dog: Animal {<br>    func makeSound() { print(&quot;Woof!&quot;) }<br>}<br><br>struct Cat: Animal {<br>    func makeSound() { print(&quot;Meow!&quot;) }<br>}<br><br>// Existential version (dynamic)<br>func playWith(_ animal: Animal) {<br>    animal.makeSound()<br>}<br><br>// Generic version (static)<br>func playWith&lt;T: Animal&gt;(_ animal: T) {<br>    animal.makeSound()<br>}<br><br>playWith(Dog()) // Static dispatch<br>playWith(Cat()) // Static dispatch</pre><pre>class BaseModel {<br>    // Cannot be overridden: Static Dispatch<br>    final func logCreation() {<br>        print(&quot;Model instance created.&quot;)<br>    }<br>    <br>    // Can be overridden: Dynamic Dispatch<br>    func process() {<br>        print(&quot;Processing base model.&quot;)<br>    }<br>}<br><br>class AdvancedModel: BaseModel {<br>    override func process() {<br>        print(&quot;Processing advanced model (requires V-Table lookup).&quot;)<br>    }<br>}<br><br>let advanced = AdvancedModel()<br>advanced.logCreation() // Static jump (Fast)<br>advanced.process()     // V-Table lookup (Slower)</pre><h4>Stack vs. Heap: The Memory Arena</h4><p>Method dispatch speed is closely tied to where your data lives. Swift memory is divided into two major regions, each optimized for different purposes.</p><ol><li>The Stack (Fast and Automatic):</li></ol><p>Think of the stack as a neat, organized <strong>Last-In, First-Out (LIFO)</strong> pile. It is used for memory that is short-lived and of a known size, primarily <strong>Value Types</strong> (<strong>Structs</strong> and <strong>Enums</strong>).</p><ul><li><strong>Allocation:</strong> <strong>Extremely Fast</strong>. Allocation and deallocation are simple, involving just moving a pointer.</li><li><strong>Lifetime:</strong> Memory is instantly freed when the function or scope that created it returns.</li><li><strong>Safety:</strong> Each thread has its own stack, meaning it’s inherently thread-safe.</li></ul><pre>struct Point { var x, y: Int }<br><br>func move() {<br>    let p = Point(x: 5, y: 10)<br>} //&#39;p&#39; destroyed automatically when function ends</pre><p>2. The Heap (Flexible and Shared):</p><p>The heap is a large, unorganized warehouse used for memory that must persist beyond a single function call, mainly for <strong>Reference Types</strong> (<strong>Classes</strong>).</p><ul><li><strong>Allocation:</strong> <strong>Slower</strong> than the stack because the system must dynamically find a free block of memory.</li><li><strong>Lifetime:</strong> Objects persist as long as they have at least one active reference, managed automatically by <strong>ARC (Automatic Reference Counting)</strong>.</li><li><strong>Safety:</strong> The heap is shared across all threads, potentially requiring synchronization for safe access.</li></ul><p><strong>Key Distinction:</strong> The <strong>instance</strong> of a Class (the object itself) lives on the <strong>Heap</strong>. The <strong>instance</strong> of a Struct (the data) lives on the <strong>Stack</strong> (if it&#39;s a local variable).</p><pre>// Class: Reference Type: Lives on the HEAP (managed by ARC)<br>class User {<br>    var id: Int<br>    init(id: Int) { self.id = id }<br>}<br><br>// Struct: Value Type: Lives on the STACK (when used locally)<br>struct Point {<br>    var x: Int<br>    var y: Int<br>}<br><br>func allocateMemory() {<br>    // 1. Point `p1` is allocated on the STACK. <br>    var p1 = Point(x: 10, y: 20)<br>    <br>    // When `p2` is assigned, a *new copy* is created on the STACK.<br>    var p2 = p1<br>    p2.x = 50 // Only p2 changes (Value Semantics).<br>    <br>    // 2. Class instance (The actual object data) is allocated on the HEAP.<br>    let user1 = User(id: 1)<br>    <br>    // `user2` copies the reference (a pointer stored on the Stack), <br>    // pointing to the same HEAP object.<br>    let user2 = user1 <br>    user2.id = 2 // Both user1 and user2 see this change (Reference Semantics).<br>}<br><br>allocateMemory()</pre><h4>At the end:</h4><p>In Swift, choosing between a struct (value type) and a class (reference type) affects both <strong>performance</strong> and <strong>design</strong>. Structs use <strong>static dispatch</strong> and <strong>stack allocation</strong>, offering speed and safety for immutable data.<br>Classes rely on <strong>dynamic dispatch</strong> and <strong>heap allocation</strong>, enabling flexibility, shared state, and inheritance.<br>While dynamic dispatch and ARC add slight overhead, they’re essential for building rich, adaptable architectures.<br>Great Swift code balances the <strong>efficiency of value types</strong> with the <strong>flexibility of reference types</strong>.</p><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc2ddcb91cb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in Swift: Building Scalable and Testable iOS Projects]]></title>
            <link>https://medium.com/@somasharma95/dependency-injection-in-swift-building-scalable-and-testable-ios-projects-beef93268dce?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/beef93268dce</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 19:45:00 GMT</pubDate>
            <atom:updated>2025-10-16T19:48:53.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHEkijS1Uh0jyRwKOcVnxg.jpeg" /></figure><p>Building an iOS app is an exciting journey, but as your project grows from a simple prototype into a feature-rich application, you invariably hit a wall. Suddenly, making a small change in your networking layer forces you to update a dozen view models. Your unit tests become slow, flaky, or even impossible to write.</p><p>The culprit is often <strong>tight coupling</strong>, and the solution is a powerful design pattern known as <strong>Dependency Injection (DI)</strong>.</p><h4>What Exactly is Dependency Injection?</h4><p>In its simplest form, Dependency Injection means a class should <strong>never create the objects it depends on</strong> instead, those dependencies should be <em>provided to it</em> from the outside.</p><p>Think of it as asking your ViewModel:</p><p>“Here’s the service you need. Just use it, don’t build it yourself.”</p><pre>final class ProfileViewModel {<br>    private let service = ProfileService() // tightly coupled<br>}</pre><pre>final class ProfileViewModel {<br>    private let service: ProfileServiceProtocol<br>    <br>    init(service: ProfileServiceProtocol) {<br>        self.service = service<br>    }<br>}</pre><p>Now, ProfileViewModel doesn’t care where service comes from.<br> It could be:</p><ul><li>A real ProfileService in production.</li><li>A MockProfileService in tests.</li></ul><h4>DI and Testability: Isolate and Conquer</h4><p>One of the greatest immediate benefits of Dependency Injection is the enormous boost it gives to <strong>unit testing</strong>. Without DI, your UserViewModel is tightly bound to the <em>real</em> APIService, meaning your tests will make actual network calls. This leads to slow, unreliable tests that break whenever the server is down.</p><p>With DI, you can easily swap the real dependency for a <strong>mock</strong> or <strong>stub</strong> version</p><pre>struct MockProfileService: ProfileServiceProtocol {<br>    func fetchProfile() async throws -&gt; Profile {<br>        return Profile(name: &quot;Test User&quot;)<br>    }<br>}<br><br>func testProfileViewModel() async throws {<br>    let mockService = MockProfileService()<br>    let viewModel = ProfileViewModel(service: mockService)<br>    <br>    let profile = try await viewModel.loadProfile()<br>    XCTAssertEqual(profile.name, &quot;Test User&quot;)<br>}</pre><p>By injecting the mock, you isolate the ProfileViewModel from the network, database, or any other external resource. This makes your tests <strong>deterministic</strong> (they always produce the same result) and <strong>blazing fast</strong>, allowing you to run your entire test suite in seconds.</p><h4>DI and Scalability: Build a Modular System</h4><p>As your app grows, you’ll have dozens of services:<br> AuthService, PaymentService, AnalyticsService, etc.</p><p>Instead of creating them everywhere, you define contracts (protocols) and inject implementations where needed.</p><p>With DI, all dependency creation is centralized to a single point, often called the <strong>Composition Root</strong> or a <strong>DI Container</strong>. Need to update how your logger is initialized? You change it in <em>one</em> place. This makes refactoring easier and dramatically reduces the chance of introducing bugs.</p><pre>final class AppContainer {<br>    lazy var authService: AuthServiceProtocol = AuthService()<br>    lazy var profileService: ProfileServiceProtocol = ProfileService()<br>    <br>    func makeProfileViewModel() -&gt; ProfileViewModel {<br>        ProfileViewModel(service: profileService)<br>    }<br>}</pre><p>Now, your app has a <strong>single source of truth</strong> for dependencies.</p><p>Dependency Injection is the cornerstone of a scalable architecture because it promotes <strong>Decoupling</strong> and adheres to the <strong>SOLID principles.</strong></p><p>By depending on protocols (abstractions) instead of concrete classes, you are following the <strong>Dependency Inversion Principle (DIP), </strong>the ‘D’ in SOLID.</p><p>In a large, modular project, this means:</p><ul><li>A high-level component (like a View Model) doesn’t need to know the implementation details of a low-level component (like a Network Client).</li><li>You can completely replace your third-party networking library (e.g., move from URLSession to a custom-built one) by simply creating a new class that conforms to the existing APIServiceProtocol. You don&#39;t have to touch a single line of code in the view model.</li></ul><h4>Ways to Do Dependency Injection in Swift</h4><p>There are multiple strategies you can use depending on project size:</p><h4>1. Initializer Injection (most common)</h4><p>Pass dependencies via the initializer.</p><pre>final class LoginViewModel {<br>    private let authService: AuthServiceProtocol<br>    <br>    init(authService: AuthServiceProtocol) {<br>        self.authService = authService<br>    }<br>}</pre><h4>2. Property Injection</h4><p>Set dependencies after initialization.</p><pre>class SettingsViewModel {<br>    var analytics: AnalyticsProtocol?<br>}</pre><p>Useful but riskier, since properties might remain nil.</p><h4>3. <strong>Environment Injection (SwiftUI)</strong></h4><p>SwiftUI has built-in support for dependency injection using @Environment and @EnvironmentObject.</p><pre>struct ProfileView: View {<br>    @Environment(\.profileService) private var service<br>}</pre><h4>When to Use DI</h4><ul><li>When writing <strong>unit tests</strong>.</li><li>When designing <strong>modular, scalable code</strong>.</li><li>When you want to <strong>swap implementations</strong> easily (e.g., different environments).</li></ul><p>But don’t over-engineer. For small apps, direct instantiation might be fine. DI shines as your project scales.</p><h4>At the end,</h4><p>Dependency Injection may feel like extra work at first, but it pays off big time when your project grows. It keeps your code <strong>clean, testable, and flexible</strong>, and makes onboarding new developers easier.</p><p>If you’re working on a long-lived iOS app (especially in SwiftUI or MVVM), DI is not just helpful, it’s essential.</p><p>Next time you’re about to write let service = Service(), stop and ask:<br> <em>“Should I inject this instead?”</em></p><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beef93268dce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Code War: I Tested Gemini and GPT-5 Inside Xcode Intelligence. One Was Clearly Superior.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@somasharma95/ai-code-war-i-tested-gemini-and-gpt-5-inside-xcode-intelligence-one-was-clearly-superior-a4d8aa50c3f7?source=rss-8424faeb04c2------2"><img src="https://cdn-images-1.medium.com/max/1600/1*4-jKrvGZJwDe4cauhTYQNQ.jpeg" width="1600"></a></p><p class="medium-feed-snippet">The battle for AI supremacy isn&#x2019;t just about chatbots, it&#x2019;s about practical, real-world creation. As developers, we want to know which AI&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@somasharma95/ai-code-war-i-tested-gemini-and-gpt-5-inside-xcode-intelligence-one-was-clearly-superior-a4d8aa50c3f7?source=rss-8424faeb04c2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@somasharma95/ai-code-war-i-tested-gemini-and-gpt-5-inside-xcode-intelligence-one-was-clearly-superior-a4d8aa50c3f7?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4d8aa50c3f7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gpt-5]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[xcodeintelligence]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 16:36:37 GMT</pubDate>
            <atom:updated>2025-09-29T16:44:30.849Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Realm Without the Crashes: Detaching Objects for a Safer, Faster App]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@somasharma95/realm-without-the-crashes-detaching-objects-for-a-safer-faster-app-fdae54fd6940?source=rss-8424faeb04c2------2"><img src="https://cdn-images-1.medium.com/max/2600/1*0RXnqeIE_KMeN9gOIn4fIw.jpeg" width="3839"></a></p><p class="medium-feed-snippet">Realm is one of the most popular local databases for iOS. Its biggest selling point is that objects are live: once you query them, they&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@somasharma95/realm-without-the-crashes-detaching-objects-for-a-safer-faster-app-fdae54fd6940?source=rss-8424faeb04c2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@somasharma95/realm-without-the-crashes-detaching-objects-for-a-safer-faster-app-fdae54fd6940?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdae54fd6940</guid>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[realmswift]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 09:47:03 GMT</pubDate>
            <atom:updated>2025-09-05T10:02:01.284Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[When to Use Class vs Struct vs Actor in Swift]]></title>
            <link>https://medium.com/@somasharma95/when-to-use-class-vs-struct-vs-actor-in-swift-c2da8b5791be?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2da8b5791be</guid>
            <category><![CDATA[actors]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[struct]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 10:03:34 GMT</pubDate>
            <atom:updated>2025-08-21T10:43:46.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uD8B1OveVfKTr1DXzgfbIQ.jpeg" /></figure><p>Swift is designed with clarity, safety, and performance in mind. One of the most common questions us developers face is.</p><p>Should I use a struct, a class, or an actor?</p><p>At first, these might feel interchangeable, but choosing the right one can make your code <strong>simpler, safer, and more efficient</strong>. In this article, we’ll break down when to use each, why SwiftUI leans heavily on struct, and how actors fit into modern Swift concurrency.</p><h4>Structs: The Default Choice-</h4><p>In Swift, struct should be your <strong>go-to type</strong>. They’re <strong>value types</strong>, which means they are <strong>copied</strong> when assigned or passed around. This eliminates accidental shared state, making them naturally safer in multi-threaded code.</p><p>You must have seen how SwiftUI takes full advantage of structs and almost every view you write is a struct.</p><p>When to use Struct:</p><ul><li><strong>SwiftUI Views</strong>: Every SwiftUI view is a struct, making them lightweight and disposable.</li><li><strong>Models</strong>: If your data is small and copyable. Example: a User or Message.</li><li><strong>State containers</strong>: With property wrappers like @State, @Binding, @AppStorage.</li></ul><pre>struct User {<br>    let id: UUID<br>    var name: String<br>}<br><br>struct UserProfileView: View {<br>    let user: User<br>    <br>    var body: some View {<br>        Text(&quot;Hello, \(user.name)!&quot;)<br>    }<br>}</pre><p>When not to use struct:</p><ul><li>If you have to work with large, mutable data that gets copied often.</li><li>If you have to share state across multiple owners.</li></ul><h4>Classes: Identity and Shared State-</h4><p>Sometimes you need more than just data, you need <strong>identity</strong>. Unlike structs, class is a <strong>reference type</strong>, so multiple variables can point to the same instance.</p><p>This makes classes ideal for shared state and observing changes across multiple views.</p><p>When to use a class:</p><ul><li><strong>Observable Objects in SwiftUI</strong>: Classes conforming to ObservableObject let SwiftUI automatically re-render when data changes.</li><li><strong>Managers and Services</strong>: Networking, database, audio, etc.</li><li><strong>UIKit / AppKit </strong>: Many Apple APIs require classes.</li></ul><pre>final class UserManager: ObservableObject {<br>    @Published var currentUser: User?<br>    <br>    func login(name: String) {<br>        self.currentUser = User(id: UUID(), name: name)<br>    }<br>}</pre><p>While using classes be careful with:</p><ul><li>Reference cycles (weak/unowned often needed).</li><li>Thread safety: two threads can mutate the same class instance at once.</li><li>Manual locks/queues might be needed for concurrency.</li></ul><h4>Actors: Concurrency-Safe Classes-</h4><p>With Swift 5.5, Apple introduced actor, a <strong>reference type with built-in data isolation</strong>. Think of it like a class, but only one task can touch its mutable state at a time. This eliminates a huge source of bugs like data races.</p><p>When to use an actor:</p><ul><li><strong>Shared mutable state across tasks</strong>: Caches, sessions, stores.</li><li><strong>Thread-safe services</strong>: Logging, analytics, download managers</li><li><strong>Anywhere you’d normally use a class with manual locks/queues</strong>.</li></ul><pre>actor ImageCache {<br>    private var cache: [URL: UIImage] = [:]<br>    <br>    func image(for url: URL) -&gt; UIImage? {<br>        cache[url]<br>    }<br>    <br>    func insert(_ image: UIImage, for url: URL) {<br>        cache[url] = image<br>    }<br>}</pre><p>Why Not Use Actors for Everything?:</p><p>Because you’d be paying unnecessary costs for things that don’t need isolation.</p><ul><li><strong>Lightweight models</strong>: Structs are faster, cheaper, and easier to use. Making them actors introduces unnecessary async/await ceremony and hop overhead.</li><li><strong>Immutable state</strong>: If your data never changes, there’s no point in an actor.</li></ul><p>So the rule of thumb is:</p><ul><li>Use <strong>structs</strong> for simple models.</li><li>Use <strong>actors</strong> only for <strong>shared mutable state that needs to be concurrency-safe</strong>.</li></ul><p>The Cost of Actor Hops:</p><p>Although in this article we aren&#39;t going that deep for structs and classes but i feel this is important to know for anyone using actors.</p><p>When you call a method or access a property on an actor, Swift ensures that only one task is touching its mutable state at a time. To enforce this, Swift sometimes has to perform what’s called an <strong>actor hop</strong>.</p><p>An <strong>actor hop</strong> means:</p><ul><li>The runtime checks “who owns this piece of data right now?”</li><li>If you’re outside the actor, your call must be scheduled <strong>into the actor’s queue</strong> (like a serial executor).</li><li>This scheduling isn’t free and it adds a small but real overhead.</li></ul><p>When Actor Hops Matter</p><ul><li><strong>Fine-grained, high-frequency operations</strong>: If you’re calling tiny methods (like incrementing a number) millions of times per second, actor hops will add up.</li><li><strong>Low-latency scenarios</strong>: Real-time graphics or audio processing often can’t afford actor hop overhead.</li><li><strong>Tight loops</strong>: If every loop iteration does an await actor.method(), performance drops compared to batching.</li></ul><p>For instance, inserting 10,000 items into an actor-backed cache <em>one by one</em> will be slower than batching them in a single method.</p><p>When They Don’t Matter</p><ul><li><strong>Most app code</strong>: UI updates, network responses, and user interactions are slow relative to an actor hop.</li><li><strong>Service-level code</strong>: A logger, analytics collector, or download manager benefits more from safety than raw micro-optimizations.</li></ul><p>A Real-World Example:</p><p>In my recent work on a professional events app, I had a case where multiple parts of the system needed to update <strong>attendee details for generating a badge</strong>. Since that data was shared, I didn’t want two different objects trying to modify it at the same time and risk inconsistencies.</p><p>This was a perfect use case for an <strong>actor</strong>. By isolating the update logic inside an actor, I ensured that only one task could modify attendee details at any given moment. The result: <strong>no race conditions, no corrupted data, and much simpler code compared to locks or queues</strong>.</p><p>This experience reinforced for me why Swift introduced actors: they give us <strong>class-like flexibility with concurrency safety built in</strong>.</p><h4>What i think at the end:</h4><p>Swift gives us three powerful tools <strong>structs, classes, and actors, </strong>each with its own benefits.</p><ul><li><strong>Structs</strong> should be your default choice. They’re lightweight, safe by design, and align perfectly with SwiftUI’s declarative model. Their value semantics make code easier to reason about and naturally thread-safe.</li><li><strong>Classes</strong> step in when you need identity, shared mutable state, or interoperability with Apple frameworks. They power SwiftUI’s ObservableObject model and remain essential for reference-based designs.</li><li><strong>Actors</strong> bring modern concurrency safety to reference types. They’re perfect for shared resources that multiple tasks might access at once, removing the need for manual locking.</li></ul><p>The key is balance:</p><ul><li>Start with <strong>structs</strong> whenever possible.</li><li>Reach for <strong>classes</strong> when shared state or reference semantics are required.</li><li>Introduce <strong>actors</strong> when concurrency makes data safety a concern.</li></ul><p>A well-structured SwiftUI app will often use all three, each where it makes the most sense. By understanding their strengths and trade-offs, you can write code that’s not only safer and faster but also easier to maintain and reason about.</p><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2da8b5791be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a To-Do List App in Under 5 Minutes with Cursor (Step-by-Step)]]></title>
            <link>https://medium.com/@somasharma95/create-a-to-do-list-app-in-under-5-minutes-with-cursor-step-by-step-44bb4056e40b?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/44bb4056e40b</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 10:14:05 GMT</pubDate>
            <atom:updated>2025-07-06T10:14:05.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrTP5x4xsUjXTyBUgzzlRg.jpeg" /></figure><p>I’ve been curious about the power of <strong>AI + developer tools</strong> for a while now, specially when it comes to speeding up everyday tasks like building UI. Recently, I gave <strong>Cursor</strong> a try on my Mac and I was shocked.</p><p>To test it, I created a simple <strong>To-Do List app</strong> something that would usually take 20–30 minutes in SwiftUI. But with Cursor, it took <strong>under 5 minutes</strong>, and the best part? I could see <strong>live changes instantly reflected in Xcode</strong> and run the app <strong>simultaneously in the simulator</strong> no switching back and forth, no guesswork.</p><p>Let me take you to a 5 minutes journey of how to use it.</p><h4>Step 1: Create a Basic Xcode Project</h4><p>Let’s start with a blank SwiftUI project:</p><ol><li>Open <strong>Xcode &gt; File &gt; New &gt; Project</strong></li><li>Choose <strong>App</strong></li><li>Name it TodoApp</li><li>Interface: <strong>SwiftUI</strong>, Language: <strong>Swift</strong></li><li>Save it anywhere on your Mac</li></ol><p>This creates a standard SwiftUI project with ContentView.swift and TodoApp.swift.</p><h4>Step 2: Open the Project in Cursor</h4><ol><li>Launch <strong>Cursor.app</strong> on your Mac</li><li>Click <strong>“Open Project”</strong> and select the folder containing your TodoApp.xcodeproj</li><li>Cursor loads your project structure into a visual editor ready for prompts</li></ol><p>Now comes the fun part.</p><h4>Step 3: Let AI Build the To-Do Screen for You</h4><p>Instead of dragging UI components or writing boilerplate, just type this in the prompt bar inside Cursor:</p><blockquote>“Build a to-do screen with a list of tasks, each with a title and a done toggle. Add a button to create new tasks. Save data locally.”</blockquote><p>Cursor will automatically:</p><ul><li>Create a TodoItem model with title and isDone</li><li>Build a SwiftUI screen with a dynamic list</li><li>Add local persistence</li><li>Generate clean Swift code in your project structure</li></ul><p>For me it created below code and it also asks me if i accept it or not</p><pre>//<br>//  ContentView.swift<br>//  TODO<br>//<br>//  Created by soma sharma on 05/07/25.<br>//<br><br>import SwiftUI<br><br>struct Task: Identifiable, Codable {<br>    let id = UUID()<br>    let title: String<br>    var isDone: Bool<br>    <br>    init(title: String, isDone: Bool = false) {<br>        self.title = title<br>        self.isDone = isDone<br>    }<br>}<br><br>struct ContentView: View {<br>    @State private var tasks: [Task] = []<br>    @State private var newTask: String = &quot;&quot;<br>    <br>    var body: some View {<br>        NavigationView {<br>            VStack {<br>                HStack {<br>                    TextField(&quot;Enter new task&quot;, text: $newTask)<br>                        .textFieldStyle(RoundedBorderTextFieldStyle())<br>                    Button(action: addTask) {<br>                        Image(systemName: &quot;plus&quot;)<br>                            .foregroundColor(.blue)<br>                    }<br>                    .disabled(newTask.trimmingCharacters(in: .whitespaces).isEmpty)<br>                }<br>                .padding()<br>                <br>                List {<br>                    ForEach(tasks) { task in<br>                        HStack {<br>                            Button(action: {<br>                                toggleTask(task)<br>                            }) {<br>                                Image(systemName: task.isDone ? &quot;checkmark.circle.fill&quot; : &quot;circle&quot;)<br>                                    .foregroundColor(task.isDone ? .green : .gray)<br>                                    .font(.title2)<br>                            }<br>                            .buttonStyle(PlainButtonStyle())<br>                            <br>                            Text(task.title)<br>                                .strikethrough(task.isDone)<br>                                .foregroundColor(task.isDone ? .gray : .primary)<br>                            <br>                            Spacer()<br>                        }<br>                        .padding(.vertical, 4)<br>                    }<br>                    .onDelete(perform: deleteTasks)<br>                }<br>            }<br>            .navigationTitle(&quot;TODO List&quot;)<br>            .onAppear(perform: loadTasks)<br>        }<br>    }<br>    <br>    private func addTask() {<br>        let trimmed = newTask.trimmingCharacters(in: .whitespaces)<br>        guard !trimmed.isEmpty else { return }<br>        tasks.append(Task(title: trimmed))<br>        newTask = &quot;&quot;<br>        saveTasks()<br>    }<br>    <br>    private func toggleTask(_ task: Task) {<br>        if let index = tasks.firstIndex(where: { $0.id == task.id }) {<br>            tasks[index].isDone.toggle()<br>            saveTasks()<br>        }<br>    }<br>    <br>    private func deleteTasks(offsets: IndexSet) {<br>        tasks.remove(atOffsets: offsets)<br>        saveTasks()<br>    }<br>    <br>    private func saveTasks() {<br>        if let encoded = try? JSONEncoder().encode(tasks) {<br>            UserDefaults.standard.set(encoded, forKey: &quot;SavedTasks&quot;)<br>        }<br>    }<br>    <br>    private func loadTasks() {<br>        if let data = UserDefaults.standard.data(forKey: &quot;SavedTasks&quot;),<br>           let decoded = try? JSONDecoder().decode([Task].self, from: data) {<br>            tasks = decoded<br>        }<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><h4>Step 4: Watch Xcode Update Instantly</h4><p>As Cursor builds the UI and logic:</p><ul><li>Your <strong>Swift files update in real-time in Xcode</strong></li><li>You can <strong>run the app in the simulator immediately</strong></li><li>Any edits made via prompts or Cursor’s UI reflect in your project instantly</li></ul><p>This live integration completely eliminates the old dev loop of <em>edit → build → test → repeat</em>. Now, it’s all simultaneous.</p><p>Here is the final result</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ff2iWqLOemSpgi2CzHf%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ff2iWqLOemSpgi2CzHf&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExc2h2aXF2M2NwbDBvOWFxbGVkM2I1M250cWp2a3IwdTFzYzczM3h2MCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Ff2iWqLOemSpgi2CzHf%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/68296f5611897e76e487fa79446f3f1c/href">https://medium.com/media/68296f5611897e76e487fa79446f3f1c/href</a></iframe><h4>What You’ve Just Built (In 5 Minutes)</h4><ul><li>A functional <strong>to-do list app</strong></li><li>Task creation and completion toggles</li><li>Data stored <strong>locally and persistently</strong></li><li>A clean SwiftUI codebase, production-ready</li></ul><h3>If you want to modify more or just want to play with it.</h3><p>You can continue refining your app by prompting Cursor:</p><ul><li><em>“Group completed and incomplete tasks into sections”</em></li><li><em>Add swipe to delete for tasks”</em></li><li><em>“Add a title at the top saying ‘My Tasks’”</em></li><li><em>“Support dark mode styling”</em></li></ul><p>Cursor updates the UI and code instantly, and you can see the changes live in your running app.</p><h4>What I think at the end:</h4><p>Well, I’ll be honest. I do find this a bit scary. But at this point, it’s incredibly useful for <strong>quick prototypes</strong>, <strong>reviewing your own code</strong>, or even <strong>generating boilerplate for unit testing</strong>. It’s like having a supercharged assistant that helps you move faster without giving up control. If you’re a Swift developer, this is absolutely worth trying.</p><p>Let me know what you build next and maybe we can discuss more.</p><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44bb4056e40b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI WebView Guide: Native Web Embedding Made Easy]]></title>
            <link>https://medium.com/@somasharma95/swiftui-webview-guide-native-web-embedding-made-easy-a3dd222940c3?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3dd222940c3</guid>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[webkit]]></category>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Wed, 18 Jun 2025 18:56:03 GMT</pubDate>
            <atom:updated>2025-06-18T18:59:13.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3kHfjdkJGFgSHTkMdPipQ.jpeg" /></figure><p>First of all I really waited for this update. With every new release, SwiftUI continues to close the gap between UIKit and modern declarative UI development. One area where developers have long relied on UIKit interoperability is WebView. In this article, we’ll explore how Apple has improved WebView support in SwiftUI making it easier and cleaner to embed web content natively.</p><h3>The Old Way: Wrapping WKWebView</h3><p>Before iOS 26, SwiftUI had no native WebView support. Developers had to bridge UIKit’s WKWebView using UIViewRepresentable, which introduced boilerplate code and maintenance challenges.</p><pre>import SwiftUI<br>import WebKit<br><br>struct LegacyWebView: UIViewRepresentable {<br>    let url: URL<br><br>    func makeUIView(context: Context) -&gt; WKWebView {<br>        return WKWebView()<br>    }<br><br>    func updateUIView(_ uiView: WKWebView, context: Context) {<br>        let request = URLRequest(url: url)<br>        uiView.load(request)<br>    }<br>}</pre><p>While this worked, it didn’t feel very SwiftUI native.</p><h3>The New Way: Native WebView in SwiftUI (iOS 26+)</h3><p>Apple introduced native WebView support in SwiftUI starting with iOS 26. This drastically simplifies embedding web content.</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>private var url: URL? {<br>        URL(string: &quot;https://www.swift.org&quot;)<br>    }<br>    var body: some View {<br>        WebView(url: url)<br>    }<br>}</pre><p>No more UIViewRepresentable, no more bridging headaches. It just works.</p><h3>Advanced Features:</h3><h4>Injecting JavaScript</h4><p>You can now inject JavaScript directly into your WebView with ease:</p><pre>webView.evaluateJavaScript(&quot;document.body.style.backgroundColor = &#39;lightgray&#39;;&quot;)</pre><h4>Navigation Controls</h4><p>SwiftUI’s WebView allows interaction with navigation events, such as detecting when a page starts loading or handling redirects.</p><pre>WebView(url: url)<br>    .onNavigationAction { action in<br>        switch action {<br>        case .linkActivated(let url):<br>            print(&quot;User tapped on a link: \(url)&quot;)<br>        default:<br>            break<br>        }<br>    }</pre><h4>Local HTML and File Loading</h4><p>You can still load local HTML strings and files:</p><pre>WebView(html: &quot;&lt;h1&gt;Hello SwiftUI WebView!&lt;/h1&gt;&quot;)</pre><p>Or load from a bundle:</p><pre>if let path = Bundle.main.path(forResource: &quot;index&quot;, ofType: &quot;html&quot;) {<br>    let url = URL(fileURLWithPath: path)<br>    WebView(url: url)<br>}</pre><h3>Performance and Security</h3><ul><li>SwiftUI’s WebView uses the same under the hood WKWebView engine.</li><li>Benefits include better memory management, support for cookies, cache, and storage.</li><li>JavaScript execution is sandboxed and follows WebKit’s latest policies from iOS 26.</li></ul><h4>So…</h4><p>Most importantly, it helps eliminate reliance on UIViewRepresentable and scattered delegate patterns that often clutter SwiftUI codebases. Instead of juggling multiple WKNavigationDelegate callbacks to handle forward/backward navigation or JavaScript messages, everything is now declarative and composable.</p><p>By removing the need for UIKit bridging, it empowers developers to embed rich web content with minimal code and maximum clarity. I just love it and cant wait to use it in real world applications.</p><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3dd222940c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift Concurrency (Part 2): Actors, MainActor, and Sendable Explained]]></title>
            <link>https://medium.com/@somasharma95/mastering-swift-concurrency-part-2-actors-mainactor-and-sendable-explained-788150a3c8da?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/788150a3c8da</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 19:00:57 GMT</pubDate>
            <atom:updated>2025-06-05T19:01:42.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYYTIOetHgHlNSJOU4kDAg.jpeg" /></figure><p>In Part One, we covered the basics async/await, Task, and TaskGroup. Now let’s dive into how Swift handles concurrency <strong>safely</strong> when shared state and thread confinement come into play.</p><p>In this part, we’ll explore:</p><ul><li>What is an actor and when to use it</li><li>How MainActor keeps your UI safe</li><li>What Sendable means in Swift Concurrency and why it matters</li></ul><h4>Understanding Tasks and Why We Need Actors:</h4><p>When you’re working with <strong>Swift Concurrency</strong>, you often split your work into <strong>Tasks</strong>. Each task is like a mini thread of work running on its own for e.g. fetching data, processing input, storing data, etc.</p><p>Now here’s the catch:</p><p><strong>Tasks are isolated.</strong><br> They don’t share data with each other by default. This is intentional and it’s what makes concurrency safe and avoids weird bugs like data races.</p><p>But sometimes, you do want to share some state between tasks. For example:</p><ul><li>Tracking shared progress</li><li>Updating a shared cache</li><li>Logging or collecting results</li></ul><p>That’s where <strong>Actors</strong> come in.</p><h4>What is an Actor?</h4><p>An actor is like a special kind of class that <strong>protects its internal state</strong> from being accessed by multiple tasks at the same time. You can think of it like a <strong>synchronized room </strong>where only one task is allowed inside to read or modify the state at any given time.</p><p>This prevents bugs like:</p><ul><li>Two tasks modifying the same variable at once</li><li>Reading a value while another task is changing it</li></ul><p>Lets understand it through a real world example</p><p>Let’s say you’re building a shopping app where different parts of the code like maybe a SwiftUI view, a background sync process, or even live updates from a server can modify the user’s shopping cart at the same time.</p><p>This can quickly lead to <strong>data races</strong> if multiple tasks try to update the cart concurrently. That’s where actors come in.</p><p>Here’s a simple ShoppingCart actor that manages items in a thread-safe way:</p><pre>actor ShoppingCart {<br>    private var items: [String: Int] = [:]<br><br>    func addItem(_ item: String, quantity: Int = 1) {<br>        items[item, default: 0] += quantity<br>    }<br><br>    func removeItem(_ item: String) {<br>        items.removeValue(forKey: item)<br>    }<br><br>    func totalItems() -&gt; Int {<br>        items.values.reduce(0, +)<br>    }<br>}</pre><p>Now you can use it like</p><pre>let cart = ShoppingCart()<br><br>Task {<br>    await cart.addItem(&quot;Apple&quot;)<br>}<br><br>Task {<br>    await cart.addItem(&quot;Banana&quot;, quantity: 3)<br>}<br><br>Task {<br>    let total = await cart.totalItems()<br>    print(&quot;Cart contains \(total) items.&quot;)<br>}</pre><h4>How It Works</h4><ul><li>The actor guarantees that only one task at a time can access or modify its internal state (items dictionary).</li><li>Even if multiple tasks try to call addItem, removeItem, or totalItems() at the same time, Swift automatically queues those accesses.</li><li>This avoids data corruption without requiring locks or DispatchQueues.</li><li>Each await ensures that the actor is accessed in a safe, sequential manner even though the Task blocks are running concurrently. This is the power of <strong>actor isolation</strong>.</li></ul><h4>But what exactly is Actor Isolation</h4><p>When you define an actor, its internal mutable state like items is isolated to the actor instance. Only one task can interact with it at a time. Swift enforces this for you.</p><p>You can think of it like this:</p><ul><li>Imagine the actor as a private office.</li><li>Only one task is allowed inside the office at a time to work with the data.</li><li>Others wait politely in line (the queue) until it’s their turn.</li></ul><p>This model ensures thread safety without the headache of semaphores, locks, or race conditions.</p><h4>Few more things to remember before we move to next section of this article:</h4><ul><li>Actors are <strong>reference types</strong>, just like classes.</li><li>You can call their methods using await, even from Task blocks or other async functions.</li><li>You <strong>cannot</strong> access their mutable properties directly from outside because that would break isolation.</li></ul><h4>Understanding MainActor: Keeping UI Code Safe:</h4><p>When building iOS apps, you often need to update the UI based on async work like displaying fetched data, showing loading states, or updating form inputs. But UIKit and SwiftUI require that all UI updates happen on the <strong>main thread</strong>.</p><p>That’s where MainActor comes in.</p><h4>What is MainActor?</h4><p>MainActor is a special global actor provided by Swift. It ensures that any code running on it is executed on the <strong>main thread</strong>, which is required for anything that touches the UI.</p><p>You can think of it as a <strong>structured and type-safe replacement for </strong><strong>DispatchQueue.main.async {}</strong>.</p><h4>Why Do We Need It?</h4><p>Let’s say you fetch data in the background and want to update a label:</p><pre>Task {<br>    let data = await fetchUserData()<br>    label.text = data.name // This will crash if not on main thread<br>}</pre><p>To fix it safely:</p><pre>Task {<br>    let data = await fetchUserData()<br>    <br>    await MainActor.run {<br>        label.text = data.name // Now runs on the main thread<br>    }<br>}</pre><p>You can mark an entire method or property to always run on the main thread using the @MainActor annotation:</p><pre>@MainActor<br>func updateUI(with data: User) {<br>    label.text = data.name<br>}</pre><p>Or on a whole class or struct (like a ViewModel):</p><pre>@MainActor<br>class ProfileViewModel: ObservableObject {<br>    @Published var name: String = &quot;&quot;<br><br>    func loadProfile() async {<br>        let user = await fetchUser()<br>        name = user.name //already on MainActor<br>    }<br>}</pre><p>SwiftUI automatically runs most of your view updates on the main thread. But if you’re doing async work inside a ViewModel, @MainActor ensures that all published properties are safely updated.</p><p>Without MainActor, You Might See:</p><ul><li>Crashes: Modifying state from background thread</li><li>UI not updating</li><li>Hard-to-find bugs in SwiftUI previews</li><li>Don’t overuse it for background work like network calls, JSON parsing, or heavy processing <strong>should not</strong> happen on the main thread.</li></ul><p>If you are still here and reading this article then let me also talk about Sendable with you.</p><h4>Sendable: Ensuring Safe Data Across Concurrency Domains:</h4><p>In Swift’s new concurrency model, values often move between different threads or tasks. That can be dangerous if those values contain mutable state that might be changed simultaneously.</p><p>To help the compiler prevent data races, Swift uses a protocol called Sendable.</p><h4>What is Sendable?</h4><p>Sendable is a marker protocol that tells the compiler: <strong>It’s safe to pass this value across concurrency boundaries.</strong></p><p>Types that conform to Sendable guarantee:</p><ul><li>No shared mutable state.</li><li>No unexpected mutations when accessed from multiple tasks.</li></ul><h4>Common Sendable Types:</h4><p>Swift’s standard library types like Int, String, Array, Dictionary, etc., are all Sendable.</p><p>Structs composed entirely of Sendable properties are <strong>automatically</strong> Sendable.</p><p>Example:</p><pre>struct User: Sendable {<br>    let name: String<br>    let age: Int<br>}</pre><p>In fact, it is still Sendable even if you don’t explicitly write Sendable, as long as all of its stored properties are Sendable and the compiler is able to synthesize conformance.</p><h4>What Happens If a Type Is Not Sendable?</h4><p>If you pass a non-Sendable type across a concurrency boundary (e.g., into a Task, TaskGroup, or actor), Swift will warn mostly stating you are using non sendable inside sendable closure.</p><p>Example:</p><pre>class SomeClass {<br>    var value = 0<br>}<br><br>func doAsyncWork(obj: SomeClass) async {<br>    await Task {<br>        print(obj.value) // Warning: &#39;SomeClass&#39; is not Sendable<br>    }<br>}</pre><p>To fix this, either:</p><ul><li>Refactor to a value type (struct)</li><li>Protect the access using an actor</li><li>Or explicitly mark conformance (only if you’re sure it’s safe):</li></ul><pre>final class SomeClass: @unchecked Sendable {<br>    var value = 0<br>}</pre><p>Use @unchecked Sendable <strong>with caution, </strong>you&#39;re telling the compiler. that trust me, I know it&#39;s safe. That shifts responsibility from the compiler to you.</p><h4>When to Think About Sendable</h4><p>You don’t always need to declare types as Sendable, but be aware of it when:</p><ul><li>Passing values into concurrent contexts (e.g. Task, TaskGroup)</li><li>Sharing values across threads or between actors</li><li>Building libraries that use concurrency internally</li></ul><p>With Swift 6 and strict concurrency enabled, the compiler will guide you with warnings and errors if Sendable conformance is needed.</p><h3>Wrapping Up: Concurrency with Confidence</h3><p>In this second part of our Swift Concurrency series, we dove deeper into how Swift helps you <strong>safely share data across tasks and threads</strong> using:</p><ul><li>How <strong>actors</strong> protect mutable state with isolation</li><li>How @MainActor helps keep UI updates thread-safe</li><li>Why Sendable matters for safe cross-task data sharing</li></ul><p>Together, these tools form the foundation of Swift’s <strong>modern, structured, and safe</strong> approach to concurrency.</p><p>As you continue building more complex features, understanding these patterns will help you write <strong>cleaner, more reliable, and race-free</strong> code.</p><p>Let me know in comments if you want me to cover <strong>actor reentrancy</strong>, <strong>custom global actors</strong>, and <strong>advanced patterns</strong> with concurrency.</p><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788150a3c8da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Swift Concurrency: A Practical Guide]]></title>
            <link>https://medium.com/@somasharma95/mastering-swift-concurrency-a-practical-guide-198e01f62d69?source=rss-8424faeb04c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/198e01f62d69</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-concurrency]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Soma Sharma]]></dc:creator>
            <pubDate>Thu, 29 May 2025 16:00:20 GMT</pubDate>
            <atom:updated>2025-06-07T19:06:36.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdbieOV3_Nt4AJwuhU4zgg.jpeg" /></figure><p>Concurrency has always been key to making apps feel fast and responsive. Whether you’re fetching data from a server, processing images, or just handling user interactions smoothly, you need a way to do work in the background without freezing the main thread.</p><p>For the longest time, we’ve used tools like <strong>Grand Central Dispatch (GCD)</strong> and <strong>OperationQueue</strong> in Swift. They’re powerful, but let’s be honest they can also be clunky and error-prone. Managing thread safety, juggling completion handlers, and keeping things clean? Not always fun.</p><p>Thankfully, with Swift 5.5 and beyond, Apple gave us a much better way forward: <strong>structured concurrency</strong>. It brings async/await, Task, and Actor to the table making async code cleaner, safer, and easier to reason about.</p><p>In this article, we’ll explore Swift Concurrency in depth and show how to apply it in real-world apps.</p><h3>Core Concepts Of Swift Concurrency</h3><p>Before diving into code, let’s define the core building blocks of Swift Concurrency:</p><ul><li><strong>async / </strong><strong>await</strong> – Asynchronous functions that suspend execution until a result is ready.</li><li><strong>Task</strong> – A unit of asynchronous work.</li><li><strong>Structured concurrency</strong> — Tasks are scoped to the context they were created in, making it easier to manage lifecycles and cancellations.</li><li><strong>Actor</strong> – A reference type that protects its mutable state from data races.</li><li><strong>MainActor</strong> – A global actor used to guarantee code runs on the main thread.</li></ul><p>These constructs allow you to write concurrent code that reads like synchronous code while avoiding common bugs.</p><h3>Getting Started with async/await</h3><p>Let’s begin by transforming a traditional closure-based API into Swift’s modern async/await syntax.</p><p>Old style (completion handler):</p><pre>func fetchData(from url: URL, completion: @escaping (Data?, Error?) -&gt; Void) {<br>    URLSession.shared.dataTask(with: url) { data, _, error in<br>        completion(data, error)<br>    }.resume()<br>}</pre><p>New style (async/await):</p><pre>func fetchData(from url: URL) async throws -&gt; Data {<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return data<br>}</pre><p>Usage becomes cleaner and more readable:</p><pre>Task {<br>    do {<br>        let data = try await fetchData(from: someURL)<br>        // Handle data<br>    } catch {<br>        // Handle error<br>    }<br>}</pre><p>If you are already inside an async func then you might not need task and can write code like this.</p><pre>func loadUserProfile() async {<br>    do {<br>        let data = try await fetchData(from: someURL)<br>        // Use the data<br>    } catch {<br>        // Handle error<br>    }<br>}</pre><p>If you’re in a synchronous context (e.g., a SwiftUI .onAppear, a UIButton target, or a normal function), then you must create a task to call async code.</p><h4>But Why?</h4><p>async functions can only be called from other async functions or inside a Task {} block. That’s part of Swift’s structured concurrency model, ensuring async code is handled in a safe and controlled way.</p><h3>Working with Task</h3><p>Now that you already know from above that task is useful when you’re outside of an async context like in a button action or View.onAppear. Lets learn more about it in detail.</p><h4>Does Task Run in the Background?</h4><p>Not always.</p><p>When you write:</p><pre>Task {<br>    await doWork()<br>}</pre><p>Swift creates a <strong>child task</strong> in the cooperative thread pool, most likely not on the main thread, but <strong>it depends</strong>.</p><p>If you want to <strong>explicitly opt out of parent context</strong> (e.g. from a SwiftUI view), use:</p><pre>Task.detached(priority: .background) {<br>    await doHeavyWork()<br>}</pre><ul><li>Task inherits the surrounding task context.</li><li>Task.detached runs in its own context and can run truly independently (e.g. in a global background thread).</li></ul><h4>Task Cancellation</h4><p>Swift uses <strong>cooperative cancellation, </strong>tasks periodically check if they’ve been canceled, and exit gracefully if so.</p><p>You can cancel tasks with:</p><pre>task.cancel()</pre><p>And inside a task, respond to cancellation using either:</p><pre> guard !Task.isCancelled else { return nil }</pre><p>you can also use it with a cancellation handler, in case you need immediate notification of cancellation</p><pre>let task = await Task.withTaskCancellationHandler {<br>    // ...<br>} onCancel: {<br>    print(&quot;Canceled!&quot;)<br>}</pre><h3>Concurrent Work with TaskGroup</h3><p>TaskGroup is your tool when you want to launch multiple async operations in parallel and wait for all of them to complete, like fetching multiple images at once.</p><p>Let’s say you have three API calls: fetchUser(), fetchPosts(), and fetchComments(). You want to call them all in parallel and wait for all to finish, just like you&#39;d do with DispatchGroup.</p><pre>func loadAllData() async throws -&gt; APIResponse {<br>    var response = APIResponse()<br><br>    try await withThrowingTaskGroup(of: (String, Any).self) { group in<br>        group.addTask {<br>            let user = try await fetchUser()<br>            return (&quot;user&quot;, user)<br>        }<br><br>        group.addTask {<br>            let posts = try await fetchPosts()<br>            return (&quot;posts&quot;, posts)<br>        }<br><br>        group.addTask {<br>            let comments = try await fetchComments()<br>            return (&quot;comments&quot;, comments)<br>        }<br><br>        for try await (key, value) in group {<br>            switch key {<br>            case &quot;user&quot;:<br>                response.user = value as? String<br>            case &quot;posts&quot;:<br>                response.posts = value as? [String] ?? []<br>            case &quot;comments&quot;:<br>                response.comments = value as? [String] ?? []<br>            default:<br>                break<br>            }<br>        }<br>    }<br><br>    return response<br>}</pre><p>Use it</p><pre>Task {<br>    do {<br>        let result = try await loadAllData()<br>        print(&quot;User:&quot;, result.user ?? &quot;none&quot;)<br>        print(&quot;Posts:&quot;, result.posts)<br>        print(&quot;Comments:&quot;, result.comments)<br>    } catch {<br>        print(&quot;Failed to load data:&quot;, error)<br>    }<br>}</pre><p>If any task in a withThrowingTaskGroup throws an error, <strong>all other tasks are automatically cancelled</strong>, preventing wasted work.</p><p>This makes it great for things like:</p><ul><li>Fetching a set of data where any failure should stop the whole process</li><li>Ensuring cleanup or rollback when one part fails.</li></ul><h4>What if One Task Fails, But You Want Others to Keep Running?</h4><p>By default, withThrowingTaskGroup cancels all remaining tasks as soon as one throws an error. But if you want <strong>all tasks to run to completion, even if some fail</strong>, you can use following approach:</p><h4>Use withTaskGroup Instead of withThrowingTaskGroup</h4><pre>await withTaskGroup(of: (String, Any?).self) { group in<br>    group.addTask {<br>        let user = try? await fetchUser()<br>        return (&quot;user&quot;, user)<br>    }<br><br>    group.addTask {<br>        let posts = try? await fetchPosts()<br>        return (&quot;posts&quot;, posts)<br>    }<br><br>    group.addTask {<br>        let comments = try? await fetchComments() // Will be nil if fails<br>        return (&quot;comments&quot;, comments)<br>    }<br><br>    var response = APIResponse()<br><br>    for await (key, value) in group {<br>        switch key {<br>        case &quot;user&quot;:<br>            response.user = value as? String<br>        case &quot;posts&quot;:<br>            response.posts = value as? [String] ?? []<br>        case &quot;comments&quot;:<br>            response.comments = value as? [String] ?? []<br>        default:<br>            break<br>        }<br>    }<br>  return response<br>}</pre><ul><li>withTaskGroup <strong>does not cancel</strong> other tasks if one throws.</li><li>You manually handle errors inside each task.</li></ul><p><strong>P.S.</strong> I didn’t cover Actor and MainActor in this article to keep things focused and digestible, but they’re super important when it comes to managing shared mutable state safely in Swift Concurrency.</p><p>Thinking of doing a follow-up article just on that. <strong>Drop a comment if you’re interested</strong>, and I’ll make it happen!</p><h3>Conclusion: The Power of Structured Concurrency</h3><p>Swift Concurrency is not just a new syntax but it’s a new mindset.</p><p>Where we once relied on DispatchQueue, completion handlers, and GCD juggling, Swift now empowers us with modern, <strong>structured concurrency </strong>which is clear, readable, and safe. With async/await, we can write asynchronous code that feels synchronous. With Task, we can launch and cancel background work in a Swift-native way. And with TaskGroup, we can run multiple operations concurrently while retaining full control over failure handling and cancellation.</p><h3>What’s Next?</h3><p>With the core concurrency tools under your belt, consider diving deeper into:</p><ul><li>Actors to manage mutable shared state safely</li><li>Using MainActor for UI updates</li><li>Designing cancellable workflows using Task.handle and TaskCancellationHandler</li><li>Adding timeouts, retries, and backoff logic to network requests</li><li>Writing unit tests for async code</li></ul><p><strong>Let’s connect on </strong><a href="http://www.linkedin.com/in/soma-sharma-253a1896"><strong>LinkedIn</strong></a> — always happy to meet fellow developers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=198e01f62d69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>