<?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 Sachin Goswami on Medium]]></title>
        <description><![CDATA[Stories by Sachin Goswami on Medium]]></description>
        <link>https://medium.com/@itsachin523?source=rss-c73a45314d68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YWIQsUCsKrqOIAZ59Frgnw.jpeg</url>
            <title>Stories by Sachin Goswami on Medium</title>
            <link>https://medium.com/@itsachin523?source=rss-c73a45314d68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:20:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itsachin523/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[Why SwiftUI LazyVStack Can Become a Silent Memory Killer]]></title>
            <link>https://medium.com/@itsachin523/why-swiftui-lazyvstack-can-become-a-silent-memory-killer-c0a6557111e5?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0a6557111e5</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[lazyvstack]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 23:24:23 GMT</pubDate>
            <atom:updated>2026-09-14T16:17:22.075Z</atom:updated>
            <content:encoded><![CDATA[<p>Most iOS developers eventually replace VStack with LazyVStack when building large scrolling feeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLBPFm4fT_NeOzxWE1YLdA.png" /></figure><p>It feels like the obvious optimization.</p><p>After all, the word <em>“Lazy”</em> suggests that views will be created only when needed and removed when they are no longer visible.</p><p>But there is an important detail many developers discover only after seeing memory spikes in production:</p><p><strong>LazyVStack is lazy in creating views, not in releasing them.</strong></p><p>If your feed contains large images, video players, or heavy view models, memory usage can grow continuously as users scroll through content.</p><h3>The Situation Every iOS Developer Faces</h3><p>Imagine you’re building:</p><ul><li>A social media feed</li><li>A movie catalog</li><li>An e-commerce product grid</li><li>A photo gallery</li></ul><p>You switch from VStack to LazyVStack expecting memory usage to stay stable.</p><p>Everything looks fine at first.</p><p>Then you profile the app using Instruments and notice something strange:</p><ul><li>Memory starts at 120 MB</li><li>After scrolling for a while it reaches 500 MB</li><li>A few hundred items later it crosses 1 GB</li></ul><p>Even worse, scrolling back to the top doesn’t reduce memory consumption.</p><p>Eventually iOS terminates the application because of memory pressure.</p><p>The question becomes:</p><p><strong>Why isn’t LazyVStack cleaning up off-screen views?</strong></p><h3>Understanding the Common Misconception</h3><p>Many developers come from UIKit and naturally compare LazyVStack to UICollectionView.</p><p>In UIKit, cells are recycled.</p><p>When a cell moves off-screen:</p><ol><li>The cell enters a reuse pool.</li><li>Its memory is reused for new content.</li><li>The total number of active cells remains relatively constant.</li></ol><p>This is why a collection view can display thousands of items without significant memory growth.</p><p>SwiftUI works differently.</p><p>When an item appears inside a LazyVStack, SwiftUI creates and stores the view&#39;s state.</p><p>As additional items become visible, more state is added.</p><p>When those items move off-screen, SwiftUI may stop rendering them, but their associated state often remains alive.</p><p>The result is a memory footprint that grows alongside the amount of content a user has viewed.</p><h3>Why SwiftUI Keeps Views Alive</h3><p>This behavior is not a bug.</p><p>It is actually part of SwiftUI’s design philosophy.</p><p>SwiftUI prioritizes state preservation.</p><p>Imagine a row containing:</p><ul><li>User-entered text</li><li>Toggle selections</li><li>Expanded sections</li><li>Media playback positions</li></ul><p>If SwiftUI destroyed everything the moment a view left the screen, users would experience:</p><ul><li>Lost input</li><li>Reset controls</li><li>Broken animations</li><li>Poor scrolling experiences</li></ul><p>To avoid this, SwiftUI retains view state for content that has already been displayed.</p><p>The trade-off is increased memory usage when views hold heavy resources.</p><h3>The Real Problem: Heavy Objects in State</h3><p>The biggest memory issues appear when developers store large objects directly inside view state.</p><p>Examples include:</p><ul><li>UIImage</li><li>Video players</li><li>Audio buffers</li><li>Large data caches</li></ul><p>A single high-resolution image can consume tens of megabytes after decoding.</p><p>Multiply that across hundreds of rows and memory usage grows rapidly.</p><p>Many developers focus on network size while overlooking decoded memory size.</p><p>A 4 MB JPEG downloaded from a server can easily expand into 30+ MB once decoded in memory.</p><p>That’s where the real danger begins.</p><h3>Myth #1: AsyncImage Solves Everything</h3><p>AsyncImage is useful for downloading and displaying remote images.</p><p>However, it is not a complete memory management solution.</p><p>Once an image has been downloaded and decoded, memory is still required to render that bitmap.</p><p>In large feeds containing hundreds of images, memory usage can still become significant.</p><p>Using AsyncImage alone does not guarantee a stable memory footprint.</p><h3>Myth #2: Forcing View Refreshes Fixes Memory</h3><p>Some developers attempt to reset the entire LazyVStack using changing IDs or aggressive refresh logic.</p><p>While this may temporarily reduce memory usage, it introduces new problems:</p><ul><li>Scroll position resets</li><li>UI flickering</li><li>Poor user experience</li><li>Additional rendering costs</li></ul><p>This approach treats the symptom rather than solving the root cause.</p><h3>Practical Solutions for Production Apps</h3><h3>1. Downsample Images Before Displaying Them</h3><p>This is often the biggest win.</p><p>If a thumbnail is displayed at 150×150 points, there is rarely a reason to decode a full-resolution camera image.</p><p>Instead:</p><ul><li>Decode images at display size</li><li>Use ImageIO for downsampling</li><li>Avoid loading unnecessary pixels</li></ul><p>Reducing image dimensions can dramatically lower memory consumption while maintaining visual quality.</p><p>For image-heavy applications, this optimization alone can prevent crashes.</p><h3>2. Release Expensive Resources When They Leave the Screen</h3><p>Not every piece of state needs to live forever.</p><p>Resources such as:</p><ul><li>Video decoders</li><li>AVPlayers</li><li>Large caches</li><li>Audio processing objects</li></ul><p>should be released when content becomes invisible.</p><p>Using lifecycle events like onDisappear allows heavy objects to be cleaned up proactively.</p><p>This ensures memory remains bounded even during extended scrolling sessions.</p><h3>3. Take Advantage of Visibility APIs</h3><p>Modern versions of SwiftUI provide better visibility tracking.</p><p>These APIs allow developers to determine whether content is currently visible to users.</p><p>When an item disappears:</p><ul><li>Pause playback</li><li>Stop processing</li><li>Clear temporary resources</li><li>Reduce memory consumption</li></ul><p>This approach aligns resource usage with what the user can actually see.</p><h3>When SwiftUI Isn’t the Best Tool</h3><p>SwiftUI is excellent for most applications.</p><p>However, some products have unique requirements:</p><ul><li>Infinite video feeds</li><li>TikTok-style experiences</li><li>Instagram-scale media grids</li><li>Thousands of rapidly changing cells</li></ul><p>In these scenarios, UIKit’s battle-tested recycling mechanisms may still offer advantages.</p><p>Using UICollectionView through UIViewControllerRepresentable is not a step backward.</p><p>It is often the right engineering decision when predictable memory behavior is critical.</p><h3>Key Lessons</h3><p>Before shipping any large scrolling interface, remember these principles:</p><p>✅ LazyVStack delays view creation but does not guarantee view recycling.</p><p>✅ Large images are one of the most common causes of memory growth.</p><p>✅ Store lightweight references such as URLs instead of large decoded bitmaps whenever possible.</p><p>✅ Release expensive resources when views leave the screen.</p><p>✅ Downsampling images can dramatically reduce memory consumption.</p><p>✅ For extremely demanding media feeds, consider using UICollectionView.</p><h3>Final Thoughts</h3><p>LazyVStack is an incredibly powerful tool, but understanding its memory behavior is essential for building scalable applications.</p><p>The biggest mistake isn’t using LazyVStack.</p><p>The biggest mistake is assuming it behaves like UICollectionView.</p><p>Once you understand the difference between <strong>lazy creation</strong> and <strong>memory retention</strong>, you can design feeds that remain fast, responsive, and stable — even when users scroll through thousands of items.</p><p>A smooth user experience isn’t just about rendering performance.</p><p>It’s also about controlling memory before the operating system decides to do it for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0a6557111e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Concurrency: Write Less Code, Do More Work, Ship Better Apps]]></title>
            <link>https://medium.com/@itsachin523/swiftui-concurrency-write-less-code-do-more-work-ship-better-apps-83da03050e0f?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/83da03050e0f</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Wed, 20 May 2026 15:59:02 GMT</pubDate>
            <atom:updated>2026-05-20T15:59:02.274Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Concurrency is not just about speed. It’s about structure, safety, and scalability.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMR0DElR8etrmTI792bg2Q.png" /></figure><h3>Introduction</h3><p>If you’ve ever watched a loading spinner freeze your UI or wrestled with completion handlers nested five levels deep, you already know the pain that Swift Concurrency was built to solve.</p><p>Modern iOS apps are expected to be fast, smooth, and responsive—all at the same time. Users don’t wait. They swipe away. And every janky frame, every frozen button, and every delayed response chips away at trust in your app.</p><p>Swift Concurrency—built into SwiftUI—gives you a set of powerful tools to write asynchronous code that reads like synchronous code, protects shared state from corruption, and keeps your UI thread free to do what it does best: render beautiful interfaces.</p><p>In this post, we’ll walk through the <strong>7 core pillars of SwiftUI Concurrency</strong>, explore real code examples, and wrap up with best practices you can apply today.</p><h3>What Is Concurrency in Simple Words?</h3><p>Break big work into small, independent tasks that can run at the same time.</p><p>Instead of this:</p><pre>Request → Wait → Wait → Wait → Complete</pre><p>You get this:</p><pre>Request → Do Work (Concurrently) → Complete</pre><p>More work done. Less waiting. Happier users.</p><h3>The 4 Core Benefits</h3><p>Before diving into the pillars, here’s what Swift Concurrency gives you at a glance:</p><p>Benefit What It Means 🚀 <strong>Blazing Fast</strong> Do more in less time with parallel execution 🛡️ <strong>Data Safe</strong> Protect shared state using Actors 🧹 <strong>Cleaner Code</strong> Write less, express more with async/await ✨ <strong>Better UX</strong> Smooth, responsive, and user-first apps</p><h3>Pillar 1: Async / Await</h3><p>The foundation of Swift Concurrency. Write asynchronous code that reads like synchronous code.</p><pre>func loadPosts() async throws -&gt; [Post] {<br>    let url = URL(string: endpoint)!<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return try JSONDecoder().decode([Post].self, from: data)<br>}</pre><p><strong>Key tips:</strong></p><ul><li>Use await for every async call — it tells Swift to suspend here and resume later</li><li>Always handle errors with do-catch when using try await</li><li>Functions marked async can only be called from async contexts or with Task {}</li></ul><p>No more completion handler pyramids. No more callback hell. Just clear, top-to-bottom code.</p><h3>Pillar 2: Structured Concurrency</h3><p>Organize tasks in a hierarchy. When the parent ends, its children are automatically canceled.</p><pre>async let a = fetchA()<br>async let b = fetchB()<br>async let c = fetchC()<br>let result = await (a, b, c)</pre><p>Think of it like a <strong>task tree</strong>:</p><pre>Parent Task<br>├── Child Task A<br>├── Child Task B<br>└── Child Task C</pre><p>If the parent is cancelled or throws an error, every child is cleaned up automatically. This gives you <strong>safer resource management</strong> and prevents common bugs like dangling network requests after a view disappears.</p><h3>Pillar 3: Actors</h3><p>Protect shared mutable state and eliminate data races — one of the most insidious bugs in concurrent programming.</p><pre>actor Counter {<br>    private var value = 0<br>    func increment() { value += 1 }<br>    func current() -&gt; Int { value }<br>}</pre><pre>let counter = Counter()<br>await counter.increment()<br>let v = await counter.current()</pre><p>Actors are reference types — like classes — but with a superpower: <strong>only one task can access an actor’s state at a time</strong>. Swift enforces this at compile time, so data races become a compiler error, not a runtime crash.</p><h3>Pillar 4: Tasks</h3><p>Create independent units of work that run concurrently.</p><pre>let task = Task {<br>    let data = try await fetchData()<br>    await MainActor.run {<br>        self.items = data<br>    }<br>}</pre><pre>// Cancel anytime:<br>// task.cancel()</pre><p>Tasks are ideal for:</p><ul><li>Background jobs (syncing, fetching)</li><li>One-off async work triggered by user actions</li><li>UI actions that need async results</li></ul><p>And when you no longer need the work, task.cancel() cooperatively stops it.</p><h3>Pillar 5: Task Groups</h3><p>Run multiple tasks concurrently and collect their results — the fan-out/fan-in pattern.</p><pre>try await withThrowingTaskGroup(of: Item.self) { group in<br>    for id in ids {<br>        group.addTask { try await fetch(id: id) }<br>    }<br>    var results: [Item] = []<br>    for try await item in group {<br>        results.append(item)<br>    }<br>    return results<br>}</pre><p>Instead of fetching items one by one (serial), Task Groups let you fetch all of them simultaneously (parallel) and collect the results as they complete. This can dramatically reduce total loading time for large data sets.</p><p><strong>Perfect for:</strong> loading lists, fetching multiple resources, parallel image downloads.</p><h3>Pillar 6: Cancellation</h3><p>Cancellation is <strong>cooperative</strong> in Swift. That means your code needs to check for it and respond.</p><pre>func longOperation() async {<br>    for i in 0..&lt;1000 {<br>        try Task.checkCancellation()<br>        // do heavy work<br>    }<br>}</pre><p>Task.checkCancellation() throws a CancellationError if the current task has been cancelled, allowing you to exit cleanly. You can also use Task.isCancelled for a non-throwing check.</p><p><strong>Always check for cancellation in long-running loops</strong> — otherwise your task keeps running even after the user has navigated away, wasting CPU and battery.</p><h3>Pillar 7: MainActor</h3><p>Update UI on the main thread safely and explicitly.</p><pre>@MainActor<br>class ViewModel: ObservableObject {<br>    @Published var items: [Item] = []</pre><pre>    func load() async {<br>        let data = await fetchItems()<br>        items = data // safe for UI<br>    }<br>}</pre><p>The @MainActor annotation guarantees that this class&#39;s code always runs on the main thread — the only thread where UIKit and SwiftUI updates are safe. No more DispatchQueue.main.async {} scattered throughout your code.</p><p>You can also annotate individual methods with @MainActor if you only need specific functions to run on the main thread.</p><h3>Best Practices at a Glance</h3><p>Practice Why It Matters ✅ Prefer structured concurrency over detached tasks Automatic cancellation and cleanup ✅ Use actors for shared mutable state Eliminates data races at compile time ✅ Keep async functions small and focused. Easier to test, reason about, and compose. ✅ Handle errors and cancellation thoughtfully Prevents resource leaks and crashes ✅ Measure, profile, and optimize continuously Concurrency bugs can be subtle</p><h3>Common Keywords Cheat Sheet</h3><pre>async / await    →  Mark and call asynchronous functions<br>Task             →  Spawn a unit of async work<br>TaskGroup        →  Run and collect multiple concurrent tasks<br>Actor            →  Protect shared mutable state<br>MainActor        →  Ensure execution on the main thread<br>Sendable         →  Mark types safe to send across concurrency boundaries<br>Cancellation     →  Cooperatively stop running tasks<br>Isolation        →  Control which actor owns a piece of state</pre><h3>Key Takeaway</h3><p>Swift Concurrency makes your code more readable, your app more responsive, and your users happier.</p><p>The concepts might feel unfamiliar at first—but they&#39;re built around one idea: <strong>let the system manage threading so you can focus on logic</strong>.</p><blockquote><strong><em>Think in tasks, not threads.</em></strong><em> </em><strong><em>Keep work off the main thread.</em></strong><em> </em><strong><em>Let the system manage the rest.</em></strong></blockquote><p>Master it once, and benefit forever.</p><p><strong>Think Concurrent. Build Better.</strong></p><h3>Further Reading</h3><ul><li><a href="https://developer.apple.com/documentation/swift/concurrency">Swift Concurrency Documentation — Apple</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2021/10132/">WWDC21: Meet async/await in Swift</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2021/10133/">WWDC21: Protect mutable state with Swift actors</a></li><li><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0296-async-await.md">SE-0296: Async/await proposal</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83da03050e0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Centralized MVVM-based navigation in SwiftUI Using NavigationStack & NavigationPath]]></title>
            <link>https://medium.com/@itsachin523/centralized-mvvm-based-navigation-in-swiftui-using-navigationstack-navigationpath-a150461bee42?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/a150461bee42</guid>
            <category><![CDATA[centralized]]></category>
            <category><![CDATA[navigationpath]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[navigation-stack]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 19:11:31 GMT</pubDate>
            <atom:updated>2026-02-09T19:11:31.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Navigation is one of the most important parts of any iOS application.<br>As applications grow, handling navigation using NavigationLink everywhere quickly becomes <strong>messy, tightly coupled, and hard to scale</strong>.</p><p>With <strong>SwiftUI’s NavigationStack and NavigationPath</strong>, Apple finally gave us a <strong>modern, programmatic, and scalable navigation system</strong>.</p><p>In this article, we’ll build a <strong>simple demo application</strong> using:</p><ul><li>MVVM architecture</li><li>NavigationStack &amp; NavigationPath</li><li>Centralized navigation (Router / Coordinator)</li><li>Bottom Tab Bar</li><li>Push, Pop &amp; Pop-to-Root</li><li>Data passing between screens</li></ul><p>This pattern is <strong>production-ready</strong> and commonly used in <strong>banking, enterprise, and large-scale applications</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfDA2sL2LIbdlgp0Vx62eg.png" /></figure><h3>Why Not Use NavigationLink Directly?</h3><p>NavigationLink works well for small demos, but in real-world apps it causes problems:</p><ul><li>Navigation logic lives inside Views</li><li>Hard to trigger navigation from business logic</li><li>Difficult to support deep linking</li><li>Not test-friendly</li><li>Breaks MVVM separation</li></ul><p><strong>Solution:</strong><br>Use NavigationStack with a <strong>central router</strong> and let <strong>ViewModels control navigation intent</strong>.</p><h3>Architecture Overview (MVVM + Router)</h3><p>We follow a <strong>clean MVVM structure</strong>:</p><pre>View → ViewModel → Router → NavigationStack</pre><h3>Responsibilities Breakdown</h3><p><strong>View → UI rendering only<br>ViewModel → Business logic + navigation intent<br>Router → Push / Pop / Reset navigation<br>Model -&gt; Data layer</strong></p><p>Each tab maintains <strong>its own NavigationStack</strong>, which means:</p><ul><li>Switching tabs does <strong>not reset navigation</strong></li><li>Each flow remains independent</li></ul><h3>Step 1: Define App Routes (Type-Safe Navigation)</h3><p>Instead of hardcoding destinations, we define all routes in one place.</p><pre>enum AppRoute: Hashable {<br>    case homeDetail(title: String)<br>    case profileDetail(userId: Int)<br>}</pre><h3>Why this matters</h3><ul><li>Type-safe navigation</li><li>Central source of truth</li><li>Easy to maintain and scale</li><li>Ideal for deep linking</li></ul><h3>Step 2: Central Router (Navigation Manager)</h3><p>The router owns all navigation paths and exposes push/pop APIs.</p><pre>final class AppRouter: ObservableObject {<br>    @Published var homePath = NavigationPath()<br>    @Published var profilePath = NavigationPath()<br>    <br>    // MARK: - Push<br>    func pushHome(_ route: AppRoute) {<br>        homePath.append(route)<br>    }<br>    <br>    func pushProfile(_ route: AppRoute) {<br>        profilePath.append(route)<br>    }<br>    <br>    // MARK: - Pop<br>    func popHome() {<br>        guard !homePath.isEmpty else { return }<br>        homePath.removeLast()<br>    }<br>    <br>    func popToHomeRoot() {<br>        homePath.removeLast(homePath.count)<br>    }<br>}</pre><p><strong>Key Idea:</strong></p><ul><li><em>Views never push or pop directly.</em></li><li><em>Navigation is handled centrally.</em></li></ul><h3>Step 3: Root View with Bottom Tab Bar</h3><p>Each tab has its own navigation flow.</p><pre>struct RootView: View {<br>    @StateObject private var router = AppRouter()<br>    <br>    var body: some View {<br>        TabView {<br>            HomeNavigation()<br>                .tabItem {<br>                    Label(&quot;Home&quot;, systemImage: &quot;house&quot;)<br>                }<br>            <br>            ProfileNavigation()<br>                .tabItem {<br>                    Label(&quot;Profile&quot;, systemImage: &quot;person&quot;)<br>                }<br>        }<br>        .environmentObject(router)<br>    }<br>}</pre><ul><li>Router is injected once</li><li>Shared across the app</li><li>Clean and scalable</li></ul><h3>Step 4: NavigationStack for Home Tab</h3><pre>struct HomeNavigation: View {<br>    @EnvironmentObject var router: AppRouter<br>    <br>    var body: some View {<br>        NavigationStack(path: $router.homePath) {<br>            HomeView(<br>                viewModel: HomeViewModel(router: router)<br>            )<br>            .navigationDestination(for: AppRoute.self) { route in<br>                switch route {<br>                case .homeDetail(let title):<br>                    HomeDetailView(title: title)<br>                default:<br>                    EmptyView()<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>NavigationPath allows:</p><ul><li>Programmatic navigation</li><li>Pop to root</li><li>Deep linking support</li></ul><h3>Step 5: ViewModel (Correct MVVM Navigation)</h3><pre>final class HomeViewModel: ObservableObject {<br>    private let router: AppRouter<br>    <br>    init(router: AppRouter) {<br>        self.router = router<br>    }<br>    <br>    func openDetail() {<br>        router.pushHome(.homeDetail(title: &quot;SwiftUI MVVM Demo&quot;))<br>    }<br>}</pre><p><strong>Important Principle</strong></p><ul><li><em>ViewModels decide </em>when<em> to navigate</em></li><li><em>Routers decide </em>how<em> to navigate</em></li><li><em>Views just react</em></li></ul><h3>Step 6: View (UI Only)</h3><pre>struct HomeView: View {<br>    @ObservedObject var viewModel: HomeViewModel<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(&quot;Home Screen&quot;)<br>                .font(.title)<br>            <br>            Button(&quot;Go to Detail&quot;) {<br>                viewModel.openDetail()<br>            }<br>        }<br>        .navigationTitle(&quot;Home&quot;)<br>    }<br>}</pre><ul><li>No navigation logic</li><li>Easy to test</li><li>Reusable UI</li></ul><h3>Step 7: Detail Screen (Pop &amp; Reset)</h3><pre>struct HomeDetailView: View {<br>    let title: String<br>    @EnvironmentObject var router: AppRouter<br>    <br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(title)<br>                .font(.title)<br>            <br>            Button(&quot;Back&quot;) {<br>                router.popHome()<br>            }<br>            <br>            Button(&quot;Pop to Root&quot;) {<br>                router.popToHomeRoot()<br>            }<br>        }<br>        .navigationTitle(&quot;Detail&quot;)<br>    }<br>}</pre><h3>Benefits of This Pattern</h3><ul><li>Centralized navigation</li><li>MVVM compliant</li><li>Scales for large apps</li><li>Supports deep linking</li><li>Easy to test</li></ul><h3>Final Thoughts</h3><p>SwiftUI navigation becomes <strong>clean, predictable, and scalable</strong> when combined with:</p><ul><li>MVVM architecture</li><li>NavigationStack</li><li>Centralized routing</li></ul><p>This pattern works extremely well for <strong>banking, enterprise, and production-level apps</strong>.</p><p><strong>Thank you</strong> for reading until the end. Before you go:</p><p>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</p><p>Follow me on <a href="https://www.linkedin.com/in/sachin-goswami-0b827b122/"><strong>LinkedIn</strong></a><strong> for more updates.</strong></p><p>Happy Coding 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a150461bee42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find Unused Images in Your iOS Project in Minutes with a Script]]></title>
            <link>https://medium.com/@itsachin523/find-unused-images-in-your-ios-project-in-minutes-with-a-script-acb9f59dbc31?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb9f59dbc31</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[unused]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 10:16:53 GMT</pubDate>
            <atom:updated>2025-09-11T10:16:53.642Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked on iOS apps for a while, you know how easily <strong>unused images pile up</strong> in Assets.xcassets. Old icons, temporary graphics, or test placeholders often sit there doing nothing — except making your app heavier and slower to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*RjutkxecQwKIYM2sunvbjw.png" /></figure><p>Instead of manually checking each asset (which is painful for big projects), I use a simple <strong>Bash script</strong> that scans all image sets and compares them against the source code. 🚀</p><h3>Why It Matters</h3><ul><li><strong>Smaller app size</strong> → Users don’t want to download a heavy app filled with unused junk.</li><li><strong>Faster builds</strong> → Every file adds up; trimming them saves time during development.</li><li>️<strong>Cleaner codebase</strong> → Teams don’t waste time wondering if an asset is still in use.</li><li><strong>Professional polis</strong>h → Shipping a tidy project always feels better.</li></ul><p>I once deleted over <strong>50 unused images</strong> from a project, and the app size dropped by almost <strong>30 MB</strong>. That’s the kind of win both developers and end-users appreciate.</p><h3>The Script</h3><p>Create a file in your project root called <strong>find_unused_images.sh</strong> and add this code:</p><pre>#!/bin/bash<br># --------------------------------------<br># Script to find unused images in Xcode project (recursive)<br># --------------------------------------<br># Path to your project<br>PROJECT_PATH=&quot;$(pwd)&quot;<br>ASSETS_PATH=&quot;$PROJECT_PATH/YourApp/Assets.xcassets&quot;   # &lt;-- Replace &#39;YourApp&#39; with your folder name<br>echo &quot;🔎 Scanning for unused images in: $ASSETS_PATH&quot;<br>echo &quot;&quot;<br># Loop through all .imageset folders<br>for image in $(find &quot;$ASSETS_PATH&quot; -name &quot;*.imageset&quot;); do<br>    imageName=$(basename &quot;$image&quot; .imageset)<br>    # Search recursively in Swift, ObjC, Storyboard, and XIB files<br>    usage=$(grep -R --include=&quot;*.swift&quot; --include=&quot;*.m&quot; --include=&quot;*.mm&quot; --include=&quot;*.h&quot; \<br>                --include=&quot;*.storyboard&quot; --include=&quot;*.xib&quot; \<br>                --exclude-dir=Assets.xcassets \<br>                &quot;$imageName&quot; &quot;$PROJECT_PATH&quot;)<br>    # If no usage found, mark it as unused<br>    if [ -z &quot;$usage&quot; ]; then<br>        echo &quot;🚨 Unused image: $imageName&quot;<br>    fi<br>done<br>echo &quot;&quot;<br>echo &quot;✅ Done scanning.&quot;</pre><h3>How to Run It</h3><ol><li>Make it executable:</li></ol><pre>chmod +x find_unused_images.sh</pre><p>2. Run the script:</p><pre>./find_unused_images.sh</pre><p>If an image isn’t used anywhere in your codebase, you’ll see output like:</p><pre>🚨 Unused image: ic_oldArrow<br>🚨 Unused image: temp_bg</pre><h3>Limitations</h3><p>Like any script, this isn’t perfect.</p><ul><li>It won’t catch <strong>dynamic image names</strong> (e.g. UIImage(named: &quot;icon_\(type)&quot;)).</li><li>Some Storyboard images may still sneak through.</li><li>There’s always a small risk of false positives.</li></ul><p>That’s why I always recommend running this script and then <strong>double-checking</strong> before actually deleting assets. And of course, <strong>use Git</strong> so you can roll back if something breaks.</p><h3>Final Thoughts</h3><p>This little script has saved me hours of manual searching and helped keep projects clean. It’s a quick win:</p><ul><li>Smaller app size</li><li>Faster build times</li><li>A codebase that feels lighter and easier to maintain</li></ul><p>It’s one of those things that doesn’t take long to set up but pays off every time you run it.</p><p>👉 Try it in your project and see what you discover. How many unused images do you think are hiding in your asset catalog right now?</p><p><strong>Thank you</strong> for reading until the end. Before you go:</p><p>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</p><p>Follow me on <a href="https://www.linkedin.com/in/sachin-goswami-0b827b122/"><strong>LinkedIn</strong></a><strong> for more updates.</strong></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb9f59dbc31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static vs Dynamic Libraries in iOS Projects: A Complete Guide]]></title>
            <link>https://medium.com/@itsachin523/static-vs-dynamic-libraries-in-ios-projects-a-complete-guide-3eba1f15e4ac?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eba1f15e4ac</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[static]]></category>
            <category><![CDATA[dynamics]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 05:09:01 GMT</pubDate>
            <atom:updated>2025-07-07T05:09:01.902Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing iOS applications, understanding the differences between static and dynamic libraries is crucial for optimizing your app’s performance, size, and maintainability. This guide will explore both types of libraries, their advantages and disadvantages, and when to use each in your iOS projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*3pMHxXG1atAhBCZbIDTKCA.png" /></figure><h3>What Are Libraries in iOS Development?</h3><p>Libraries are collections of reusable code that can be shared across multiple applications. In iOS development, they help:</p><ul><li>Reduce code duplication</li><li>Improve modularity</li><li>Speed up compilation times</li><li>Enable code sharing between apps</li></ul><h3>Static Libraries</h3><h4>Definition</h4><p>Static libraries (.a files) are collections of object files that are linked directly into your app&#39;s binary at compile time. The code becomes part of your executable.</p><h4>Characteristics</h4><ul><li>Linking: Occurs during compile time</li><li>File Extension: .a (or sometimes .framework when bundled with headers/resources)</li><li>Memory Usage: Code is duplicated in each process using it</li><li>Size Impact: Increases the size of your binary</li><li>Loading Time: Loads immediately with the app</li></ul><h4>Advantages</h4><ol><li>Faster launch times (no dynamic linking overhead)</li><li>No dependency management at runtime</li><li>Better performance for frequently called code</li><li>More control over included code</li><li>Easier distribution (everything is self-contained)</li></ol><h4>Disadvantages</h4><ol><li>Larger app size (code is duplicated in each binary)</li><li>No sharing between processes</li><li>Requires recompilation for updates</li><li>Harder to update (requires app store submission)</li></ol><h4>Creating a Static Library in Xcode</h4><ol><li>File → New → Target</li><li>Select “Static Library” under Framework &amp; Library</li><li>Add your implementation files</li><li>Build the target to generate the .a file</li></ol><h3>Dynamic Libraries</h3><h4>Definition</h4><p>Dynamic libraries (.dylib files, or .framework bundles) are linked at runtime rather than compile time. The code exists as a separate file that&#39;s loaded when needed.</p><h4>Characteristics</h4><ul><li>Linking: Occurs at runtime</li><li>File Extension: .dylib or .framework</li><li>Memory Usage: Shared between processes</li><li>Size Impact: Smaller main binary</li><li>Loading Time: Slight overhead when first loaded</li></ul><h4>Advantages</h4><ol><li>Smaller app size (code is shared)</li><li>Memory efficiency (shared between processes)</li><li>Can be updated without recompiling the main app</li><li>Better for large codebases (reduces binary size)</li><li>Supports plugins/extensions</li></ol><h4>Disadvantages</h4><ol><li>Slower initial load (dynamic linking overhead)</li><li>Dependency management required</li><li>More complex distribution (need to include the library)</li><li>Potential versioning issues</li><li>App Store restrictions (limited use in iOS)</li></ol><h4>Creating a Dynamic Framework in Xcode</h4><ol><li>File → New → Target</li><li>Select “Framework” under Framework &amp; Library</li><li>Add your implementation files</li><li>Build the target to generate the .framework bundle</li></ol><h3>When to Use Each</h3><h4><strong>Use Static Libraries When:</strong></h4><ul><li>You need maximum performance</li><li>You’re developing a self-contained app</li><li>You want to minimize runtime dependencies</li><li>You’re using private code not shared between apps</li><li>You need to support older iOS versions</li></ul><h4>Use Dynamic Libraries When:</h4><ul><li>You’re sharing code between multiple apps</li><li>You need to reduce your main binary size</li><li>You want to enable plugins/extensions</li><li>You need to update code without app store submission (for enterprise/internal apps)</li><li>You’re developing a large, modular application</li></ul><h3>Conclusion</h3><p>Choosing between static and dynamic libraries in iOS depends on your specific needs. While static libraries offer better performance and simpler distribution, dynamic libraries provide memory efficiency and modularity. With Apple’s restrictions on dynamic libraries in App Store apps, static libraries remain the default choice for most iOS developers, but understanding both types will help you make informed architectural decisions for your projects.</p><p><strong>Thank you</strong> for reading until the end. Before you go:</p><p>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</p><p>Follow me on <a href="https://www.linkedin.com/in/sachin-goswami-0b827b122/"><strong>LinkedIn</strong></a><strong> for more updates.</strong></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eba1f15e4ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Show a Countdown Timer in Every UITableViewCell in Swift (Efficiently!)]]></title>
            <link>https://medium.com/@itsachin523/how-to-show-a-countdown-timer-in-every-uitableviewcell-in-swift-efficiently-b5df9cb4ab7e?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5df9cb4ab7e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[timer]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Fri, 16 May 2025 12:55:35 GMT</pubDate>
            <atom:updated>2025-05-16T12:55:35.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Displaying a countdown timer in a list is a common feature in many apps — for example, tracking time left in a flash sale, an auction, or a quiz. Recently, I faced a similar challenge where <strong>each row in a </strong><strong>UITableView</strong> needed to show its own countdown timer, and I wanted to share how I solved it efficiently using Swift and UIKit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*fi9GWg-Y8LfjSCzp5vMqhQ@2x.png" /></figure><h3>The Naive Approach (What Not to Do)</h3><p>At first, I thought about adding a Timer directly in each UITableViewCell. It seemed easy: start a timer in cellForRowAt, and stop it when the cell disappears.</p><p>But this quickly led to problems:</p><ul><li>📉 <strong>Performance issues</strong>: Too many timers running at once.</li><li>🔁 <strong>Incorrect timer values</strong> due to cell reuse (cells recycle as you scroll).</li><li>💥 <strong>Memory overhead</strong>: Each timer consumes system resources, and cells don’t manage memory well when timers are added per instance.</li></ul><p>So I needed a better way…</p><h3>The Smart and Scalable Approach</h3><p>Instead of using multiple timers, I used <strong>a single </strong><strong>Timer in the ViewController</strong> that ticks once per second. Here&#39;s how it works:</p><h3>Key Concepts:</h3><ul><li>A <strong>central timer</strong> fires every 1 second.</li><li>Only <strong>visible cells</strong> are updated — improving performance.</li><li>Each cell calculates the <strong>remaining time</strong> using:</li><li>A saved startTime (Date)</li><li>A duration (how long the countdown should last)</li></ul><h3>Why This Works:</h3><ul><li>No need to manage multiple timers.</li><li>Cell reuse is handled cleanly.</li><li>Smooth scrolling performance.</li><li>Memory-friendly — just one timer in the entire table.</li></ul><h3>Sample Implementation</h3><p>Here’s a simplified version of the logic:</p><h3>1. Model</h3><pre>struct TimerItem {<br>    let id: UUID<br>    let startTime: Date<br>    let duration: TimeInterval<br>}</pre><h3>2. View Controller Timer</h3><pre>class TimerTableViewController: UITableViewController {<br>    var timerItems: [TimerItem] = []<br>    var timer: Timer?<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        timerItems = loadSampleItems()<br>        startTimer()<br>    }<br><br>    func startTimer() {<br>        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in<br>            self.updateVisibleCells()<br>        }<br>    }<br>    func updateVisibleCells() {<br>        for cell in tableView.visibleCells {<br>            if let indexPath = tableView.indexPath(for: cell),<br>               let timerCell = cell as? TimerCell {<br>                let item = timerItems[indexPath.row]<br>                timerCell.updateTime(for: item)<br>            }<br>        }<br>    }<br>    deinit {<br>        timer?.invalidate()<br>    }<br>}</pre><h3>3. UITableViewCell</h3><pre>class TimerCell: UITableViewCell {<br>    @IBOutlet weak var timerLabel: UILabel!<br><br>    func updateTime(for item: TimerItem) {<br>        let elapsed = Date().timeIntervalSince(item.startTime)<br>        let remaining = max(0, item.duration - elapsed)<br>        timerLabel.text = format(remaining)<br>    }<br><br>    func format(_ time: TimeInterval) -&gt; String {<br>        let seconds = Int(time)<br>        let minutes = seconds / 60<br>        let sec = seconds % 60<br>        return String(format: &quot;%02d:%02d&quot;, minutes, sec)<br>    }<br>}</pre><h3>What Do You Think?</h3><p>This method works great for countdowns, quiz timers, or any time-sensitive data in lists.</p><p><strong>iOS developers — how do you handle timers in table views? Do you use a similar pattern or something different?</strong> I’d love to learn about your approach!</p><p><strong>Thank you</strong> for reading until the end. Before you go:</p><p>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</p><p>Follow me on <a href="https://www.linkedin.com/in/sachin-goswami-0b827b122/"><strong>LinkedIn</strong></a><strong> for more updates.</strong></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5df9cb4ab7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Modern Concurrency in Swift: A Beginner-Friendly Guide to Async/Await, Actors, Tasks…]]></title>
            <link>https://medium.com/@itsachin523/mastering-modern-concurrency-in-swift-a-beginner-friendly-guide-to-async-await-actors-tasks-60e9619cef68?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/60e9619cef68</guid>
            <category><![CDATA[actors]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[tasks]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 16:43:04 GMT</pubDate>
            <atom:updated>2025-04-21T16:43:04.330Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Modern Concurrency in Swift: A Beginner-Friendly Guide to Async/Await, Actors, Tasks, withTaskGroup and AsyncSequence</h3><p>Swift Concurrency introduces a powerful and intuitive way to handle asynchronous programming in iOS. Concepts like async, await, Task, actors, and others might seem a bit overwhelming at first, but once you understand how they work, they can make your code more readable, safe, and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZC6LU7k6J5stU_UtnFMEw.png" /></figure><p>In this blog post, we’ll walk through the core concurrency concepts in Swift with simple and easy-to-understand examples.</p><h3>1. async - Defining an Asynchronous Function</h3><p>An async function can perform asynchronous operations and must be called from an asynchronous context. It allows your function to suspend and resume later.</p><pre>// An async function that returns a string after a delay or async operation<br>func fetchData() async -&gt; String {<br>    return &quot;Data loaded&quot;<br>}</pre><h3>2. await - Waiting for an Async Result</h3><p>You use await to call an asynchronous function and wait for its result.</p><pre>Task {<br>    // Calling async function using await<br>    let result = await fetchData()<br>    print(result)<br>}</pre><h3>3. Task - Running Asynchronous Code</h3><p>You use Task to launch asynchronous code from a synchronous context.</p><pre>// Running async function from sync context using Task<br>Task {<br>    let data = await fetchData()<br>    print(&quot;Fetched inside Task: \(data)&quot;)<br>}</pre><p>You can also cancel a task if needed:</p><pre>// Creating a cancellable task<br>let task = Task {<br>    return await fetchData()<br>}<br>qtask.cancel() // Cancel the task if needed</pre><h3>4. async let - Running Multiple Async Calls in Parallel</h3><p>Use async let to run multiple asynchronous operations in parallel.</p><pre>// Fetching user profile and posts in parallel<br>func loadUserData() async {<br>    async let profile = fetchUserProfile() // async call 1<br>    async let posts = fetchUserPosts()     // async call 2<br><br>    let (user, userPosts) = await (profile, posts) // await both concurrently<br>    print(user, userPosts)<br>}</pre><h3>5. withTaskGroup - Dynamic Parallelism</h3><p>When you have a dynamic number of tasks, use withTaskGroup to run them concurrently and collect results.</p><pre>// Fetching multiple items concurrently with dynamic ids<br>func fetchMultipleItems(ids: [Int]) async {<br>    await withTaskGroup(of: String.self) { group in<br>        for id in ids {<br>            // Add a task for each ID<br>            group.addTask {<br>                return await fetchItem(id: id)<br>            }<br>        }<br><br>         // Iterate over results as they finish<br>        for await item in group {<br>            print(&quot;Received item: \(item)&quot;)<br>        }<br>    }<br>}</pre><h3>6. actor - Protecting Shared Mutable State</h3><p>Actors help prevent data races by isolating state.</p><pre>// Define an actor to manage a counter safely<br>actor Counter {<br>    var value = 0<br><br>    func increment() {<br>        value += 1<br>    }<br>}<br><br>let counter = Counter()<br>Task {<br>    await counter.increment() // Safe access using await<br>}</pre><h3>7. @MainActor - Running on the Main Thread</h3><p>To safely update the UI from async code, use @MainActor.</p><pre>// Mark the function to run on the main thread<br>@MainActor<br>func updateUI() {<br>    print(&quot;UI updated safely on main thread&quot;)<br>}<br><br>  Task {<br>    await updateUI() // Ensure UI updates happen on main thread<br>}</pre><h3>8. AsyncSequence - Working with Async Streams</h3><p>Use AsyncSequence to handle a sequence of values delivered over time.</p><pre>// Create a countdown sequence using AsyncStream<br>func countdown() -&gt; AsyncStream&lt;Int&gt; {<br>    return AsyncStream { continuation in<br>        for i in (1...5).reversed() {<br>            continuation.yield(i) // Emit each value<br>            sleep(1) // Simulate delay<br>        }<br>        continuation.finish() // Complete the stream<br>    }<br>}<br><br>Task {<br>    // Iterate through the async stream<br>    for await number in countdown() {<br>        print(&quot;Countdown: \(number)&quot;)<br>    }<br>}</pre><h3>9. Handling Errors in Async Functions</h3><p>Async functions can throw errors just like regular functions.</p><pre>// Define a custom error type<br>enum NetworkError: Error {<br>    case failed<br>}<br><br>// An async function that throws an error<br>func fetchResource() async throws -&gt; String {<br>    throw NetworkError.failed<br>}<br><br>Task {<br>    do {<br>        // Try to call the throwing async function<br>        let result = try await fetchResource()<br>        print(result)<br>    } catch {<br>        // Handle the error<br>        print(&quot;Error: \(error)&quot;)<br>    }<br>}</pre><h3>Conclusion</h3><p>Swift Concurrency offers a modern and powerful approach to asynchronous programming. Whether you’re fetching data, updating UI, or processing multiple tasks in parallel, these tools can help you write clearer and safer code.</p><p>Here’s a quick recap of what we covered:</p><ul><li>async &amp; await: For writing and calling async code</li><li>Task: For running async code from sync context</li><li>async let: For concurrent async operations</li><li>withTaskGroup: For dynamic parallelism</li><li>actor: For safe shared state</li><li>@MainActor: For main-thread UI updates</li><li>AsyncSequence: For async streams</li><li>throws + async: For error handling</li></ul><p>Keep experimenting with these concepts and try integrating them into your projects. You’ll love how clean and expressive your async code becomes!</p><p><strong>Thank you</strong> for reading until the end. Before you go:</p><p>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</p><p>Follow me on <a href="https://www.linkedin.com/in/sachin-goswami-0b827b122/"><strong>LinkedIn</strong></a><strong> for more updates.</strong></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60e9619cef68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding @MainActor in Swift: Ensuring Thread Safety in UI Code]]></title>
            <link>https://medium.com/@itsachin523/understanding-mainactor-in-swift-ensuring-thread-safety-in-ui-code-0e62fd332475?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e62fd332475</guid>
            <category><![CDATA[thread-safe]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mainactor]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Sat, 08 Feb 2025 07:38:32 GMT</pubDate>
            <atom:updated>2025-02-08T07:38:32.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift’s concurrency model makes handling asynchronous tasks much safer and more efficient, especially when dealing with UI updates. One key feature that helps with this is @MainActor. It ensures that code runs on the main thread, which is crucial for updating UI elements without running into threading issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*19fR2VFPogpb29wjxgZ9ag.png" /></figure><h3>What is @MainActor?</h3><p>@MainActor is a global actor in Swift that ensures tasks are executed on the main thread. This is important because UI updates in UIKit and SwiftUI must always happen on the main thread to avoid crashes or unexpected behavior.</p><h3>How to Use @MainActor</h3><p>You can use @MainActor in different ways—on functions, properties, or even entire classes—to make sure everything inside runs on the main thread.</p><h4>Using @MainActor on a Function</h4><pre>@MainActor<br>func updateUI() {<br>    print(Thread.isMainThread) // Always true<br>    // Update UI elements here<br>}</pre><h4>Using @MainActor on a Property</h4><pre>class ViewModel {<br>    @MainActor var title: String = &quot;Hello, Swift!&quot;<br>}</pre><p>This ensures that title is always accessed and modified on the main thread.</p><h4>Using @MainActor on a Class</h4><pre>@MainActor<br>class ViewModel {<br>    var title: String = &quot;Hello, Swift!&quot;<br>    func updateData() {<br>        // UI-related updates<br>    }<br>}</pre><p>Here, everything inside ViewModel will always run on the main thread.</p><h3>Why Use @MainActor?</h3><ul><li><strong>Ensures UI Safety</strong> — UI updates must happen on the main thread, and @MainActor guarantees that.</li><li><strong>Reduces Threading Issues</strong> — No need to manually switch to the main thread using DispatchQueue.main.async.</li><li><strong>Makes Code Cleaner</strong> — Less boilerplate code, making it easier to read and maintain.</li></ul><h3>Avoid Using DispatchQueue.main.async {}</h3><p>Before @MainActor, developers had to explicitly dispatch UI updates to the main queue:</p><pre>DispatchQueue.main.async {<br>    self.label.text = &quot;Updated Text&quot;<br>}</pre><p>While this approach works, it adds extra complexity and increases the risk of forgetting to switch back to the main thread. @MainActor eliminates this need by automatically ensuring that UI updates happen safely on the main thread.</p><h4>With @MainActor</h4><p>Now, this happens automatically:</p><pre>@MainActor<br>func updateUI(_ data: String) {<br>    print(&quot;Updating UI on main thread&quot;)<br>}</pre><p>This makes code cleaner, safer, and less error-prone.</p><h3>Using @MainActor with Async/Await</h3><p>When calling an @MainActor function from a background thread, Swift automatically ensures it runs on the main thread:</p><pre>func fetchData() async {<br>    let data = await fetchFromNetwork()<br>    await updateUI(data)<br>}<br><br>@MainActor<br>func updateUI(_ data: String) {<br>    // Safe UI updates<br>}</pre><h3>Things to Keep in Mind</h3><ul><li><strong>Don’t Overuse It</strong> — Marking an entire class with @MainActor might lead to unnecessary main-thread execution. Use it only where needed.</li><li><strong>Watch for Performance Issues</strong> — Running too much work on the main thread can slow down your app.</li><li><strong>Use Background Tasks When Needed</strong> — If something doesn’t need to be on the main thread, keep it in a background task.</li></ul><h3>Conclusion</h3><p>@MainActor makes UI thread management in Swift much easier. It helps prevent threading issues while reducing the need for extra code. By using it, you can avoid DispatchQueue.main.async {} and write cleaner, safer, and more efficient SwiftUI and UIKit applications.</p><p><strong>Thank you</strong> for reading until the end. Before you go:</p><p>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</p><p>Follow me on <a href="https://www.linkedin.com/in/sachin-goswami-0b827b122/"><strong>LinkedIn</strong></a><strong> for more updates.</strong></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e62fd332475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering State Management in SwiftUI (With Examples)]]></title>
            <link>https://medium.com/@itsachin523/mastering-state-management-in-swiftui-with-examples-66cacf08ef74?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/66cacf08ef74</guid>
            <category><![CDATA[state]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[binding]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 12:39:45 GMT</pubDate>
            <atom:updated>2024-12-22T12:39:45.071Z</atom:updated>
            <content:encoded><![CDATA[<p>A key component of developing interactive apps in SwiftUI is efficient state management. We’ll go over the fundamentals of state management with @State, @Binding, @StateObject, @ObservedObject, and @EnvironmentObject in this post. Knowing when to utilize each of these techniques will help your app become more efficient and well-organized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*zkUvR9ZpXHcjr-qqUmfI9A.png" /></figure><h3>Why it’s important to manage the state</h3><p>SwiftUI’s declarative approach means your app’s UI is driven by its state. When the state changes, the UI updates automatically. This simplifies development and helps avoid bugs that arise from out-of-sync views.</p><h3>1. @State — Simple Local State</h3><p>@State is the simplest way to manage state within a view. It’s designed for local, private state that doesn’t need to be shared.</p><p><strong>Example:</strong> A basic text field that tracks user input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ImQYEDQ1bTMd9DMPVtXaQ.png" /></figure><p>Here, userInput stores the text entered by the user. As the input changes, the text below updates instantly.</p><h3>2. @Binding — Sharing State Between Views</h3><p>@Binding lets child views modify state owned by a parent. It creates a connection that allows changes to flow back and forth.</p><p><strong>Example:</strong> A slider that adjusts the parent view’s progress bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1wTVytobJczQ9AgDzaAHQ.png" /></figure><p>The slider modifies the parent’s progress bar by updating the shared progress state.</p><h3>3. @StateObject — Persistent Observable Object</h3><p>@StateObject creates an observable object that persists for the lifetime of the view. This is useful when you need a data model that survives view redraws.</p><p><strong>Example:</strong> A stopwatch that tracks elapsed time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUpTgpbdJkqppM59u-kw6g.png" /></figure><p>The stopwatch runs persistently, updating the elapsed time every second.</p><h3>4. @ObservedObject — External Observable Object</h3><p>@ObservedObject tracks observable objects that are created outside the view. The lifecycle of the object isn’t controlled by the view.</p><p><strong>Example:</strong> A shared shopping cart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PDiSofsjdGSmKMH9wH4bJg.png" /></figure><p>Here, the cart model is shared between multiple views, reflecting changes instantly.</p><h3>5. @EnvironmentObject — App-Wide State</h3><p>@EnvironmentObject makes state available globally to any view in the app, without passing it manually.</p><p><strong>Example:</strong> Managing app-wide notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWHKIxATrWnDikW-lXLmEQ.png" /></figure><p>Notifications can be updated globally and reflected wherever NotificationBanner is used.</p><h3>Wrapping Up</h3><p>State management is a core concept in SwiftUI. By using the right tools for the job, you ensure your app remains responsive and scalable. Take the time to understand how each state property works, and you’ll have a much smoother development experience. Now get coding and bring your app ideas to life!</p><p>Thank you for reading until the end. Before you go:</p><p>Please consider clapping and following the writer! 👏</p><p>Follow me on <a href="https://www.linkedin.com/in/sachin-goswami-0b827b122/"><strong>LinkedIn</strong></a><strong> for more updates.</strong></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66cacf08ef74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Own Image Caching in IOS with Swift]]></title>
            <link>https://medium.com/@itsachin523/building-your-own-image-caching-in-ios-with-swift-d6a52912dd8f?source=rss-c73a45314d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6a52912dd8f</guid>
            <category><![CDATA[uiimageview]]></category>
            <category><![CDATA[catching]]></category>
            <category><![CDATA[image-captcha]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sachin Goswami]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 11:10:07 GMT</pubDate>
            <atom:updated>2024-07-15T04:58:08.986Z</atom:updated>
            <content:encoded><![CDATA[<p>Image caching is a critical aspect of developing smooth and efficient iOS applications. It can significantly improve the performance of your app by reducing the number of network requests and ensuring that images load quickly and seamlessly. In this post, we’ll explore how to implement a simple yet effective image caching mechanism in iOS using Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JKq6NlrYeKFHxiaSr3yAA.png" /></figure><h3>Why Image Caching?</h3><p>When developing an iOS application, you often need to display images from the internet. Without caching, every time an image needs to be displayed, the app would have to fetch it from the network, leading to increased load times and a poor user experience. Caching allows us to store downloaded images locally so that we can retrieve them quickly when needed.</p><h3>Basic Concepts</h3><ol><li><strong>Cache</strong>: A storage mechanism to store and retrieve data quickly.</li><li><strong>NSCache</strong>: A mutable collection you can use to temporarily store transient key-value pairs that are subject to eviction when resources are low.</li></ol><h3>Setting Up Your Project</h3><ol><li><strong>Create a new iOS project</strong>: Open Xcode, select “Create a new Xcode project”, choose a template, and configure your project settings.</li><li><strong>Add a new Swift file</strong>: Name it ImageCache.swift.</li></ol><h3>Implementing Image Caching</h3><p>Let’s break down the implementation into manageable parts.</p><h4>1. Creating the ImageCache Class</h4><p>First, create a singleton class for the image cache. This ensures that the same cache is used throughout the app.</p><pre>import UIKit<br><br>class ImageCache {<br>    static let shared = ImageCache()<br>    private let cache = NSCache&lt;NSString, UIImage&gt;()<br>    private init() {}<br>    <br>    func getImage(forKey key: String) -&gt; UIImage? {<br>        return cache.object(forKey: key as NSString)<br>    }<br>    <br>    func setImage(_ image: UIImage, forKey key: String) {<br>        cache.setObject(image, forKey: key as NSString)<br>    }<br>}</pre><h4>2. Extending UIImageView for Image Loading</h4><p>Next, create an extension for UIImageView to easily load images from a URL and use the cache.</p><pre>import UIKit<br>extension UIImageView {<br>    func loadImage(from url: URL, placeholder: UIImage? = nil) {<br>        self.image = placeholder<br>        let cacheKey = url.absoluteString<br>        // Check if the image is already in the cache<br>        if let cachedImage = ImageCache.shared.getImage(forKey: cacheKey) {<br>            self.image = cachedImage<br>            return<br>        }<br>        // Download the image if it&#39;s not in the cache<br>        URLSession.shared.dataTask(with: url) { [weak self] data, response, error in<br>            guard let self = self, let data = data, let image = UIImage(data: data) else {<br>                return<br>            }<br>            // Cache the image<br>            ImageCache.shared.setImage(image, forKey: cacheKey)<br>            // Update the UI on the main thread<br>            DispatchQueue.main.async {<br>                self.image = image<br>            }<br>        }.resume()<br>    }<br>}</pre><h3>Using the Image Caching</h3><p>Now that we have our caching mechanism in place, using it is straightforward. In your view controller, you can load images into UIImageView like this:</p><pre>import UIKit<br>class ViewController: UIViewController {<br>    @IBOutlet weak var imageView: UIImageView!<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        if let url = URL(string: &quot;https://example.com/image.jpg&quot;) {<br>            imageView.loadImage(from: url, placeholder: UIImage(named: &quot;placeholder&quot;))<br>        }<br>    }<br>}</pre><h3>Advanced Features</h3><p>To further enhance this basic image caching implementation, consider adding the following features:</p><ol><li><strong>Disk Caching</strong>: Store images on disk for persistent caching across app launches.</li><li><strong>Automatic Cache Management</strong>: Implement mechanisms to manage cache size and automatically remove old or least-used images.</li><li><strong>Progress Indicator</strong>: Show a loading indicator while images are being fetched from the network.</li><li><strong>Error Handling</strong>: Handle errors gracefully, such as showing an error image if the download fails.</li></ol><h3>Conclusion</h3><p>Implementing your own image caching in iOS using Swift can greatly improve your app’s performance and user experience. By following the steps outlined above, you can create a simple and efficient image caching mechanism that ensures images load quickly and smoothly. Experiment with additional features and optimisations to suit your specific app needs.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6a52912dd8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>