<?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 Rushikesh Gaikwad on Medium]]></title>
        <description><![CDATA[Stories by Rushikesh Gaikwad on Medium]]></description>
        <link>https://medium.com/@rushikeshgaikwad4899?source=rss-17d3a7f9be32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f8TO-VypRIy0LxDtOJgPOg.png</url>
            <title>Stories by Rushikesh Gaikwad on Medium</title>
            <link>https://medium.com/@rushikeshgaikwad4899?source=rss-17d3a7f9be32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:56:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rushikeshgaikwad4899/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[Stop Fighting Data Races: A Practical Guide to Swift Actors (and the Reentrancy Trap Nobody Warns…]]></title>
            <link>https://medium.com/@rushikeshgaikwad4899/stop-fighting-data-races-a-practical-guide-to-swift-actors-and-the-reentrancy-trap-nobody-warns-8bd4cb7e77bb?source=rss-17d3a7f9be32------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd4cb7e77bb</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Rushikesh Gaikwad]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 18:12:35 GMT</pubDate>
            <atom:updated>2026-11-23T18:12:35.394Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Fighting Data Races: A Practical Guide to Swift Actors (and the Reentrancy Trap Nobody Warns You About)</h3><p><em>The bug that passes every test, survives code review, and crashes in production at 2 AM.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hkz1WrUiWL0JqmSsSvzpdw.png" /></figure><p>Every iOS developer has met this bug.</p><p>A counter shows the wrong number. A cache returns stale data. An array crashes with Index out of range, but only on some devices, only sometimes, and never when you attach the debugger.</p><p>That’s a <strong>data race</strong>: two threads touching the same memory at the same time, with at least one of them writing. For years our defenses were DispatchQueue, locks, semaphores, and hope.</p><p>Swift’s concurrency model gives us something better. Here’s how <strong>actors</strong> work, where they quietly betray you, and the patterns that make your concurrent code boring and safe.</p><h3>The Bug: A Class That Looks Fine</h3><pre>final class Counter {<br>    private(set) var value = 0<br><br>    func increment() {<br>        value += 1<br>    }<br>}<br><br>let counter = Counter()<br><br>await withTaskGroup(of: Void.self) { group in<br>    for _ in 0..&lt;1000 {<br>        group.addTask { counter.increment() }<br>    }<br>}<br><br>print(counter.value) // Expected: 1000. Actual: 987? 994? Who knows.</pre><p>value += 1 looks like one operation, but it’s three: <strong>read, add, write</strong>. When two threads interleave those steps, one increment is lost.</p><p>In Swift 6 language mode, the compiler refuses to build this code at all. That’s the point: <strong>Swift turns data races from runtime mysteries into compile-time errors.</strong></p><h3>The Fix: Actors</h3><pre>actor Counter {<br>    private(set) var value = 0<br><br>    func increment() {<br>        value += 1<br>    }<br>}<br><br>let counter = Counter()<br><br>await withTaskGroup(of: Void.self) { group in<br>    for _ in 0..&lt;1000 {<br>        group.addTask { await counter.increment() }<br>    }<br>}<br><br>print(await counter.value) // Always 1000.</pre><p>An actor protects its mutable state by allowing <strong>only one task at a time</strong> to run code on it. Everyone else waits in line. You don’t write locks or queues. You write actor instead of class.</p><p>Notice the new keyword at every call site: <strong>await</strong>. It marks a place where your code may pause while waiting for the actor to become free. These markers aren’t noise. They tell you where interleaving can happen, and that matters for the next section.</p><h3>The Trap: Actor Reentrancy</h3><p>Most tutorials stop at “actors are thread-safe.” That’s true, and it’s also what leads to the nastiest actor bugs.</p><blockquote><strong><em>An actor guarantees that only one task runs at a time. It does NOT guarantee that your function runs from start to finish without interruption.</em></strong></blockquote><p>Whenever an actor function hits an await, it <em>suspends</em>, and the actor is free to run other work. This is called <strong>reentrancy</strong>.</p><p>Here’s an image cache that looks correct:</p><pre>actor ImageCache {<br>    private var cache: [URL: Data] = [:]<br><br>    func data(for url: URL) async throws -&gt; Data {<br>        if let cached = cache[url] {<br>            return cached<br>        }<br><br>        // ⚠️ Suspension point: the actor is now free for other callers<br><br>        let (data, _) = try await URLSession.shared.data(from: url)<br><br>        cache[url] = data<br>        return data<br>    }<br>}</pre><p>No data race exists here, and the actor protects cache perfectly. But picture a feed screen where 10 cells request the same avatar at once:</p><ol><li>Call #1 checks the cache. Miss. Starts downloading, suspends.</li><li>Call #2 enters the now-free actor. Checks the cache. Still a miss. Starts downloading.</li><li>Calls #3 through #10 do exactly the same.</li></ol><p><strong>You just downloaded the same image 10 times.</strong> The state was safe, but the <em>logic</em> was broken, because the check (cache[url]) and the act (cache[url] = data) were separated by an await.</p><h4>The Rule</h4><blockquote><strong><em>Never assume state is unchanged after an </em></strong><strong><em>await.</em></strong><em> Re-check, or restructure so you don’t have to.</em></blockquote><h4>The Pro Fix: Cache the Task, Not Just the Result</h4><p>Instead of storing finished data, store the <strong>in-flight work</strong> so later callers join it:</p><pre>actor ImageCache {<br>    private var cache: [URL: Data] = [:]<br>    private var inFlight: [URL: Task&lt;Data, Error&gt;] = [:]<br><br>    func data(for url: URL) async throws -&gt; Data {<br>        // 1. Already finished? Return immediately.<br>        if let cached = cache[url] {<br>            return cached<br>        }<br><br>        // 2. Already downloading? Join the existing task.<br>        if let existing = inFlight[url] {<br>            return try await existing.value<br>        }<br><br>        // 3. Otherwise, start it and register it BEFORE suspending.<br>        let task = Task {<br>            let (data, _) = try await URLSession.shared.data(from: url)<br>            return data<br>        }<br>        inFlight[url] = task  <br><br>        do {<br>            let data = try await task.value<br>            cache[url] = data<br>            inFlight[url] = nil<br>            return data<br>        } catch {<br>            inFlight[url] = nil<br>            throw error<br>        }<br>    }<br>}</pre><p>The crucial detail is that inFlight[url] = task runs <strong>before</strong> the first suspension point. Once it’s registered, every later caller finds it and waits on the same task. Ten requests, one download.</p><p>This pattern, <strong>deduplicating in-flight work</strong>, shows up everywhere: token refresh, config loading, database migrations, thumbnail generation. Learn it once and you’ll use it for years.</p><h3>@MainActor: The Actor You Already Use</h3><p>The UI must only be touched from the main thread. @MainActor makes the compiler enforce that:</p><pre>@MainActor<br>final class ProfileViewModel: ObservableObject {<br>    @Published var name = &quot;&quot;<br>    @Published var isLoading = false<br><br>    func load() async {<br>        isLoading = true<br>        defer { isLoading = false }<br><br>        do {<br>            let profile = try await api.fetchProfile() // runs off the main actor<br>            name = profile.name                        // back on main, guaranteed<br>        } catch {<br>            name = &quot;Failed to load&quot;<br>        }<br>    }<br>}</pre><p>No more DispatchQueue.main.async { ... } sprinkled around. The compiler guarantees that property updates happen on the main thread. If you forget, <strong>it won’t compile</strong>.</p><h3>Sendable: What’s Allowed to Cross the Border</h3><p>Actors protect their <em>internal</em> state. But values passed between concurrency domains must be safe to share. Swift expresses this with the Sendable protocol:</p><pre>// ✅ Value types made of Sendable parts are Sendable<br>struct User: Sendable {<br>    let id: Int<br>    let name: String<br>}<br><br>// ❌ A mutable class is not<br>final class Settings {<br>    var theme = &quot;dark&quot;<br>}</pre><p>Passing a Settings instance across actors is exactly how two threads end up mutating the same object. The compiler now catches it.</p><p><strong>Practical advice:</strong></p><ul><li>Prefer struct and enum for data you pass around. They’re copied, so no sharing happens.</li><li>If a class must cross boundaries, make it final with only let properties, or turn it into an actor.</li><li>Avoid @unchecked Sendable unless you’ve protected the state yourself and can explain why it’s safe.</li></ul><h3>5 Mistakes I See Constantly</h3><p><strong>1. Treating </strong><strong>await as “just async.”</strong><br> It’s a place where <em>other code can run</em>. Re-validate your assumptions after every one.</p><p><strong>2. Putting everything on </strong><strong>@MainActor to silence errors.</strong><br> It compiles, but you’ve moved heavy work onto the UI thread. Keep parsing, disk, and network processing off it.</p><p><strong>3. Using </strong><strong>Task { } as a fire-and-forget escape hatch.</strong><br> Unstructured tasks don’t inherit cancellation. Prefer async let and TaskGroup, which give you structured, cancellable concurrency.</p><p><strong>4. Making an actor “too big.”</strong><br> One giant actor for your whole app becomes a bottleneck. Create small actors with a single, focused responsibility, like a cache, a token manager, or a download coordinator.</p><p><strong>5. Mixing actors with locks or </strong><strong>DispatchQueue.</strong><br> Pick one model per piece of state. Layering them invites deadlocks and confusing behavior.</p><h3>Cheat Sheet</h3><ol><li>Shared mutable state accessed from many tasks use actor</li><li>Anything that touches UI use @MainActor</li><li>Data passed between tasks use Sendable value types</li><li>Run N operations in parallel and gather results use TaskGroup / async let</li><li>Many callers need the same expensive result use Cache the in-flight Task</li><li>Immutable property needed without awaituse nonisolated(on let constants)</li></ol><h3>Final Thoughts</h3><p>Swift concurrency changes where bugs get caught. Instead of discovering races in production crash logs, you discover them in the compiler. Actors give you safety, Sendable gives you boundaries, and understanding <strong>reentrancy</strong> gives you correctness, which is the part most developers miss.</p><p>If you remember one thing from this article, make it this:</p><blockquote><strong><em>Actors make your state safe. Only you can make your logic correct.</em></strong></blockquote><p>Next time you write an await inside an actor, stop and ask: <em>“What if someone else got here while I was waiting?”</em> That one question will save you from a whole class of bugs.</p><p><em>If this helped you, a 👏 or a follow means a lot. I write about Swift, SwiftUI, and building better iOS apps. What topic should I cover next: SwiftUI performance, Swift Macros, or architecture patterns? Tell me in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd4cb7e77bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@ViewBuilder in SwiftUI: The Magic Behind Multiple Views]]></title>
            <link>https://medium.com/@rushikeshgaikwad4899/viewbuilder-in-swiftui-the-magic-behind-multiple-views-1fa366ec2b69?source=rss-17d3a7f9be32------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa366ec2b69</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Rushikesh Gaikwad]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 06:20:23 GMT</pubDate>
            <atom:updated>2026-10-06T06:20:23.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="@ViewBuilder transformation pipeline: How multiple SwiftUI views compile into a single view hierarchy." src="https://cdn-images-1.medium.com/max/1024/1*hGObTEfic3pUzqcch6i1Ew.png" /><figcaption>@ViewBuilder transformation pipeline: How multiple SwiftUI views compile into a single view hierarchy.</figcaption></figure><p>If you’ve worked with SwiftUI, you’ve probably written code like this:</p><pre>VStack {<br>    Text(&quot;Hello&quot;)<br>    Text(&quot;Welcome to SwiftUI&quot;)<br>    Image(systemName: &quot;swift&quot;)<br>}</pre><p>But have you ever wondered how SwiftUI allows us to write multiple views inside a closure when a function normally returns only one value?</p><p>The answer is <strong>@ViewBuilder</strong>.</p><p>Let’s understand what it is, why we need it, and where we can use it.</p><h3>What is @ViewBuilder?</h3><p>@ViewBuilder is a <strong>result builder</strong> provided by SwiftUI.</p><p>It allows us to combine multiple SwiftUI views into a single view hierarchy.</p><p>For example:</p><pre>@ViewBuilder<br>func profileView() -&gt; some View {<br>    Text(&quot;Rushikesh&quot;)<br>    Text(&quot;iOS Developer&quot;)<br>    Image(systemName: &quot;person.circle&quot;)<br>}</pre><p>Here we have multiple views, but the function still returns:</p><pre>some View</pre><p>@ViewBuilder handles the construction of these multiple views.</p><p>A simple way to think about it is:</p><pre>Multiple Views<br>      ↓<br> @ViewBuilder<br>      ↓<br>View Hierarchy</pre><h3>Why Do We Need @ViewBuilder?</h3><p>Without @ViewBuilder, this won&#39;t work:</p><pre>func profileView() -&gt; some View {<br>    Text(&quot;Rushikesh&quot;)<br>    Text(&quot;iOS Developer&quot;)<br>}</pre><p>The problem is that the function is expected to return a single value, but we’re providing multiple views.</p><p>We could solve this by explicitly wrapping them:</p><pre>func profileView() -&gt; some View {<br>    VStack {<br>        Text(&quot;Rushikesh&quot;)<br>        Text(&quot;iOS Developer&quot;)<br>    }<br>}</pre><p>But @ViewBuilder allows us to write:</p><pre>@ViewBuilder<br>func profileView() -&gt; some View {<br>    Text(&quot;Rushikesh&quot;)<br>    Text(&quot;iOS Developer&quot;)<br>}</pre><p>This is especially useful when building reusable SwiftUI components.</p><h3>@ViewBuilder with Conditions</h3><p>One of the biggest advantages of @ViewBuilder is that it works nicely with conditional views.</p><pre>@ViewBuilder<br>func statusView(isLoggedIn: Bool) -&gt; some View {<br>    if isLoggedIn {<br>        Text(&quot;Welcome Back!&quot;)<br>    } else {<br>        Text(&quot;Please Login&quot;)<br>    }<br>}</pre><p>We can also use an if without an else:</p><pre>@ViewBuilder<br>func notificationView(showNotification: Bool) -&gt; some View {<br>    Text(&quot;Home&quot;)<br>    if showNotification {<br>        Text(&quot;You have a new notification&quot;)<br>    }<br>}</pre><p>The builder takes care of constructing the appropriate view hierarchy based on the condition.</p><h3>Using @ViewBuilder in Custom Views</h3><p>This is where @ViewBuilder becomes really useful.</p><p>Suppose we want to create a reusable card:</p><pre>struct CardView&lt;Content: View&gt;: View {<br>    let content: Content<br><br>    init(@ViewBuilder content: () -&gt; Content) {<br>        self.content = content()<br>    }<br><br>    var body: some View {<br>        VStack {<br>            content<br>        }<br>        .padding()<br>    }<br>}</pre><p>Now we can pass multiple views into it:</p><pre>CardView {<br>    Text(&quot;Investment&quot;)<br>        .font(.headline)<br><br>    Text(&quot;$10,000&quot;)<br><br>    Button(&quot;View Details&quot;) {<br>        print(&quot;Tapped&quot;)<br>    }<br>}</pre><p>“By adopting this generic pattern, your CardView becomes a flexible container, just like a built-in VStack or List. This is the single best way to create a truly modular and re-usable component library in SwiftUI.&quot;</p><p>The CardView controls the overall layout, while the caller provides the content.</p><p>This makes our components <strong>flexible and reusable</strong>.</p><h3>Why Do We Use Content: View?</h3><p>You may have noticed this:</p><pre>struct CardView&lt;Content: View&gt;: View</pre><p>SwiftUI views can have different concrete types.</p><p>For example:</p><pre>Text(&quot;Hello&quot;)</pre><p>and:</p><pre>Image(systemName: &quot;star&quot;)</pre><p>are different types.</p><p>By using:</p><pre>Content: View</pre><p>we allow our component to accept <strong>any view that conforms to the </strong><strong>View protocol</strong>.</p><h3>@ViewBuilder vs some View</h3><p>These two are often confused, but they solve different problems.</p><h3>@ViewBuilder</h3><p>Used to <strong>build multiple views</strong>.</p><pre>@ViewBuilder<br>func content() -&gt; some View {<br>    Text(&quot;Hello&quot;)<br>    Text(&quot;World&quot;)<br>}</pre><h3>some View</h3><p>Used to <strong>hide the concrete return type</strong>.</p><pre>func content() -&gt; some View {<br>    Text(&quot;Hello&quot;)<br>}</pre><p>So remember:</p><blockquote><strong><em>@ViewBuilder builds the views, while </em></strong><strong><em>some View hides the concrete type.</em></strong></blockquote><h3>@ViewBuilder vs Group</h3><p>Group and @ViewBuilder are also different.</p><p>Group is a <strong>SwiftUI view container</strong>:</p><pre>Group {<br>    Text(&quot;Hello&quot;)<br>    Text(&quot;World&quot;)<br>}</pre><p>@ViewBuilder is a <strong>result builder</strong> that helps construct the view hierarchy.</p><p>A simple way to remember:</p><blockquote><strong><em>Group is a view. </em></strong><strong><em>@ViewBuilder is a mechanism for building views.</em></strong></blockquote><h3>Is @ViewBuilder a Property Wrapper?</h3><p>No.</p><p>This is an important distinction.</p><p>Things like:</p><pre>@State<br>@Binding<br>@ObservedObject</pre><p>are property wrappers.</p><p>@ViewBuilder is a <strong>result builder</strong>.</p><p>They serve completely different purposes.</p><h3>Do We Always Need @ViewBuilder?</h3><p>No.</p><p>If your function returns a single view, you don’t need it:</p><pre>func titleView() -&gt; some View {<br>    Text(&quot;Hello&quot;)<br>}</pre><p>Use @ViewBuilder when you need to build multiple views or support conditional view construction.</p><h3>@ViewBuilder in SwiftUI APIs</h3><p>You’ve probably already been using @ViewBuilder without realizing it.</p><p>For example:</p><pre>VStack {<br>    Text(&quot;Hello&quot;)<br>    Text(&quot;World&quot;)<br>}</pre><pre>HStack {<br>    Image(systemName: &quot;person&quot;)<br>    Text(&quot;Profile&quot;)<br>}</pre><pre>List {<br>    Text(&quot;Apple&quot;)<br>    Text(&quot;Banana&quot;)<br>    Text(&quot;Orange&quot;)<br>}</pre><p>SwiftUI uses view-builder-based closures extensively to give us this clean, declarative syntax.</p><h3>Key Takeaways</h3><p>If you remember only a few things about @ViewBuilder, remember these:</p><ul><li>@ViewBuilder is a <strong>Swift result builder</strong>.</li><li>It allows us to construct <strong>multiple SwiftUI views</strong>.</li><li>It supports <strong>conditional views</strong> such as if/else.</li><li>It is commonly used when creating <strong>reusable custom components</strong>.</li><li>@ViewBuilder is <strong>not a property wrapper</strong>.</li><li>@ViewBuilder and some View serve <strong>different purposes</strong>.</li><li>You don’t need @ViewBuilder when returning only a single view.</li></ul><p>Once you understand these concepts, the SwiftUI syntax starts to make much more sense.</p><p>What initially looks like magic is actually a powerful result-building mechanism that makes SwiftUI’s declarative UI syntax possible.</p><p><strong>Happy coding! 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa366ec2b69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[for-in vs forEach in Swift: The Difference You Should Know]]></title>
            <link>https://medium.com/@rushikeshgaikwad4899/for-in-vs-foreach-in-swift-the-difference-you-should-know-d262c8db0dc0?source=rss-17d3a7f9be32------2</link>
            <guid isPermaLink="false">https://medium.com/p/d262c8db0dc0</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Rushikesh Gaikwad]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 09:56:53 GMT</pubDate>
            <atom:updated>2026-09-29T09:56:53.815Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand when to use each, their key differences, and common mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PidHkRyW1knSuAqrpZNHJw.png" /></figure><p>When working with collections in Swift, we often need to go through each element and perform some operation.</p><p>Swift provides different ways to do this. Two commonly used approaches are:</p><ul><li>for-in loop</li><li>forEach</li></ul><p>At first, they may look almost the same. But there are some important differences that you should understand before choosing one.</p><p>Let’s understand them with simple examples.</p><h3>What is a for-in loop?</h3><p>A for-in loop is the traditional way of iterating over a collection in Swift.</p><p>For example:</p><pre>let names = [&quot;John&quot;, &quot;Alex&quot;, &quot;Sam&quot;]</pre><pre>for name in names {<br>    print(name)<br>}</pre><p>Output:</p><pre>John<br>Alex<br>Sam</pre><p>Here, Swift takes each element from the names array and assigns it to name.</p><p>The loop runs once for every element in the array.</p><h3>Another example</h3><p>We can also use for-in with a range:</p><pre>for number in 1...5 {<br>    print(number)<br>}</pre><p>Output:</p><pre>1<br>2<br>3<br>4<br>5</pre><p>So, for-in is useful whenever we want to iterate through a sequence of values.</p><h3>What is forEach?</h3><p>forEach is a method provided by Swift&#39;s collections.</p><p>Instead of writing a traditional loop, we provide a closure that should be executed for every element.</p><pre>let names = [&quot;John&quot;, &quot;Alex&quot;, &quot;Sam&quot;]</pre><pre>names.forEach { name in<br>    print(name)<br>}</pre><p>The output is the same:</p><pre>John<br>Alex<br>Sam</pre><p>We can make it even shorter using $0:</p><pre>names.forEach {<br>    print($0)<br>}</pre><p>Here, $0 represents the current element.</p><p>So:</p><pre>names.forEach {<br>    print($0)<br>}</pre><p>is basically saying:</p><blockquote><em>“For each name in the array, print that name.”</em></blockquote><h3>Then why do we need both?</h3><p>This is where the important difference comes in.</p><p>For simple iteration, both approaches can do the same thing.</p><p>But for-in gives us more control over the loop.</p><p>Let’s look at the differences one by one.</p><h3>1. break works with for-in</h3><p>Suppose we have numbers from 1 to 10, but we want to stop when we reach 5.</p><p>With for-in, we can use break.</p><pre>for number in 1...10 {<br>    if number == 5 {<br>        break<br>    }</pre><pre>    print(number)<br>}</pre><p>Output:</p><pre>1<br>2<br>3<br>4</pre><p>When number becomes 5, break stops the entire loop.</p><p>This is one of the important advantages of for-in.</p><p>With forEach, we cannot use break in the same way.</p><pre>numbers.forEach {<br>    if $0 == 5 {<br>        break // ❌ Not allowed<br>    }<br>}</pre><p>So if you need to stop the iteration early, use for-in.</p><h3>2. continue works with for-in</h3><p>Sometimes we don’t want to stop the entire loop. We just want to skip the current element.</p><p>That’s what continue does.</p><p>For example:</p><pre>for number in 1...5 {<br>    if number == 3 {<br>        continue<br>    }</pre><pre>    print(number)<br>}</pre><p>Output:</p><pre>1<br>2<br>4<br>5</pre><p>When the number is 3, Swift skips that iteration and moves to the next one.</p><p>Again, forEach doesn&#39;t provide continue in the same way.</p><p>So whenever you need to skip or control individual iterations, for-in is usually clearer.</p><h3>3. return behaves differently inside forEach</h3><p>This is another area that can sometimes confuse developers.</p><p>Consider this example:</p><pre>let names = [&quot;John&quot;, &quot;Alex&quot;, &quot;Sam&quot;]</pre><pre>names.forEach { name in<br>    if name == &quot;Alex&quot; {<br>        return<br>    }</pre><pre>    print(name)<br>}</pre><p>The output is:</p><pre>John<br>Sam</pre><p>What happened here?</p><p>When the name is &quot;Alex&quot;, return exits the current closure execution.</p><p>It does <strong>not</strong> stop the entire forEach.</p><p>The forEach continues with &quot;Sam&quot;.</p><p>You can think of it like this:</p><pre>John → execute<br>Alex → return from this closure execution<br>Sam  → execute</pre><p>If your intention is to control the entire loop, for-in is easier to understand.</p><h3>4. for-in is easier when the logic becomes complex</h3><p>Imagine we are working with banking transactions.</p><p>We want to check transactions and stop when we find a blocked transaction.</p><pre>for transaction in transactions {<br>  if transaction.isBlocked {<br>        print(&quot;Blocked transaction found&quot;)<br>        break<br>    }<br>    print(&quot;Processing transaction&quot;)<br>}</pre><p>This is easy to understand.</p><p>The logic is:</p><ol><li>Go through each transaction.</li><li>Check whether it is blocked.</li><li>If it is blocked, stop.</li><li>Otherwise, continue processing.</li></ol><p>Trying to handle complex control flow inside forEach can make the code less readable.</p><p>For simple operations, forEach is nice.</p><p>For complex logic, for-in is often easier to follow.</p><h3>5. What about async/await?</h3><p>Modern Swift applications use async/await frequently.</p><p>Suppose we have multiple users and want to fetch their details one by one.</p><p>With for-in, we can write:</p><pre>for user in users {<br>    await fetchUserDetails(user)<br>}</pre><p>This makes the flow very clear.</p><p>We are saying:</p><blockquote><em>Take one user, fetch the details, then move to the next user.</em></blockquote><p>forEach is not designed to work like a normal structured loop with asynchronous operations.</p><p>So when working with async/await, especially when you need sequential execution, for-in is generally the better choice.</p><h3>6. When should you use forEach?</h3><p>forEach is a good choice when you simply want to perform an action for every element.</p><p>For example:</p><pre>let accounts = [&quot;Savings&quot;, &quot;Current&quot;, &quot;Investment&quot;]</pre><pre>accounts.forEach {<br>    print(&quot;Account: \($0)&quot;)<br>}</pre><p>This is short and easy to understand.</p><p>Another example:</p><pre>transactions.forEach { transaction in<br>    logTransaction(transaction)<br>}</pre><p>There is no complicated logic here.</p><p>We simply want to perform logTransaction() for every transaction.</p><p>This is where forEach works nicely.</p><h3>7. When should you use for-in?</h3><p>Use for-in when you need more control over the iteration.</p><p>For example:</p><h3>When you need break</h3><pre>for transaction in transactions {<br>    if transaction.isBlocked {<br>        break<br>    }<br>}</pre><h3>When you need continue</h3><pre>for transaction in transactions {<br>    if transaction.isCancelled {<br>        continue<br>    }<br>  process(transaction)<br>}</pre><h3>When you have complex logic</h3><pre>for transaction in transactions {<br>    if transaction.isCancelled {<br>        continue<br>    }<br>    if transaction.amount &gt; 10000 {<br>        print(&quot;Large transaction&quot;)<br>    }<br>    if transaction.isBlocked {<br>        break<br>    }<br>}</pre><p>In these situations, for-in makes the intention much clearer.</p><h3>for-in vs forEach</h3><p>Here is a simple comparison between for-in and forEach:</p><h3>for-in</h3><ul><li>✅ Can iterate over a collection</li><li>✅ Supports break</li><li>✅ Supports continue</li><li>✅ Good for complex control flow</li><li>✅ Allows early exit</li><li>✅ Works naturally with sequential async/await</li><li>❌ Does not use a closure</li></ul><h3>forEach</h3><ul><li>✅ Can iterate over a collection</li><li>❌ Does not support break</li><li>❌ Does not support continue</li><li>⚠️ Can become less readable with complex control flow</li><li>❌ Cannot easily stop the entire iteration</li><li>⚠️ Not suitable in the same way for sequential async/await</li><li>✅ Uses a closure</li></ul><h3>In short</h3><p><strong>Use </strong><strong>forEach</strong> when you simply want to perform an action for every element.</p><p><strong>Use </strong><strong>for-in</strong> when you need more control over the iteration, such as using break, continue, or handling more complex logic.What about performance?</p><p>A common question is:</p><blockquote><em>“Which one is faster — </em><em>for-in or </em><em>forEach?&quot;</em></blockquote><p>In most real-world applications, you should <strong>not choose between them based only on performance</strong>.</p><p>For normal collection iteration, the difference is usually not something you should worry about.</p><p>Instead, choose the one that makes your code easier to understand.</p><p>For example:</p><pre>names.forEach {<br>    print($0)<br>}</pre><p>is perfectly reasonable when all you want to do is perform an action for every name.</p><p>But if you need:</p><pre>break<br>continue</pre><p>or more complex control flow, use:</p><pre>for name in names {<br>    // logic<br>}</pre><h3>A simple rule to remember</h3><p>If you only remember one thing from this article, remember this:</p><blockquote><strong><em>Use </em></strong><strong><em>forEach when you simply want to perform an action for every element.</em></strong></blockquote><blockquote><strong><em>Use </em></strong><strong><em>for-in when you need control over the iteration.</em></strong></blockquote><p>You can think about it like this:</p><pre>Simple operation<br>      ↓<br>   forEach</pre><pre>Need control<br>      ↓<br>   for-in<br>      ↓<br>break / continue / early exit</pre><h3>Final Thoughts</h3><p>Both for-in and forEach are useful ways to iterate over collections in Swift.</p><p>Neither one is universally “better.”</p><p>The right choice depends on what you are trying to accomplish.</p><p>For simple operations:</p><pre>names.forEach {<br>    print($0)<br>}</pre><p>is clean and concise.</p><p>For more control:</p><pre>for name in names {<br>    if name == &quot;Alex&quot; {<br>        continue<br>    }<br>    print(name)<br>}</pre><p>for-in is usually the better choice.</p><p>Understanding this small difference can help you write Swift code that is not only shorter, but also <strong>clearer and easier to maintain</strong>.</p><p>If you’re learning Swift, don’t just focus on knowing the syntax. Try to understand <strong>why and when you should use each approach</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d262c8db0dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@StateObject vs @ObservedObject in SwiftUI: A Quick, Practical Guide]]></title>
            <link>https://medium.com/@rushikeshgaikwad4899/stateobject-vs-observedobject-in-swiftui-a-quick-practical-guide-67b9e6801a1b?source=rss-17d3a7f9be32------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b9e6801a1b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Rushikesh Gaikwad]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 18:57:43 GMT</pubDate>
            <atom:updated>2026-08-27T18:58:33.818Z</atom:updated>
            <content:encoded><![CDATA[<p>Stop guessing which property wrapper to use — understand state ownership in under 5 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TdwiCBqVCe6Zq-Ap1s6ew.png" /><figcaption>SwiftUI State Management: @StateObject (Owner) vs @ObservedObject (Subscriber).</figcaption></figure><p>If you have worked with SwiftUI, you have probably seen both @StateObject and @ObservedObject. They look similar because both work with ObservableObject, but they solve different problems.</p><p>The easiest way to remember the difference is:</p><blockquote><strong><em>@StateObject = I own it.</em></strong><em><br></em><strong><em>@ObservedObject = I observe it.</em></strong></blockquote><h3>First: What Is ObservableObject?</h3><p>An ObservableObject is a reference-type model that can notify SwiftUI when its published properties change.</p><pre>final class ProfileViewModel: ObservableObject {<br>    @Published var username = &quot;Rushikesh&quot;<br>}</pre><p>@Published is what makes the property emit change notifications through ObservableObject.</p><h3>@StateObject — When the View Owns the Object</h3><p>Use @StateObject when the view <strong>creates and owns</strong> the observable object.</p><pre>struct ProfileView: View {<br>    @StateObject private var viewModel = ProfileViewModel()<br><br>var body: some View {<br>        Text(viewModel.username)<br>    }<br>}</pre><p>Why not just use @ObservedObject here?</p><p>SwiftUI views are value types and can be recreated. @StateObject tells SwiftUI to keep the object associated with the view&#39;s identity instead of treating it as a new object every time the view value is recomputed.</p><p>Think of it as:</p><pre>View<br> │<br> └── owns → ViewModel</pre><h3>Use @StateObject when:</h3><ul><li>The view creates the object.</li><li>The view is the owner of that object’s lifecycle.</li><li>You want the object to persist across view value recreation.</li></ul><h3>@ObservedObject — When the View Receives the Object</h3><p>Use @ObservedObject when the object is <strong>created and owned somewhere else</strong>.</p><pre>struct ParentView: View {<br>    @StateObject private var viewModel = ProfileViewModel()<br><br>      var body: some View {<br>        ProfileDetailsView(viewModel: viewModel)<br>    }<br>}<br><br>struct ProfileDetailsView: View {<br>    @ObservedObject var viewModel: ProfileViewModel<br><br>    var body: some View {<br>        Text(viewModel.username)<br>    }<br>}</pre><p>Here, ParentView owns the view model. ProfileDetailsView only observes it.</p><pre>ParentView<br>    │<br>    └── owns → ViewModel<br>                 │<br>                 └── observed by → ChildView</pre><h3>Use @ObservedObject when:</h3><ul><li>Another object/view creates the view model.</li><li>The current view receives it as a dependency.</li><li>The current view should observe changes but should not establish ownership.</li></ul><h3>The Most Important Difference</h3><p>The difference is simple: <strong>ownership</strong>.</p><h3>@StateObject</h3><p>The view <strong>creates and owns</strong> the object. SwiftUI manages its lifetime.</p><pre>@StateObject private var viewModel = ProfileViewModel()</pre><h3>@ObservedObject</h3><p>The object is <strong>created and owned somewhere else</strong>. The view only observes it.</p><pre>@ObservedObject var viewModel: ProfileViewModel</pre><p>Both can observe changes. The question to ask is:</p><blockquote><strong><em>Who owns the object?</em></strong></blockquote><p>If <strong>I create it</strong>, use @StateObject.</p><p>If <strong>someone else gives it to me</strong>, use @ObservedObject.</p><h3>A Common Mistake</h3><p>Avoid this when the current view creates the object:</p><pre>@ObservedObject var viewModel = ProfileViewModel()</pre><p>Prefer:</p><pre>@StateObject private var viewModel = ProfileViewModel()</pre><p>And don’t use @StateObject in a child just because the object is observable:</p><pre>@StateObject var viewModel: ProfileViewModel // ❌ if parent owns it</pre><p>Use:</p><pre>@ObservedObject var viewModel: ProfileViewModel // ✅ </pre><h3>What About @EnvironmentObject?</h3><p>@EnvironmentObject is useful when shared state needs to be available to many views without passing it through every initializer.</p><pre>@EnvironmentObject var session: SessionManager</pre><p>The simple mental model is:</p><pre>@StateObject       → I own it<br>@ObservedObject    → Someone gives it to me<br>@EnvironmentObject → SwiftUI provides it from the environment</pre><h3>What About @Binding?</h3><p>Don’t pass an entire view model if a child only needs one value.</p><pre>struct ProfileView: View {<br>    @State private var username = &quot;&quot;<br><br>var body: some View {<br>        UsernameEditor(username: $username)<br>    }<br>}<br>struct UsernameEditor: View {<br>    @Binding var username: String<br>    var body: some View {<br>        TextField(&quot;Username&quot;, text: $username)<br>    }<br>}</pre><p>This keeps dependencies smaller and makes views easier to reuse.</p><h3>What About the Modern Observation Framework?</h3><p>If you’re working with newer SwiftUI code, you may also see Apple’s Observation framework:</p><pre>@Observable<br>final class ProfileViewModel {<br>    var username = &quot;&quot;<br>}</pre><p>This is different from the older ObservableObject + @Published approach.</p><p>With Observation, you commonly use:</p><pre>@State private var viewModel = ProfileViewModel()</pre><p>and @Bindable when you need bindings.</p><p>So if you’re starting a new project, learn both patterns. If you’re working on an existing ObservableObject-based project, @StateObject and @ObservedObject are still important.</p><h3>Quick Decision Guide</h3><p>Ask yourself one question:</p><blockquote><strong><em>Who creates and owns this object?</em></strong></blockquote><p><strong>The current view creates it?</strong></p><pre>@StateObject</pre><p><strong>Another view/component creates it and passes it to you?</strong></p><pre>@ObservedObject</pre><p><strong>It is shared through the SwiftUI environment?</strong></p><pre>@EnvironmentObject</pre><p><strong>The child only needs one piece of mutable state?</strong></p><pre>@Binding</pre><h3>Final Takeaway</h3><p>Don’t memorize these property wrappers as four unrelated SwiftUI features. Think about <strong>ownership and data flow</strong>.</p><pre>@StateObject<br>    ↓<br>  Own it<br>@ObservedObject<br>    ↓<br>  Observe it<br>@EnvironmentObject<br>    ↓<br>  Get it from environment<br>@Binding<br>    ↓<br>  Share a specific piece of state</pre><p>Once you understand <strong>who owns the state and who only consumes it</strong>, choosing between @StateObject and @ObservedObject becomes much easier.</p><p>And that’s really the most important concept to take away from this topic.</p><p><strong>Enjoyed this quick guide?</strong></p><p>If you found this helpful, give it a few 👏 <strong>claps</strong> (you can clap up to 50 times!) so more developers can find it.</p><p>Follow me for more practical SwiftUI and iOS development tips!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b9e6801a1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Copy-on-Write in Swift: The Smart Way Swift Handles Value Types]]></title>
            <link>https://medium.com/@rushikeshgaikwad4899/copy-on-write-in-swift-the-smart-way-swift-handles-value-types-d7966608e936?source=rss-17d3a7f9be32------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7966608e936</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Rushikesh Gaikwad]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 04:59:03 GMT</pubDate>
            <atom:updated>2026-08-25T04:59:03.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hi8SEV7gxzje-DhVGm9RzQ.png" /></figure><h3><strong>How Copy-on-Write Prevents Wasteful Data Duplication Under the Hood</strong></h3><p>What happens when you assign one large Swift array to another?</p><p>Does Swift immediately duplicate all of its elements?</p><p>Surprisingly, <strong>no</strong>.</p><p>Swift uses a technique called <strong>Copy-on-Write (CoW)</strong> to preserve the behaviour of value types while avoiding unnecessary memory copies.</p><p>Let’s understand how it works with a simple example, then see how we can implement the same idea ourselves.</p><h3>What Is Copy-on-Write?</h3><p>Copy-on-Write is an optimization where multiple values can initially <strong>share the same underlying storage</strong>.</p><p>The actual data is copied only when one of those values needs to modify it.</p><p>Consider this:</p><pre>var first = [1, 2, 3]<br>var second = first</pre><p>Conceptually, the two arrays can share their storage:</p><pre>first  ───┐<br>          ├──&gt; [1, 2, 3]<br>second ───┘</pre><p>No separate copy is needed just because we assigned first to second.</p><p>Now modify second:</p><pre>second.append(4)</pre><p>Swift must ensure that changing second doesn&#39;t change first. The storage is therefore separated:</p><pre>first  ───&gt; [1, 2, 3]</pre><pre>second ───&gt; [1, 2, 3, 4]</pre><p>That’s the entire idea behind Copy-on-Write:</p><blockquote><strong><em>Share when you can. Copy when you must.</em></strong></blockquote><h3>Why Does Swift Use It?</h3><p>Swift relies heavily on value types such as Array, Dictionary, Set, and String.</p><p>Value semantics mean that when we copy a value and modify the copy, the original shouldn’t change.</p><p>For example:</p><pre>var numbers1 = [1, 2, 3]<br>var numbers2 = numbers1</pre><pre>numbers2.append(4)</pre><p>The result is:</p><pre>numbers1 → [1, 2, 3]<br>numbers2 → [1, 2, 3, 4]</pre><p>Now imagine numbers1 contains millions of elements.</p><p>If Swift eagerly copied all of that data during the assignment, the operation could require a large memory allocation even if numbers2 were never modified.</p><p>Copy-on-Write avoids that unnecessary work.</p><p>This gives Swift two important properties:</p><ul><li><strong>Value semantics</strong> — copies behave independently when modified.</li><li><strong>Efficient storage</strong> — data can be shared until a copy is actually needed.</li></ul><h3>What Actually Happens During a Write?</h3><p>The important moment is not the assignment:</p><pre>var second = first</pre><p>The important moment is the <strong>mutation</strong>:</p><pre>second.append(4)</pre><p>Before modifying shared storage, the implementation can determine whether that storage is uniquely referenced.</p><p>If it isn’t unique, a new storage is created and the modification happens on that new storage.</p><p>So the flow is essentially:</p><pre>Assignment<br>    ↓<br>Share storage<br>    ↓<br>Mutation?<br>    ↓<br> ┌──No──&gt; Keep sharing<br> │<br> Yes<br> ↓<br>Create a copy<br>    ↓<br>Modify the copy</pre><p>The important thing to remember is that <strong>Copy-on-Write is an implementation optimization</strong>. From the developer’s perspective, the value still behaves like an independent value.</p><h3>Implementing Copy-on-Write Yourself</h3><p>Swift provides isKnownUniquelyReferenced(_:), which can be used to build Copy-on-Write storage around a reference type.</p><p>Here’s a small example:</p><pre>final class Storage {<br>    var values: [Int]</pre><pre>    init(values: [Int]) {<br>        self.values = values<br>    }<br>}</pre><pre>struct MyArray {<br>    private var storage: Storage</pre><pre>    init(_ values: [Int]) {<br>        storage = Storage(values: values)<br>    }</pre><pre>    var values: [Int] {<br>        storage.values<br>    }</pre><pre>    mutating func append(_ value: Int) {<br>        if !isKnownUniquelyReferenced(&amp;storage) {<br>            storage = Storage(values: storage.values)<br>        }</pre><pre>        storage.values.append(value)<br>    }<br>}</pre><p>Now:</p><pre>var first = MyArray([1, 2, 3])<br>var second = first</pre><p>Both values can share the same Storage instance.</p><p>When we do:</p><pre>second.append(4)</pre><p>isKnownUniquelyReferenced tells us whether second has exclusive ownership of the storage.</p><p>If the storage is shared, we create a new Storage before modifying it.</p><p>This is the basic pattern used to build a custom Copy-on-Write value type.</p><h3>Where Do We See Copy-on-Write in Swift?</h3><p>You don’t normally need to implement CoW yourself. Swift’s standard library uses similar techniques for important value types, including:</p><ul><li>Array</li><li>Dictionary</li><li>Set</li><li>String</li></ul><p>That’s why assigning a large collection doesn’t necessarily mean immediately duplicating all of its underlying storage.</p><p>The optimization remains invisible to us while the type continues to provide value semantics.</p><h3>One Important Distinction</h3><p>Copy-on-Write is sometimes confused with a deep copy.</p><p>A <strong>deep copy</strong> creates independent storage immediately:</p><pre>original ───&gt; Data A<br>copy ───────&gt; Data B</pre><p>With Copy-on-Write, the storage can initially be shared:</p><pre>original ───┐<br>            ├──&gt; Data A<br>copy ───────┘</pre><p>Only when a mutation requires independence does the copy occur.</p><p>So the key difference is simple:</p><blockquote><strong><em>Deep copy copies now. Copy-on-Write copies only when necessary.</em></strong></blockquote><h3>When Should You Care About CoW?</h3><p>For normal iOS development, you usually don’t need to manually manage Copy-on-Write.</p><p>Understanding it becomes valuable when you’re:</p><ul><li>Working with large collections</li><li>Designing custom value types</li><li>Investigating memory or performance issues</li><li>Preparing for Swift interviews</li></ul><p>More importantly, CoW is a great example of how Swift combines <strong>value semantics with performance optimizations</strong>.</p><h3>Final Thoughts</h3><p>Copy-on-Write sounds complicated at first, but the idea is surprisingly simple:</p><pre>Copy<br> ↓<br>Share storage<br> ↓<br>Someone modifies the value?<br> ↓<br>Yes → Create a copy → Modify it</pre><p>You still get the predictable behavior of value types, but Swift avoids copying large amounts of data when that copy isn’t actually needed.</p><p>So the next time you write:</p><pre>var second = first</pre><p>remember:</p><blockquote><strong><em>The copy may not happen when you copy the value. It happens when you need to change it.</em></strong></blockquote><p>And that’s the beauty of Copy-on-Write in Swift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7966608e936" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.onAppear vs .task in SwiftUI: Which One Should You Use?]]></title>
            <link>https://medium.com/@rushikeshgaikwad4899/onappear-vs-task-in-swiftui-which-one-should-you-use-e36fcf879d01?source=rss-17d3a7f9be32------2</link>
            <guid isPermaLink="false">https://medium.com/p/e36fcf879d01</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Rushikesh Gaikwad]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 05:22:39 GMT</pubDate>
            <atom:updated>2026-08-24T05:22:39.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t788HbTLBybhrPwV9Jte7w.png" /><figcaption>SwiftUI comparison of .onAppear and .task for asynchronous view lifecycle work</figcaption></figure><h3>Understanding asynchronous work, view lifecycle, cancellation, and task(id:) with practical examples.</h3><p>You open a screen and need to load some data. You reach for .onAppear. Then you realize the API is asynchronous, so you write Task {} inside it. A few lines later, you discover that SwiftUI already provides a .task modifier.</p><p>So the obvious question is:</p><blockquote><strong><em>If both can start work when a view appears, what is the actual difference between </em></strong><strong><em>.onAppear and </em></strong><strong><em>.task?</em></strong></blockquote><p>This is a small SwiftUI topic, but it touches several important concepts: asynchronous closures, view lifecycle, concurrency, cancellation, and task(id:).</p><p>In this article, we’ll start with the basics and then use practical examples to decide which modifier makes sense in which situation.</p><p>You will usually come across these two modifiers:</p><pre>.onAppear {<br>    // Do something<br>}</pre><p>and:</p><pre>.task {<br>    // Do something asynchronously<br>}</pre><p>At first glance, they look almost identical.</p><p>Let’s find out where they actually differ.</p><h3>What is .onAppear?</h3><p>.onAppear is a SwiftUI view modifier that allows you to perform an action when a view appears.</p><p>A simple example looks like this:</p><pre>struct ProfileView: View {<br>    var body: some View {<br>        Text(&quot;Profile&quot;)<br>            .onAppear {<br>                print(&quot;Profile view appeared&quot;)<br>            }<br>    }<br>}</pre><p>The closure passed to .onAppear is synchronous:</p><pre>.onAppear {<br>    // Synchronous work<br>}</pre><p>This makes .onAppear a good choice for simple actions that don&#39;t require asynchronous execution.</p><p>For example:</p><pre>.onAppear {<br>    viewModel.resetState()<br>}</pre><p>or:</p><pre>.onAppear {<br>    analytics.trackScreenView()<br>}</pre><p>These operations don’t need await, so .onAppear is perfectly appropriate.</p><h3>What about making an API call?</h3><p>This is where things start getting interesting.</p><p>Suppose our view model has an asynchronous API call:</p><pre>@MainActor<br>final class ProfileViewModel: ObservableObject {<br>    func loadProfile() async {<br>        // API call<br>    }<br>}</pre><p>Because loadProfile() is asynchronous, we cannot directly write:</p><pre>.onAppear {<br>    await viewModel.loadProfile() // ❌<br>}</pre><p>The closure provided by .onAppear is not asynchronous.</p><p>One common solution is:</p><pre>.onAppear {<br>    Task {<br>        await viewModel.loadProfile()<br>    }<br>}</pre><p>This works because we explicitly create a Swift Concurrency Task inside the synchronous .onAppear closure.</p><p>But now we have another question:</p><blockquote><strong><em>If SwiftUI already provides </em></strong><strong><em>.task, why should we create a </em></strong><strong><em>Task manually inside </em></strong><strong><em>.onAppear?</em></strong></blockquote><p>Before answering that, let’s understand what .task actually provides.</p><h3>What is .task?</h3><p>.task is a SwiftUI view modifier designed to run asynchronous work associated with a view.</p><p>For example, if we want to load a profile when the screen appears, we can write:</p><pre>struct ProfileView: View {<br>    @StateObject private var viewModel = ProfileViewModel()</pre><pre>var body: some View {<br>        Text(&quot;Profile&quot;)<br>            .task {<br>                await viewModel.loadProfile()<br>            }<br>    }<br>}</pre><p>Notice the important difference from .onAppear: we can directly use await inside the .task closure.</p><pre>.task {<br>    await viewModel.loadProfile()<br>}</pre><p>The closure is asynchronous, which makes .task a natural fit for asynchronous operations.</p><h3>The important part: lifecycle</h3><p>The most useful feature of .task isn&#39;t simply that it allows us to write await.</p><p>It is that SwiftUI manages the task in relation to the view’s lifetime. Apple documents that SwiftUI can automatically cancel the task when the view disappears before the task completes.</p><p>Imagine the user opens ProfileView, the request starts, and the user navigates away before the operation completes.</p><p>The task associated with that view can be cancelled when the view’s lifetime ends.</p><p>This makes .task particularly useful for work such as:</p><ul><li>Fetching data from an API</li><li>Loading remote resources</li><li>Consuming an AsyncSequence</li><li>Performing other asynchronous operations that are relevant to the view</li></ul><p>There is one important detail to remember, though: <strong>cancellation is cooperative</strong>. Cancelling a Swift Task marks it as cancelled; the asynchronous code needs to respond to cancellation appropriately. APIs such as Task.isCancelled and Task.checkCancellation() can be used to respond to cancellation.</p><p>So .task is not simply another version of .onAppear.</p><p>It gives us an asynchronous context and lets SwiftUI associate that work with the view’s lifecycle.</p><h3>.onAppear vs .task: What Is the Actual Difference?</h3><p>At this point, the difference may seem simple:</p><blockquote><em>.onAppear is for synchronous work, while </em><em>.task is for asynchronous work.</em></blockquote><p>That’s a good starting point, but there is more to it.</p><p>The important difference is not just the syntax. It is also <strong>how the asynchronous work is associated with the SwiftUI view</strong>.</p><h3>.onAppear</h3><p>With .onAppear, SwiftUI executes the closure when the view appears:</p><pre>.onAppear {<br>    viewModel.resetState()<br>}</pre><p>If you need asynchronous work, you have to create a separate task yourself:</p><pre>.onAppear {<br>    Task {<br>        await viewModel.loadProfile()<br>    }<br>}</pre><p>Here, .onAppear triggers the closure, while the Task performs the asynchronous work.</p><h3>.task</h3><p>With .task, the asynchronous operation is expressed directly on the view:</p><pre>.task {<br>    await viewModel.loadProfile()<br>}</pre><p>SwiftUI can associate this task with the view’s lifetime and automatically cancel it when appropriate.</p><p>That makes the intent clearer:</p><pre>.task {<br>    await viewModel.loadProfile()<br>}</pre><p>reads as:</p><blockquote><strong><em>When this view is active, perform this asynchronous work.</em></strong></blockquote><p>Whereas:</p><pre>.onAppear {<br>    Task {<br>        await viewModel.loadProfile()<br>    }<br>}</pre><p>reads more like:</p><blockquote><strong><em>When this view appears, create a task to perform asynchronous work.</em></strong></blockquote><p>That distinction becomes important when the view disappears or the task needs to be restarted.</p><h3>A simple rule</h3><p>You can remember the difference like this:</p><ul><li>Use .onAppear for simple synchronous actions that should happen when a view appears.</li><li>Use .task for asynchronous work that is related to the view&#39;s lifetime.</li><li>Use .task(id:) when asynchronous work should restart when a value changes.</li></ul><p>This doesn’t mean .onAppear is outdated or that .task should replace it everywhere. They solve different problems.</p><h3>.onAppear { Task { ... } } vs .task: What Happens When the View Disappears?</h3><p>Consider this example:</p><pre>.onAppear {<br>    Task {<br>        await viewModel.loadProfile()<br>    }<br>}</pre><p>It is easy to assume that because the Task was created from .onAppear, SwiftUI will automatically manage its lifetime.</p><p>But that is not the right mental model.</p><p>The Task is created inside the .onAppear closure. If you discard that task&#39;s reference, you also give up the direct ability to cancel it yourself. A task continues running unless it completes or cancellation is requested.</p><p>Now compare it with:</p><pre>.task {<br>    await viewModel.loadProfile()<br>}</pre><p>With .task, SwiftUI manages the asynchronous operation as part of the view&#39;s lifecycle. If the view disappears while the task is still running, SwiftUI can cancel that task.</p><h3>Why does cancellation matter?</h3><p>Imagine a user opens a screen that loads a large amount of data:</p><pre>User opens screen<br>       ↓<br>API request starts<br>       ↓<br>User navigates away<br>       ↓<br>View disappears<br>       ↓<br>.task is cancelled</pre><p>This is useful because work that is no longer relevant to the screen can be cancelled.</p><p>However, remember that Swift concurrency uses <strong>cooperative cancellation</strong>. Cancellation is a signal, not an immediate force-stop. The asynchronous operation must be cancellation-aware for that cancellation to have the desired effect.</p><p>For example:</p><pre>.task {<br>    do {<br>        try await Task.sleep(for: .seconds(5))<br>        try Task.checkCancellation()<br>        await viewModel.loadProfile()<br>    } catch is CancellationError {<br>        print(&quot;Task was cancelled&quot;)<br>    } catch {<br>        print(&quot;Request failed: \(error)&quot;)<br>    }<br>}</pre><p>The key point is that .task gives SwiftUI a lifecycle-aware task, while a manually created task inside .onAppear is not the same thing.</p><h3>task(id:): The Feature That Makes .task Even More Powerful</h3><p>So far, we have looked at using .task to perform asynchronous work when a view becomes active.</p><p>But what if the asynchronous work depends on a value that can change?</p><p>Consider a search screen. The user types a search term, and we want to fetch matching results.</p><p>SwiftUI gives us a clean approach with task(id:):</p><pre>struct SearchView: View {<br>    @State private var searchText = &quot;&quot;</pre><pre>var body: some View {<br>        List {<br>            // Search results<br>        }<br>        .task(id: searchText) {<br>            guard !searchText.isEmpty else { return }</pre><pre>await viewModel.search(searchText)<br>        }<br>    }<br>}</pre><p>The important part is:</p><pre>.task(id: searchText) {<br>    await viewModel.search(searchText)<br>}</pre><p>SwiftUI observes the value supplied as the id. When that value changes, SwiftUI cancels the existing task and starts a new one. The id value must conform to Equatable.</p><h3>What happens when the user types?</h3><p>Imagine the user enters:</p><pre>S</pre><p>The task starts for S.</p><p>Then the user types:</p><pre>Sw</pre><p>The value changes, so SwiftUI cancels the previous task and starts a new task for Sw.</p><p>Then:</p><pre>Swi</pre><p>Again:</p><pre>Previous task → cancelled<br>New task      → started</pre><p>This gives us a useful mental model:</p><blockquote><strong><em>.task(id:) means: perform this asynchronous work for this value, and restart the work when that value changes.</em></strong></blockquote><h3>Why is this useful?</h3><p>This pattern is useful whenever asynchronous work depends on changing input, such as:</p><ul><li>Search text</li><li>Selected user ID</li><li>Selected account</li><li>A filter or query</li><li>A changing server or environment</li><li>Other values that determine what asynchronous data the view should display</li></ul><p>For example, if a profile screen receives a user ID:</p><pre>.task(id: userID) {<br>    await viewModel.loadProfile(for: userID)<br>}</pre><p>If userID changes, SwiftUI cancels the task associated with the previous value and starts a new task for the new value.</p><h3>A note about debouncing search</h3><p>You may see .task(id: searchText) described as a debounce solution. More precisely, task(id:) gives us <strong>cancellation and restart when the ID changes</strong>. If you want to wait before making the API request, you still need to add that delay.</p><p>For example:</p><pre>.task(id: searchText) {<br>    guard !searchText.isEmpty else { return }</pre><pre>do {<br>        try await Task.sleep(for: .milliseconds(300))<br>        try Task.checkCancellation()</pre><pre>await viewModel.search(searchText)<br>    } catch is CancellationError {<br>        // A newer search value arrived.<br>    } catch {<br>        // Handle other errors.<br>    }<br>}</pre><p>If the user types another character during the 300 milliseconds, the previous task is cancelled. Because Task.sleep is cancellation-aware, the API request can be avoided for the old search text.</p><h3>What Should You Use for an API Call?</h3><p>Now we can answer the question that started this article.</p><p>If you simply need to perform an asynchronous API call when a SwiftUI view becomes active, prefer .task:</p><pre>.task {<br>    await viewModel.loadProfile()<br>}</pre><p>This is clearer than:</p><pre>.onAppear {<br>    Task {<br>        await viewModel.loadProfile()<br>    }<br>}</pre><p>The second approach can still be useful when you intentionally want to create and manage a separate task yourself, but it should not be the default replacement for .task.</p><p>For view-scoped asynchronous work, .task communicates the intent and gives SwiftUI lifecycle-aware cancellation.</p><h3>When Should You Use .onAppear?</h3><p>.onAppear still has an important place in SwiftUI.</p><p>Use it when the work is simple, synchronous, and specifically related to the appearance of the view.</p><p>For example:</p><pre>.onAppear {<br>    viewModel.resetState()<br>}</pre><pre>.onAppear {<br>    analytics.trackScreenView()<br>}</pre><pre>.onAppear {<br>    isActive = true<br>}</pre><p>There is no need to introduce Swift Concurrency when the work itself is synchronous.</p><h3>When Should You Use .task?</h3><p>Use .task when the operation is asynchronous and should be associated with the lifetime of the view.</p><p>Common examples include:</p><ul><li>API requests</li><li>Loading remote data</li><li>Reading an AsyncSequence</li><li>Performing asynchronous database work</li><li>Starting other asynchronous operations that are relevant to the current view</li></ul><p>For example:</p><pre>.task {<br>    await viewModel.loadDashboard()<br>}</pre><p>If the asynchronous operation depends on a changing value, consider task(id:):</p><pre>.task(id: selectedAccountID) {<br>    await viewModel.loadTransactions(for: selectedAccountID)<br>}</pre><h3>A Simple Decision Guide</h3><p>When deciding between the two modifiers, ask one question first:</p><blockquote><strong><em>Is the work asynchronous?</em></strong></blockquote><p>If the answer is <strong>no</strong>, and you simply need to perform an action when the view appears, .onAppear is usually appropriate.</p><p>If the answer is <strong>yes</strong>, and the asynchronous work belongs to the view’s lifecycle, .task is usually the better choice.</p><p>If the asynchronous work depends on a value that can change, use .task(id:) so SwiftUI can cancel the old task and start a new one when the value changes.</p><p>Think of it like this:</p><pre>View appears<br>                         ↓<br>                  What kind of work?<br>                    /           \<br>             Synchronous      Asynchronous<br>                 ↓                  ↓<br>           `.onAppear`           `.task`<br>                                      ↓<br>                           Depends on changing value?<br>                              /              \<br>                            No                Yes<br>                            ↓                  ↓<br>                         `.task`          `.task(id:)`</pre><h3>Common Interview Questions</h3><p>This topic also comes up frequently in SwiftUI interviews.</p><h3>1. What is the difference between .onAppear and .task?</h3><p>.onAppear executes a synchronous closure when the view appears. .task runs asynchronous work associated with the view and can be automatically cancelled by SwiftUI when the view disappears before the task completes.</p><h3>2. Why would you use .task for an API call?</h3><p>Because an API call is asynchronous, and .task provides an asynchronous context where await can be used directly. It also gives the task a lifecycle relationship with the view.</p><h3>3. What happens when a .task is cancelled?</h3><p>Cancellation is cooperative. SwiftUI requests cancellation, but the asynchronous operation must respond to cancellation appropriately. Task.checkCancellation() is one way to explicitly check for cancellation.</p><h3>4. What is .task(id:)?</h3><p>It is a variant of .task that observes an Equatable value. When that value changes, SwiftUI cancels the existing task and starts a new one.</p><h3>5. Is .task exactly the same as viewDidLoad()?</h3><p>No.</p><p>SwiftUI’s view model is different from UIKit’s view-controller lifecycle. A SwiftUI view is a value describing UI, so you should not treat .task as a direct equivalent of viewDidLoad().</p><p>Instead, think of .task as a way to attach asynchronous work to the lifetime and identity of a SwiftUI view.</p><h3>6. Should I always replace .onAppear with .task?</h3><p>No.</p><p>Use the modifier that matches the work. .onAppear is perfectly appropriate for synchronous appearance-related actions. .task is designed for asynchronous work.</p><h3>Final Takeaway</h3><p>.onAppear and .task are not competing modifiers. They solve related but different problems.</p><p>Use .onAppear when you need to perform a simple synchronous action when a view appears.</p><p>Use .task when you need to perform asynchronous work that should be associated with the view&#39;s lifetime.</p><p>Use .task(id:) when that asynchronous work depends on a value that can change and should restart when that value changes.</p><p>The easiest way to remember it is:</p><pre>Synchronous action      → .onAppear<br>Asynchronous work       → .task<br>Async work + changing ID → .task(id:)</pre><p>Once you understand the lifecycle and cancellation behavior behind these modifiers, the choice becomes much simpler — and you also avoid creating unnecessary Task instances inside .onAppear for work that is naturally suited to .task.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e36fcf879d01" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>