<?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 Darshan Dodia on Medium]]></title>
        <description><![CDATA[Stories by Darshan Dodia on Medium]]></description>
        <link>https://medium.com/@darshandodia?source=rss-6059a18e39a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0ZfkqwSz6dMYX9j03lp7oQ.jpeg</url>
            <title>Stories by Darshan Dodia on Medium</title>
            <link>https://medium.com/@darshandodia?source=rss-6059a18e39a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:14:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@darshandodia/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[My Pixel 8 Can’t AirDrop. So I Went Digging to Find Out Why]]></title>
            <link>https://medium.com/@darshandodia/my-pixel-8-cant-airdrop-so-i-went-digging-to-find-out-why-dff43ed2e76e?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff43ed2e76e</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 14:45:56 GMT</pubDate>
            <atom:updated>2026-10-26T14:45:56.620Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Pixel 8, a Mac, and a mystery that went a lot deeper than I expected.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jxObTUdYnWE77Ugz" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As an Android + Mac user, I was delighted to hear that <a href="https://www.gsmarena.com/googles_quick_share_now_works_with_apples_airdrop-news-70391.php">Android had found a workaround to Apple’s AirDrop</a>, allowing Android devices to share files directly with Apple devices. Finally, no more emailing myself photos or hearing the classic, “Just WhatsApp it to me.”</p><p>Then I scrolled down to the list of supported devices, and my Pixel 8 wasn’t on it.</p><p>Okay, I thought, old phone, new feature, it happens. But then I noticed the Pixel 8a was on the list. So were a few Oppo and OnePlus phones. The cheaper sibling of my phone got the feature and mine didn’t, and that made no sense to me.</p><p>I’m a developer, so something that makes no sense is basically an invitation to investigate.</p><p>If you want a direct answer skip directly to <strong><em>“So will my Pixel 8 ever get it?” </em></strong>section.</p><h3>The evidence locker</h3><p>I didn’t want to guess, so I collected some evidence. My toolbox:</p><ul><li>The <a href="https://github.com/morluto/rea">REA</a> (Reverse Engineer Anything) skill with Claude Code, which did most of the digging through the app and the system files</li><li>The publicly available Quick Share and Quick Share Extension APKs</li><li>The OS images for the Pixel 8 and the Pixel 9</li></ul><p>I added the Pixel 9 on purpose. It’s a phone where the feature works, which makes it a handy control group. Put a working phone next to a broken one and compare them, and whatever is missing tends to show itself pretty quickly.</p><p>Everything I did was read-only. I looked at files and symbols, plus the capability reports from my own Pixel 8. I never ran the app against anything, hooked anything, or bypassed anything.</p><h3>Quick Share has a secret twin</h3><p>The first surprise showed up before I opened a single tool. Quick Share on Android turns out to be two separate systems that happen to share a name in the share sheet.</p><p>The first is the one you already use. It lives inside Google Play Services and runs on Nearby Connections: Bluetooth LE to find each other, then jump to Wi-Fi Direct, a hotspot or your local network for the actual transfer. Every Pixel has it, mine included, and it works nicely between Android phones.</p><p>The second is the Quick Share Extension, an app with the package name com.google.android.mosey. Google&#39;s internal codename for it is Mosey. This is the one that speaks Apple&#39;s AirDrop protocol, and this is the one that only Pixel 8a and newer get.</p><p>Same name in the menu, almost no shared code underneath.</p><h3>The app that pretends to be a Mac</h3><p>I started at the top, with the app, and my favorite detail of the whole trip lives right here. Mosey runs a small web server that copies Apple’s AirDrop endpoints, over HTTPS:</p><ul><li>/Discover: who are you?</li><li>/Ask: will you accept this file?</li><li>/Upload: here it is.</li></ul><p>When Mosey sends something to an Apple device, it introduces itself as com.apple.finder. So an Android phone walks up to a MacBook, says &quot;Hi, I&#39;m Finder,&quot; and the MacBook waves it in.</p><p>The whole exchange runs in AirDrop’s “Everyone” mode. The Mac discovers the phone, connects over link-local IPv6, and those three requests handle the rest.</p><p>All very tidy, until I noticed something odd. For an app that sends files over Wi-Fi, Mosey does no radio work at all. Every byte goes into a virtual network interface called mosey0, and the app never asks what sits on the other side. Something else was doing the heavy lifting, so I followed the trail down.</p><h3>Understanding the Process</h3><p>To fully understand the process, we first need to explore how AirDrop works at the hardware level and why replicating the same functionality on Android is challenging.</p><h4>How AirDrop works?</h4><p>AirDrop never goes through a router. The two devices find each other and talk straight to each other, a bit like a pair of walkie-talkies. When you hit AirDrop, three things happen in quick succession:</p><ol><li><strong>Wake up.</strong> Your device sends out a tiny Bluetooth LE signal so nearby Apple devices know someone wants to share.</li><li><strong>Meet up.</strong> The devices switch on AWDL (Apple Wireless Direct Link), Apple’s own flavor of Wi-Fi for device-to-device links. They agree on a shared schedule and meet for short slots on a few fixed “social” channels (6, 44 and 149), then hop back to whatever Wi-Fi network they were on. That’s why your Mac stays connected to your home Wi-Fi while it receives a file.</li><li><strong>Hand over.</strong> Over that private link, each device announces itself with Bonjour (mDNS), and the transfer itself is plain HTTPS: the same three requests from the last section.</li></ol><h4>Why that’s hard on Android?</h4><p>Android has its own device-to-device Wi-Fi modes, Wi-Fi Direct and Wi-Fi Aware, and AWDL is neither of them. It’s Apple’s private protocol, so no Android phone speaks it out of the box.</p><p>To imitate it, an Android phone’s Wi-Fi chip has to park on Apple’s channels (eg. 6, 44 and 149) at exactly the right moments, slip back to your router in between, and send frames in the format Apple expects. Regular Wi-Fi never asks a chip to do any of that. The timing is also far too tight to manage from an app, <em>so it has to happen inside the chip itself</em>.</p><p>And even if an app wanted to try, Android wouldn’t let it. Apps get sockets and high-level APIs, and nothing in the public SDK lets an app tell the Wi-Fi chip which channel to sit on or what raw frames to send. That level of access is reserved for system components.</p><p>So the feature needs a chain of software, where each piece hands instructions to the one below it.</p><p>Think of a restaurant. You place your order with the waiter, the waiter passes it to the kitchen manager, the manager tells the chef, and the chef cooks on the stove. Nobody can skip a step, and if the chef has never heard of the dish, the best waiter in the world makes no difference. Here is the Android version of that kitchen:</p><h3>Five Layers</h3><ol><li><strong>Layer 1 - The app: Starts the transfer</strong> (the customer). This is Mosey, the Quick Share Extension you see in the share sheet. It handles the AirDrop conversation itself, the /Discover, /Ask and /Upload requests from the last section. What it can&#39;t do is work a radio. It simply writes its traffic into mosey0, a virtual network interface that looks like an ordinary network connection, and trusts that someone below will deliver it.</li><li><strong>Layer 2 - The Daemon: Turns the request into radio instructions</strong> (the waiter). On the other side of mosey0 sits mosey_server, a background service written in Rust that ships in the Pixel 9&#39;s system image. It works out what the radio has to do for AirDrop, things like park on social channel 6, announce the phone as an AirDrop device over mDNS, keep hopping channels on schedule. It then hands those instructions to the driver as private commands, such as ART_SET_CHAN (&quot;set the channel&quot;).</li><li><strong>Layer 3 - The Driver: Relays the commands to the chip</strong> (the kitchen manager). The driver is the part of the Linux kernel that talks to the Wi-Fi chip, a Broadcom chip (bcmdhd) in this case. On the Pixel 9 it has a feature called ART (the acronym is never spelled out in the code) that understands the daemon&#39;s commands and forwards them to the chip. It also gives the daemon a special radio interface called wondertap0. Google names its side &quot;mosey&quot; and Broadcom names its side &quot;wondertap&quot;, but both point at the same radio.</li><li><strong>Layer 4 - The firmware: Does the actual work</strong> (the chef). A Wi-Fi chip is a small computer running its own signed software, called firmware. On the Pixel 9, a firmware module called wlc_art receives the driver&#39;s commands and carries them out: it sets up the AirDrop radio interface, keeps track of nearby devices, switches channels and decides how each packet goes out. This is where the tight timing from earlier happens.</li><li><strong>Layer 5 - The hardware: Transmits</strong> (the stove). The physical Wi-Fi radio, a Broadcom BCM4390 chip on the Pixel 9. It does whatever the firmware tells it to.</li></ol><p>Put together, here’s the full journey of a photo from a Pixel 9 to a Mac. The app starts the transfer and writes it into mosey0. The daemon picks it up and turns it into radio instructions. The driver relays those instructions to the chip. The firmware carries them out with the right timing, and the radio sends the photo through the air to the Mac.</p><p>The key thing to notice is that each layer only talks to the one directly below it, and none of them can stand in for another. If even one layer is missing, the chain breaks and the photo never leaves the phone. Keep that in mind, because the next step was to check which of these five layers a Pixel 8 actually has.</p><h3>Autopsy of Pixel 8</h3><p>Time to put the two phones side by side. I compared OS images for both Pixel 8 and Pixel 9 which had the same build version, so any difference is a real one. I went down comparing the five layers.</p><ul><li><strong>Layers 1 and 2 (app and daemon):</strong> The Pixel 8’s system image has no Mosey app and no mosey_server. There&#39;s nothing to launch.</li><li><strong>Layer 3 (driver):</strong> The Pixel 9’s driver has 13 ART functions and a full set of wondertap operations. The Pixel 8&#39;s driver, bcmdhd4398, has zero.</li><li><strong>Layer 4 (firmware):</strong> All three BCM4398 firmware revisions on the Pixel 8 contain zero wlc_art symbols.</li><li><strong>Layer 5 (hardware):</strong> Everything is there. My Pixel 8 reports dual-band simultaneous, Wi-Fi Aware, P2P and TDLS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m93ENjoDxg5fWlzDplh-bw.png" /></figure><blockquote>In short, every software layer is missing on the Pixel 8. There’s no app, no daemon, no ART support in the driver and no wlc_art module in the firmware. The only layer in place is the hardware.</blockquote><p>That brought me back to my first suspect, the hidden switch i.e a feature flag. Could all of this be sitting behind a feature flag that Google just hasn’t turned on for the Pixel 8?</p><p>Android builds do carry release flags for Mosey (RELEASE_MOSEY_*), so I compared them, and they&#39;re identical on both phones. And even if they differed, a flag can only switch on code that already exists on the phone. On the Pixel 8, that code simply isn&#39;t there.</p><p>This also explains the “Pixel 8a or newer” rule. I found no check on the phone model anywhere.</p><p>I also thought through some workarounds:</p><ul><li><strong>Sideload the app.</strong> You can download the Quick Share Extension APK and install it, but it won’t get far. It asks for privileged system permissions, and Android only grants those to apps that ship pre-installed in the system image, never to an app you install yourself. Even past that, the first thing the app does on startup is look for its backend, the mosey_server service. On a Pixel 8 there&#39;s nothing to find, so the app quietly removes itself from the share sheet.</li><li><strong>Copy the daemon over from a Pixel 9.</strong> Say you root the phone and drop mosey_server into place. A system service needs its own security policy and service registration before Android will even start it. Get past that too, and the daemon starts sending commands like ART_SET_CHAN to the Pixel 8&#39;s driver, which doesn&#39;t recognize them. The waiter shows up, but the kitchen manager has no idea what the order means.</li><li><strong>Root the phone and patch the lower layers.</strong> Root gives you control over Android, but the layers that matter sit below Android. The Wi-Fi firmware is signed and loaded by the vendor driver, so a home-made version isn’t an option. And even then, there’s nothing to switch on. The Pixel 8’s firmware has no ART module at all, so someone would have to write one for the BCM4398 from scratch, which is Broadcom-level work.</li></ul><p>Every one of them hits a wall on a different layer.</p><p>So the hidden switch was a dead end. The Pixel 8 simply has none of the software this feature needs. That raised an awkward question: did Google skip the Pixel 8 because its chip can’t handle the job?</p><h3>Could the chip be a problem?</h3><p>Maybe the Pixel 8’s Wi-Fi chip just can’t handle it? But the firmware feature behind AirDrop is mostly control logic built on ordinary radio abilities, and even the Pixel 9’s chip only got it in its newest firmware. Older firmware for that same chip doesn’t have it. On paper the Pixel 8’s chip is actually the stronger of the two, with 320 MHz channels against the Pixel 9’s 160 MHz.</p><blockquote>So technically chip does not seem to be a bottleneck.</blockquote><p>There’s one caveat. A timing limit might only show up under real AirDrop load, and only Broadcom or hands-on testing could rule that out.</p><h3>So, will my Pixel 8 ever get it?</h3><p><em>Probably, eventually!</em></p><blockquote>The Pixel 8’s hardware appears capable of supporting this feature. What’s missing, it seems, is the necessary software support at firmware level.</blockquote><p>Google and Broadcom would need to work together to make this happen. Broadcom would need to develop or update the required firmware, while Google would need to update its software components and apps to support the feature on the Pixel 8.</p><p>Initially, I assumed Google had drawn a line around newer devices, perhaps prioritizing software development for them over older models and that might be true.</p><p>A feature like this needs to work across four layers simultaneously: the app, daemon, driver, and firmware. A device’s inclusion on the supported-device list essentially means that all four layers are in place and working together. If even one layer is missing, the feature won’t work, regardless of whether the hardware itself is capable of supporting it.</p><p>The digging itself was done with the <a href="https://github.com/morluto/rea"><strong>REA</strong></a><strong> (Reverse Engineer Anything) skill</strong> with Claude Code. I asked the questions, and it chased the strings, symbols and call paths down through the stack. If you’re a developer who has never opened a binary on purpose, it’s a friendly way to start.</p><p>As for my Pixel 8, no AirDrop today. At least now I know the things I’m waiting on!</p><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Check out some other (cool?) stuff I made recently:</p><ol><li><a href="https://medium.com/@darshandodia/why-doesnt-youtube-music-have-crossfade-i-built-my-own-engine-to-find-out-a1de09091328?sharedUserId=darshandodia">Why Doesn’t YouTube Music Have Crossfade? I Built My Own Engine to Find Out!</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a Custom Network Listener and Mocker in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong><br>I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a><strong><br>🌏 </strong><a href="https://darshan-d.github.io/portfolio/"><strong>Portfolio</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff43ed2e76e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Doesn’t YouTube Music Have Crossfade? I Built My Own Engine to Find Out!]]></title>
            <link>https://medium.com/@darshandodia/why-doesnt-youtube-music-have-crossfade-i-built-my-own-engine-to-find-out-a1de09091328?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1de09091328</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 14:37:06 GMT</pubDate>
            <atom:updated>2026-09-12T14:37:06.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J9KbyxHiymyKgzX_" /><figcaption>Photo by <a href="https://unsplash.com/@collabstr?utm_source=medium&amp;utm_medium=referral">Collabstr</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A morning run, a sample rate, and one very stubborn silence between songs.</p><p>I was a few kilometers into a run when a song ended on YouTube Music and there was just… nothing. Half a second of dead air before the next track started. It happens every single time, and it still gets me because when I switch over to Spotify, one song just melts into the next like it’s nothing. Apple Music does it too.</p><p>It’s called <strong>Crossfade</strong>. Turn it on in the settings, and the end of your current song overlaps with the beginning of the next, giving you a smooth transition with zero silence in between. It makes a surprisingly big difference when you are in the middle of a run or just really want to be in the groove!</p><p>YouTube Music, somehow, still hasn’t figured this out. And it’s been long enough that I have stopped assuming it’s coming.</p><p>So right after finishing my run I stood in the middle of the street googling “how does audio crossfade work,” which is a sentence I never expected to type, and by the time I got home I had basically decided I was going to build the thing myself just to understand what’s actually going on under the hood.</p><p>That turned into <a href="https://github.com/Darshan-D/Harmoniq">Harmoniq</a>, a small iOS app that crossfades between local audio files using AVAudioEngine .</p><p>Check out the crossfade player in action — <a href="https://github.com/Darshan-D/Harmoniq">https://github.com/Darshan-D/Harmoniq</a></p><p>This is the writeup of what I learned building it, and my best guess at why YouTube Music might genuinely have a harder version of this problem than Spotify or Apple Music does.</p><h4>The Wrong Mental Model</h4><p>My first instinct was that crossfading is just two volume fades happening at the same time, turn one song down, turn the next one up, let them overlap for a few seconds.</p><p>That’s the right shape of the idea, but it glosses over the part that’s actually annoying: knowing <em>exactly</em> when to start. How to convert “roughly 5 seconds before the end,” to the actual “<em>frame</em>” which should trigger the crossfade. You are about to play two songs on top of each other, so any sloppiness in the timing is audible</p><blockquote>Audio doesn’t really have a concept of “seconds” internally. It has “frames”, and a frame only means anything once you know the sample rate.</blockquote><h4>Sample Rate 101</h4><p>A digital audio file is a big list of numbers (frames), and the sample rate tells you how many of those numbers (frames) get played back per second. CD-quality audio runs at 44,100 samples per second (44.1kHz). Video and a lot of streaming audio runs at 48kHz. Your grandpa’s old voice memo app might have used 8kHz. So the audio can be recorded at different sample rates, depending on the quality of recorder used, and that becomes the main issue with crossfade functionality.</p><blockquote>The reason this number matters at all is that the audio engine and the outside world don’t speak the same language.</blockquote><p>AVAudioPlayerNode doesn&#39;t know what &quot;5 seconds left&quot; means, it only knows <em>frames</em>, because that&#39;s the unit it&#39;s actually reading and playing. <em>Seconds</em> are a human thing: what shows up on the seek bar, what &quot;start the fade 5 seconds before the end&quot; means to me when I am writing the code.</p><blockquote>Sample rate is what lets you translate between those two worlds</blockquote><pre>targetFrame = targetSeconds × sampleRate<br>currentSeconds = currentFrame / sampleRate</pre><p>The first one is what happens when a human-sized number needs to become something the engine can act on, the user drags the seek bar to <em>1:23</em>, and that has to turn into an actual frame to jump to. The second is the reverse: the engine reports back “I’m currently at frame 2,116,800,” and that has to turn into “34.7 seconds in” before it means anything to a progress bar, or before I can tell whether we have crossed into the last-5-seconds window that should trigger the crossfade.</p><p>Both conversions run through the same sample rate, so getting it wrong breaks both.</p><p>Hardcode 44.1kHz in your code and load a 48kHz file, and every seek lands in slightly the wrong place, every scheduled fade runs for slightly the wrong duration, and the “5 seconds left” countdown reports a number that’s off not by a fixed amount, but by an error that scales with how far into the song you are. Nothing crashes. It just quietly stops matching what’s actually playing, a little more with every second.</p><p>Okay, so now we can convert cleanly between frames and seconds in both directions. That solves <em>when</em> to start the fade. It does not solve the actual mixing two songs together part.</p><h4>Mixing two songs together</h4><p>During the overlap, both songs are playing, and their audio has to get summed into <strong>one</strong> output stream. Here’s the thing that tripped me up: “sample number 1000” of one song and “sample number 1000” of another song are only the same moment in time <strong>if</strong> they were both recorded at the same sample rate!</p><p>If song A is 44.1kHz and song B is 48kHz, sample 1000 of A is about 22.7ms, and sample 1000 of B is about 20.8ms in. Those aren’t the same instant, so you can’t just add them .. and even if you do .. it won’t be like playing the last 5 seconds of the song overlapped with first 5 seconds of next song. Because the sample rates are different, the output you will get, will be a mess.</p><blockquote>So a simple solution to this problem is, fix the sample rate of every song to be same.</blockquote><p>Which got me thinking about why this might be so much harder for YouTube specifically.</p><h4>My best guess at why YouTube Music doesn’t have this</h4><p>I want to be clear that I have no actual insight into YouTube’s engineering decisions here, I don’t work there, I have never seen how their pipeline is built, this is just a theory I landed on after fighting this problem for a weekend.</p><p>Spotify and Apple Music get to sidestep the whole “different sample rate” issue before it ever reaches your phone. Their catalogs go through ingestion, every track gets transcoded into one consistent format at one consistent sample rate as part of getting added to the library. By the time you are streaming it, every song will be converted into a fixed sample rate.</p><p>YouTube’s catalog isn’t curated like that. It’s official audio, official music videos, live recordings, and a huge amount of covers, people recording songs on whatever mic or phone they had, at whatever rate that device defaulted to. An official studio upload at 48kHz can end up right next to someone’s bedroom recording of the same song at 44.1kHz in the same autoplay queue. YouTube obviously transcodes everything for delivery, but that pipeline is built around consistent video streaming, not around guaranteeing clean, known sample-rate metadata for a music player to build gapless mixing on top of.</p><p>Is that the whole story? Probably not. There’s likely a “this just isn’t a priority feature” angle too. But it’s the first time I have had an actual technical reason to point at instead of just being annoyed about it on my runs.</p><h4>What I ended up with…</h4><p>A small iOS app that streams FLAC files of same sample rates with a crossfade functionality. It also spins a little animated vinyl record while it does all this, mostly because I wanted something to look at while I stared at frame counts for a weekend.</p><p>If you want to poke at the actual code, it’s up on <a href="https://github.com/Darshan-D/Harmoniq">GitHub</a>. It’s a proof of concept, not something I would ship, but it plays four songs back to back without a single gap between them, and that was genuinely the whole goal.</p><p>Full Code — <a href="https://github.com/Darshan-D/Harmoniq">https://github.com/Darshan-D/Harmoniq</a></p><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Check out some other (cool?) stuff I made recently:</p><ol><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong><br>I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1de09091328" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Waiting for App Store Approvals: A Guide to Server-Driven UI]]></title>
            <link>https://medium.com/@darshandodia/stop-waiting-for-app-store-approvals-a-delicious-guide-to-server-driven-ui-a3de4aef2a00?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3de4aef2a00</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 10:47:18 GMT</pubDate>
            <atom:updated>2026-09-12T13:12:31.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iVMxfe-FR67x4qC2" /><figcaption>Photo by <a href="https://unsplash.com/@danielkorpai?utm_source=medium&amp;utm_medium=referral">Daniel Korpai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The “Two-Week Wait” Nightmare</h3><p>Picture this: It’s Thursday afternoon. You’ve just deployed the latest version of your e-commerce app. Suddenly, the marketing team bursts into your office ..</p><p>“We need a giant, blinking, red promotional banner on the home screen! Diwali Sale starts tomorrow!”</p><p>You stare at them, completely deadpan. “I can build it in an hour, but Apple’s App Store review might take anywhere from 24 hours to a week. We’ll have it ready for <em>after</em> Diwali.”</p><p>Cue the marketing tears.</p><p>Building native apps often feels like running a restaurant where, every time you want to change the “Soup of the Day” on your menu, you have to submit a formal request to the city council, wait for a health inspector, and get a notarized stamp of approval. It’s exhausting.</p><p>But what if your app didn’t have a hardcoded menu? What if the app was just a highly trained waiter, and the backend server was the Head Chef? When the Chef wants to add a new dish, they just write it on a ticket, and the waiter serves it immediately.</p><p>Welcome to the restaurant. Let’s talk about Server-Driven UI.</p><blockquote>View full code showcasing custom SDUI implementation using SwiftUI — <a href="https://github.com/Darshan-D/ServerDrivenUI">Github Code</a></blockquote><h3>SDUI: The Introduction</h3><p><strong>Server-Driven UI (SDUI)</strong> also known in the tech underworld as <strong>Backend-Driven UI (BDUI)</strong>, or <strong>Content Driven UI</strong> or “That thing Airbnb, Swiggy and Zomato use to bypass app updates” is an architectural pattern where the server dictates not just the <em>data</em>, but the <em>actual user interface components</em> displayed on the screen.</p><p>Instead of your server sending a JSON payload that looks like this: { &quot;temperature&quot;: 22.5 }</p><p>It sends a JSON payload that looks like a recipe ticket from our Head Chef:</p><pre>{<br>  &quot;screenTitle&quot;: &quot;Smart Home Hub&quot;,<br>  &quot;components&quot;: [<br>    {<br>      &quot;id&quot;: &quot;1&quot;,<br>      &quot;type&quot;: &quot;label&quot;,<br>      &quot;text&quot;: &quot;Living Room Climate&quot;,<br>      &quot;font&quot;: &quot;title&quot;<br>    },<br>    {<br>      &quot;id&quot;: &quot;2&quot;,<br>      &quot;type&quot;: &quot;slider&quot;,<br>      &quot;min&quot;: 16.0,<br>      &quot;max&quot;: 30.0,<br>      &quot;value&quot;: 22.5,<br>      &quot;tint&quot;: &quot;cyan&quot;<br>    }<br>  ]<br>}</pre><p>The app doesn’t know what a “Living Room” is. It just knows: <em>“The Chef told me to put a title label here, and a cyan slider below it.”</em></p><p>If tomorrow the Chef wants to replace the slider with a giant, interactive dial, they just update the JSON ticket. No App Store review required.</p><h3>Decoding the Recipe: How to Parse the JSON Payload</h3><p>Here is the problem with relying on the Chef’s ticket: sometimes the Chef is in a rush and writes down something illegible. In the iOS world, a single malformed object in a JSON array usually causes the default JSONDecoder to flip the table, scream, and crash the entire app.</p><p>We can’t let the whole restaurant burn down just because one potato is missing. To fix this, we build a robust data layer using an enum to handle different component types, and a @LossyArray property wrapper to silently sweep bad ingredients into the trash.</p><p>First, let’s define our menu items:</p><pre>// The &quot;Ticket&quot;<br>struct Payload: Decodable {<br>    let screenTitle: String<br>    @LossyArray var components: [Component] <br>}<br><br>// The Menu Items (Our UI Types)<br>indirect enum UIComponent {<br>    case label(LabelModel)<br>    case slider(SliderModel)<br>    case toggle(ToggleModel)<br>    case unknown(String) // For when the Chef invents a dish we don&#39;t know yet<br>}</pre><p><em>(Note: The </em><em>@LossyArray is a custom property wrapper that catches throwing errors inside an array loop so the app survives. It&#39;s the ultimate digital garbage disposal! — </em><a href="https://github.com/Darshan-D/ServerDrivenUI/blob/main/CustomSDUI-SwiftUI/ExtensionsAndWrappers/CustomWrappers.swift"><em>View Code</em></a><em>)</em></p><p>Next, we write the decoder for our wrapper Component. This is our sous-chef reading the ticket line by line:</p><pre>struct Component: Decodable, Identifiable {<br>    let id: String<br>    let uiComponent: UIComponent<br><br>    private enum CodingKeys: String, CodingKey {<br>        case id, type<br>    }<br><br>    init(from decoder: Decoder) throws {<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        self.id = try container.decode(String.self, forKey: .id)<br>        <br>        let typeString = try container.decodeIfPresent(String.self, forKey: .type) ?? &quot;unknown&quot;<br>        let singleValueContainer = try decoder.singleValueContainer()<br><br>        // Match the Chef&#39;s string to our known models<br>        switch typeString {<br>        case &quot;label&quot;: <br>            self.uiComponent = .label(try singleValueContainer.decode(LabelModel.self))<br>        case &quot;slider&quot;: <br>            self.uiComponent = .slider(try singleValueContainer.decode(SliderModel.self))<br>        default: <br>            self.uiComponent = .unknown(typeString)<br>        }<br>    }<br>}</pre><h3>Plating the Dish (Mapping Models to SwiftUI Views)</h3><p>Now we have our parsed instructions, but we need to actually put them on the plate.</p><p>If we shoved all the rendering logic into one giant view, it would be like having one cook trying to operate the grill, fry station, and bake a soufflé simultaneously. We’d get a “Massive View Controller” (or in SwiftUI, a “Fat View”).</p><p>Instead, we follow the <strong>Single Responsibility Principle</strong>. We create a ComponentRenderer that acts purely as an expeditor. Its only job is to look at the ticket and hand the work to the correct, isolated prep station.</p><pre>struct ComponentRenderer: View {<br>    let component: Component<br><br>    var body: some View {<br>        switch component.uiComponent {<br>        case .label(let model):<br>            SDUILabel(model: model) // Send to the Label Station!<br>            <br>        case .slider(let model):<br>            SDUISlider(model: model) // Send to the Slider Station!<br>            <br>        case .unknown(let type):<br>            // The Chef asked for roasted unicorn. Serve an error instead.<br>            Text(&quot;Unsupported: \(type)&quot;)<br>                .font(.caption)<br>                .foregroundColor(.red)<br>        }<br>    }<br>}</pre><p>Now, every individual UI component gets its own dedicated, tiny kitchen to operate in. They manage their own state, styling, and logic:</p><pre>struct SDUILabel: View {<br>    let model: LabelModel<br>    <br>    var body: some View {<br>        Text(model.text)<br>            .font(.title) // You can map string fonts to SwiftUI fonts!<br>            .foregroundColor(.primary)<br>    }<br>}<br><br>struct SDUISlider: View {<br>    let model: SliderModel<br>    <br>    // We add local state so the user can actually drag it!<br>    @State private var currentValue: Double<br>    <br>    init(model: SliderModel) {<br>        self.model = model<br>        _currentValue = State(initialValue: model.value)<br>    }<br>    <br>    var body: some View {<br>        HStack {<br>            Slider(value: $currentValue, in: model.min...model.max)<br>            <br>            // Format to a clean 1-decimal string so the layout doesn&#39;t jitter<br>            Text(String(format: &quot;%.1f&quot;, currentValue))<br>                .monospacedDigit()<br>        }<br>    }<br>}</pre><p>And just like that, ContentView just iterates through the Payload array, passing each item to the ComponentRenderer. Your app builds itself dynamically, top to bottom.</p><h3>Conclusion (Time for Dessert)</h3><p>By adopting Server-Driven UI in SwiftUI, you fundamentally change the relationship between your mobile app and your backend.</p><ul><li><strong>Agility:</strong> Marketing wants a new promotional layout? Change the JSON.</li><li><strong>A/B Testing:</strong> Want to see if a Toggle converts better than a Slider? Send one JSON payload to Group A, and another to Group B.</li><li><strong>Sanity:</strong> You never have to sweat through an emergency App Store review for a UI tweak again.</li></ul><p>In our restaurant analogy, you’ve successfully fired the middleman. The Server (Head Chef) is happy because they have total control over the menu. The App (the Waiter) is happy because they just have to deliver the food, not cook it. And most importantly, your users (the Customers) get fresh features without having to constantly update their app.</p><p>Bon appétit!</p><blockquote>View full code showcasing custom SDUI implementation using SwiftUI — <a href="https://github.com/Darshan-D/ServerDrivenUI">Github Code</a></blockquote><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Check out some other (cool?) stuff I made recently:</p><ol><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong><br>I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):</p><p>🖥️ <a href="https://darshan-d.github.io/portfolio/"><strong>Portfolio Website</strong></a><br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3de4aef2a00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attempting BookMyShow’s Rating Animation]]></title>
            <link>https://medium.com/@darshandodia/attempting-bookmyshows-rating-animation-b16394a4cb03?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16394a4cb03</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 09:37:31 GMT</pubDate>
            <atom:updated>2026-07-17T09:37:31.771Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRYHGnkPCSHo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRYHGnkPCSHo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRYHGnkPCSHo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8772bf56d2ac9fb7e8020905a9c7a8de/href">https://medium.com/media/8772bf56d2ac9fb7e8020905a9c7a8de/href</a></iframe><p>If you have ever tapped the “Rate Movie” notification on BookMyShow, chances are you have noticed that ridiculously smooth, physics driven slider animation that makes the whole interaction feel instantly alive.</p><p>Naturally, my first thought was: <em>“I should build this myself. How hard could it be?”. </em>Turns out, deceptively hard. What starts as a fun little UI experiment quickly snowballs into gesture quirks, animation tuning, edge cases, and a surprising amount of “why is this behaving like that?” moments.</p><p>But somewhere between the spring physics and the late-night debugging, it also becomes one of the most satisfying and educational UI components you can build.</p><p>Before we begin, here is the complete code in SwiftUI incase you want to refer it 👇</p><p><a href="https://github.com/Darshan-D/BookMyShow-RatingAnimation">GitHub - Darshan-D/BookMyShow-RatingAnimation: A sleek, interactive SwiftUI application that replicates the playful and dynamic movie rating slider found in the BookMyShow app.</a></p><p>In this article I have shared what I learned by breaking down complex animation, why things randomly fly off the screen (seriously), and how to actually make animations feel <strong><em>good</em></strong><em>.</em></p><h3>The Animation Timeline</h3><p>If you stare at a really good UI interaction long enough, you realize it’s not just one animation, it’s a carefully choreographed sequence of micro animations. And that’s exactly what I did to build this animation and break the visual experience down into a timeline:</p><ol><li><strong>Phase 1: The Idle State:</strong> The rating track sits quietly. A subtle red star rests inside the rating track’s groove.</li><li><strong>Phase 2: The Grab:</strong> The moment the user touches the slider, the UI wakes up. The star instantly scales up slightly and pops upward out of the track on the Y-axis so the user’s thumb doesn’t hide it. A small tracking circle appears on the track itself at the position where star was sitting previously.</li><li><strong>Phase 3: The Drag:</strong> As the user pulls their finger across the screen, the star follows. But it doesn’t just slide stiffly, it reacts to momentum. If dragged right, the star tilts dynamically to 45 degrees. If dragged left, it tilts to -45 degrees. A slight spring lag gives the star a feeling of physical weight.</li><li><strong>Phase 4: The Release:</strong> The user lets go. The star slows down and stops. Crucially, if the star was tilted left, it rotates clockwise directly and crisply back to 0 degrees. If tilted right, it snaps counter-clockwise straight back to 0. Crisp, clean, and intentional.</li></ol><p>By breaking the interaction down into these four distinct phases, writing the code became infinitely easier. I just had to build a UI that responded to these specific state changes.</p><h3>Code it Up!</h3><p>At its core, the slider is just a GeometryReader containing a ZStack with four main layers: the background track, the active fill track, the tracking circle, and the floating star.</p><p>Here is a look at the code driving this interaction:</p><pre>struct StarSlider: View {<br>    @Binding var rating: Double // 0.0 to 1.0<br><br>    @State var previousRating: Double = 0<br>    @State var tiltAngle: Double = 0<br>    @State var isSliding: Bool = false<br>    @State var hasInteracted: Bool = false<br>    <br>    var body: some View {<br>        GeometryReader { geometry in<br>            let thumbSize: CGFloat = 34<br>            let availableWidth = geometry.size.width - thumbSize <br>            <br>            ZStack(alignment: .leading) {<br>                // 1. Background Track<br>                Capsule().fill(Color.gray.opacity(0.3)).frame(height: 8)<br>                <br>                // 2. Active Fill Track<br>                Capsule().fill(Color.red)<br>                    .frame(width: max(thumbSize/2, CGFloat(rating) * availableWidth + thumbSize/2), height: 8)<br>                <br>                // 3. The Tracking Circle<br>                Circle()<br>                    .fill(Color.red)<br>                    .frame(width: 16, height: 16)<br>                    // PHASE 1 &amp; 2: Hidden initially, scales up on interaction<br>                    .scaleEffect(hasInteracted ? 1 : 0.001)<br>                    .opacity(hasInteracted ? 1 : 0)<br>                    .offset(x: CGFloat(rating) * availableWidth + 9)<br>                <br>                // 4. The Floating Star<br>                Image(systemName: &quot;star.fill&quot;)<br>                    .resizable()<br>                    .scaledToFit()<br>                    .frame(width: thumbSize-8, height: thumbSize-8)<br>                    .foregroundColor(.red)<br>                    // PHASE 2 &amp; 4: Scales up when sliding, shrinks slightly on release<br>                    .scaleEffect(isSliding ? 1.2 : 1.1)<br>                    .rotationEffect(.degrees(-tiltAngle), anchor: .bottom)<br>                    .offset(<br>                        x: CGFloat(rating) * availableWidth + 4,<br>                        y: hasInteracted ? -40 : 0 // PHASE 2: Pops upward out of the track<br>                    )<br>                    // PHASE 3: Heavier spring creates physical weight/lag during tracking<br>                    .animation(.spring(response: 0.6, dampingFraction: 0.7), value: rating)<br>                    .animation(.spring(response: 0.4, dampingFraction: 0.6), value: tiltAngle)<br>                <br>                    // PHASE 3: Directional Tracking<br>                    .onChange(of: rating) { newValue in<br>                        if newValue &gt; previousRating {<br>                            tiltAngle = 45  // Dragging right -&gt; Tilt right<br>                        } else if newValue &lt; previousRating {<br>                            tiltAngle = -45 // Dragging left -&gt; Tilt left<br>                        }<br>                        previousRating = newValue<br>                    }<br>                    // PHASE 4: The Clean Release logic<br>                    .onChange(of: isSliding) { isSliding in<br>                        if !isSliding {<br>                            tiltAngle = 0 // Stand back up straight<br>                        }<br>                    }<br>            }<br>            .frame(height: geometry.size.height, alignment: .center)<br>            .gesture(<br>                DragGesture(minimumDistance: 0)<br>                    .onChanged { drag in<br>                        // Trigger PHASE 2: The Grab<br>                        withAnimation(.spring(response: 0.4, dampingFraction: 0.6)) {<br>                            self.hasInteracted = true<br>                        }<br>                        <br>                        // Trigger PHASE 3: The Drag math<br>                        let dragX = drag.location.x - (thumbSize / 2)<br>                        let percentage = dragX / availableWidth<br>                        <br>                        // Guardrails: Clamping the value strictly between 0.0 and 1.0<br>                        self.rating = max(0.0, min(1.0, Double(percentage)))<br>                        self.isSliding = true<br>                    }<br>                    .onEnded { drag in<br>                        // Trigger PHASE 4: The Release<br>                        self.isSliding = false<br>                    }<br>            )<br>        }<br>        .frame(height: 100)<br>    }<br>}</pre><p>Connecting Code to the timeline we discussed previously:</p><ul><li><strong>Phase 1 (The Idle State) in Code:</strong> Look at the initial states of hasInteracted and isSliding, both starting as false. Because of this, the tracking circle&#39;s .scaleEffect evaluates to 0.001 (almost hidden), and the star&#39;s Y-offset is sitting safely at 0, resting perfectly inside the track line.</li><li><strong>Phase 2 (The Grab) in Code:</strong> The magic starts inside DragGesture&#39;s .onChanged block. The split second a user&#39;s finger touches down, hasInteracted and isSliding flip to true. Instantly, the star&#39;s ternary operator for Y-offset shifts to -40, snapping it upward away from the finger, while .scaleEffect(isSliding ? 1.2 : 1.1) balloons its size.</li><li><strong>Phase 3 (The Drag) in Code:</strong> As the finger moves, the gesture block calculates the tracking percentage. We pass this to the .onChange(of: rating) block. By comparing newValue against previousRating, our code senses direction. If the values are growing, tiltAngle hits 45, if shrinking, it sets to -45. Because we applied a heavier spring animation (response: 0.6) to the rating value, the star doesn&#39;t perfectly match the finger position frame-for-frame and safely lags behind, simulating physical mass.</li><li><strong>Phase 4 (The Release) in Code:</strong> When the user lifts their finger, .onEnded kicks in and resets isSliding = false. This directly triggers our second .onChange block. By hard-setting tiltAngle = 0 the moment sliding stops, we bypass the spring&#39;s natural desire to sway back and forth like a pendulum. The star returns straight up and down cleanly and sharply.</li></ul><h3>Mistakes I Made (So You Don’t Have To)</h3><p>Building this wasn’t entirely smooth sailing. Here are a couple of roadblocks I hit along the way.</p><h4>1. The Modifier Order Trap: Accidental Orbital Mechanics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EFBol0WHvhaRIUOo5-KzCA.gif" /><figcaption>Output with incorrect modifier order</figcaption></figure><blockquote>If you take one single thing away from this article, let it be this: in SwiftUI, <strong>modifier order changes everything</strong>.</blockquote><p>When I first tried to make the star lean into the drag, I accidentally built a solar system simulator. My star was swooping in giant, bizarre arcs across the screen instead of sliding nicely in a straight horizontal line.</p><p>Here is why it happens, explained simply. Imagine your UI component is pinned to the screen with a thumbtack:</p><ul><li><strong>Offset first, then Rotate:</strong> If you use .offset() to move your view 100 pixels to the right, and <em>then</em> apply a .rotationEffect(), SwiftUI keeps the &quot;thumbtack&quot; at the original starting position and spins the entire coordinate space. Your star swings around on an invisible 100-pixel string like a planet orbiting a sun.</li><li><strong>Rotate first, then Offset:</strong> If you apply .rotationEffect() first, the star just spins in place on its own axis. <em>Then</em>, when you apply the .offset(), you push that already-tilted star 100 pixels to the right. It moves along a perfectly straight horizontal path.</li></ul><p>To keep the star moving straight while leaning, the .rotationEffect must <em>always</em> happen before the .offset.</p><h4>2. Killing Magic Numbers with GeometryReader</h4><p>Early on, hardcoded offsets worked perfectly… until I loaded the app on a different device size. To make the component responsive, GeometryReader is non-negotiable.</p><p>By wrapping the slider in a GeometryReader, we can dynamically calculate exactly how much runway the star has based on the actual layout width (let availableWidth = geometry.size.width - thumbSize). From there, positioning the star is just simple percentage math. It scales flawlessly whether it’s on a smaller iPhone or a massive iPad screen, completely eliminating the need to guess screen boundaries.</p><h3>Final Thoughts</h3><p>Rebuilding this slider evolved from a simple UI task into a practical exploration of transform hierarchies, responsive layouts, and the power of state-driven animation.</p><p>When you break an animation down into a clear timeline and map your code directly to those visual states, you realize that SwiftUI gives you all the tools you need to build world class interactions. Next time you see a bouncy, fluid interaction in an iOS app, take a moment to appreciate the invisible tug of war happening between modifier orders, state properties, and geometry readers just beneath the surface!</p><p>Now go build something magical yourself! ✨</p><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Check out some other (cool?) stuff I made recently:</p><ol><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong> <br>I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16394a4cb03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why your Xcode console is lying to you (and how stderr fixes it)]]></title>
            <link>https://medium.com/@darshandodia/why-your-xcode-console-is-lying-to-you-and-how-stderr-fixes-it-a0f272401c22?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0f272401c22</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 14:36:36 GMT</pubDate>
            <atom:updated>2026-07-15T14:36:36.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3bLTzwX5M_9F5ivF" /><figcaption>Photo by <a href="https://unsplash.com/@davidpupaza?utm_source=medium&amp;utm_medium=referral">David Pupăză</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I was debugging some code using a physical iPhone. However, I could not see my custom print statements that I had just added, although the breakpoint right next to those print statements was hit perfectly. The print statements worked exactly as expected on the simulator, so what was missing?</p><p>I tried deleting the app from the phone, reinstalling it, cleaning the build folder, and checking my build flags. Nothing was out of the ordinary. And then, I learned about stderr and stdout.</p><p>If you have ever found yourself screaming into the void of the Xcode console, wondering where your logs went, grab a coffee. We are about to take a playful (but highly practical) dive into the differences between print and NSLog, the underlying magic of standard streams, and why the way your app &quot;batches&quot; its text might be sabotaging your debugging sessions.</p><h3>The Usual Suspects: print vs. NSLog</h3><p>When you want to see what’s going on inside your Swift code, your first instinct is probably to type print(&quot;Here!&quot;). It’s short, it’s Swift-native, and it gets the job done 90% of the time.</p><p>But hiding in the shadows is Objective-C’s battle-tested veteran: NSLog.</p><p>While they both slap text onto your screen, they do it in fundamentally different ways:</p><ul><li><strong>print</strong>: The laid-back modern approach. It takes your string, formats it nicely, and sends it to the debugger console. No timestamps, no thread identifiers, just pure text.</li><li><strong>NSLog</strong>: The strict, formal accountant. It adds a timestamp, the process name, and the thread ID to every single log. More importantly, it doesn’t just talk to the debugger, it talks to the Apple System Log (and the modern Unified Logging system), meaning its output can be read directly from the physical device’s console even if Xcode isn’t attached.</li></ul><p>But the real difference that caused my missing-log mystery lies slightly deeper, in the C-level plumbing of your operating system.</p><h3>The Tale of Two Streams: stdout and stderr</h3><p>Under the hood of Unix-based systems (which includes iOS and macOS), programs communicate with the outside world using standard streams. Think of them as dedicated plumbing pipes for your app’s text.</p><ul><li><strong>stdout (Standard Output)</strong>: This is the default pipe for normal, expected output. When you use print(), your text goes straight into the stdout pipe.</li><li><strong>stderr (Standard Error)</strong>: This pipe is specifically reserved for errors, warnings, and diagnostic logs. When you use NSLog() (or its modern Swift cousin, Logger), the text is routed through stderr.</li></ul><p>When you are running a simulator, Xcode easily captures both pipes and displays them in the debug console. But on a physical device, stdout can sometimes be ignored, disconnected by the OS to save resources, or caught in a buffering trap over a Wi-Fi debugging bridge. stderr, on the other hand, is treated like a VIP emergency siren. The system guarantees it gets logged to the device&#39;s actual console.</p><h3>To Batch or Not to Batch (The Buffering Dilemma)</h3><p>The choice between stdout and stderr isn&#39;t just about where the logs go, it&#39;s about <em>how fast</em> they get there. This brings us to <strong>buffering</strong>.</p><h4>stdout is a Commuter Bus (Buffered)</h4><p>By default, stdout is buffered. It doesn&#39;t want to waste system resources by doing a heavy write operation every time you print a single character or word. Instead, it waits. It gathers up all your print statements into a &quot;batch&quot; (a buffer) and only flushes that batch to the console when the buffer is full, or when it hits a newline character. It’s highly efficient, but it does things on its own schedule.</p><h4>stderr is a Sports Car (Unbuffered)</h4><p>stderr is entirely unbuffered. It doesn&#39;t wait to batch anything. The exact millisecond NSLog executes, the data is instantly forced out of the pipe and written to the log. It’s less efficient for system performance, but it prioritizes immediate delivery.</p><h3>Why Unbuffered is the King of Time-Sensitive Debugging</h3><p>Imagine you are trying to track down a nasty, app-crashing bug. You put a print(&quot;Starting heavy work&quot;) right before the dangerous code, and print(&quot;Finished heavy work&quot;) right after.</p><p>You run the app. It crashes. You look at the console, and <em>neither</em> print statement is there. You scratch your head, assuming the code never executed.</p><p>Here is what actually happened: The first print executed, but stdout put it into its batching buffer, waiting for a good time to send it. Then, the app crashed. The buffer was destroyed in the crash before it ever had a chance to flush the text to your screen. stdout lied to you by omission.</p><p>If you had used NSLog (which uses stderr), the unbuffered nature of the stream would have guaranteed that &quot;Starting heavy work&quot; was written to the console the absolute millisecond it executed, right before the app died.</p><p>For anything involving crashes, race conditions, or time-sensitive multi-threading bugs, <strong>batching is your enemy</strong>. You want unbuffered, immediate truth. You want stderr.</p><h3>Wait, What About stdin?</h3><p>Since we are talking about standard pipes, it feels rude not to mention the third sibling: stdin (Standard Input).</p><p>If stdout and stderr are for the outputs of your app, stdin is for the input. It is the pipe used to receive text input into a program. If you have ever written a command-line tool in Swift and used readLine() to capture what the user typed on their keyboard, you were reading from stdin.</p><p>In iOS development, we almost never touch stdin. We get our input from touches, swipes, and UI text fields rather than command-line prompts. But it&#39;s always there, sitting quietly in the Unix architecture, waiting for someone to type something.</p><h3>The Takeaway</h3><p>The next time your print statements vanish into the ether on a physical device, remember that you are at the mercy of stdout and its batching buffer.</p><ul><li>Use <strong>print</strong> for casual, everyday debugging where performance matters and you don&#39;t care about device-level persistence.</li><li>Use <strong>NSLog</strong> (or even better, Apple&#39;s modern <strong>os_log</strong> / <strong>Logger</strong>) when you need immediate, unbuffered truth, timestamps, or when you need your logs to survive an app crash and be readable from the device later.</li></ul><p>Happy debugging, and may your console never be empty when you need it most!</p><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Check out some other (cool?) stuff I made recently:</p><ol><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong> <br>I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0f272401c22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why can you loop over a Set like an Array, but not access it by index?]]></title>
            <link>https://medium.com/@darshandodia/why-can-you-loop-over-a-set-like-an-array-but-not-access-it-by-index-09e87c4f0d99?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/09e87c4f0d99</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 06:58:42 GMT</pubDate>
            <atom:updated>2026-02-17T06:58:42.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKZFEQTouDNm93U30l6yRw.png" /><figcaption>Summary of the article (AI Generated Image)</figcaption></figure><p>Type let items = [1, 2, 3] into Xcode, and you have an Array. It feels solid, dependable, and incredibly simple. You loop over it, you access item zero, you append a four. It just works.</p><p>But then you try doing the exact same thing with a Set or a Dictionary. You can effortlessly run a for-in loop over them, just like an Array. But the moment you type mySet[0], the compiler yells at you.</p><p>Why does Swift allow you to loop through these data structures perfectly fine, but suddenly develop amnesia when you ask for the “first” item?</p><p>The answer lies in the fact that an Array isn&#39;t just a magical bucket of data, it’s the highly specialized final form of a progressive ladder of Swift protocols. To understand the difference, we have to deconstruct data structures from the absolute bare minimum requirement, tracking exactly what functionality we &quot;unlock&quot; at each step.</p><h3>1. IteratorProtocol: The Raw Engine</h3><p>At the very bottom of the ladder sits the IteratorProtocol.</p><p>This protocol is shockingly simple. It doesn’t know how many items it has. It doesn’t know where the beginning or the end is. It only knows how to do exactly one thing: supply the <em>next</em> element using a next() method.</p><p>Iterators are inherently stateful and destructive. Imagine a machine dispensing tickets: once it hands you ticket #1, that ticket is gone from the machine. You cannot ask it to rewind.</p><ul><li><strong>Real-World Use Case:</strong> Reading a live stream of data over a network socket, or processing a massive file line-by-line where loading the whole thing into memory would crash your app.</li><li><strong>Compared to an Array:</strong> At this level, the only Array feature we have unlocked is the ability to fetch elements one by one. We have no .count, no [0] index access, and no ability to loop through the data a second time safely.</li></ul><p><strong>Standard Library Example:</strong></p><p>You rarely build these yourself, but every time you loop, Swift creates one behind the scenes. Here is how you interact with one directly:</p><pre>let numbers = [10, 20, 30]<br>var rawIterator = numbers.makeIterator() <br><br>// The engine pumps out values one by one<br>print(rawIterator.next()) // Optional(10)<br>print(rawIterator.next()) // Optional(20)<br>print(rawIterator.next()) // Optional(30)<br>print(rawIterator.next()) // nil - The dispenser is empty forever</pre><h3>2. Sequence: The Abstract “Series”</h3><p>The next rung up the ladder is the Sequence protocol.</p><p>Sequence is not vastly different from IteratorProtocol in terms of raw power, but it is a crucial <strong>abstract concept</strong>. Its primary job is to act as a factory. The only firm requirement of a Sequence is that it must provide a makeIterator() method.</p><p>By wrapping the raw iterator in this abstract concept, Sequence acts as the master key that unlocks Swift&#39;s for-in loop syntax. Because a Sequence might just be a thin wrapper over a destructive data source, it only guarantees that you can walk through the data <em>at least once</em>.</p><ul><li><strong>Real-World Use Case:</strong> Generating a sequence of mathematical steps or dates on the fly (like finding the next 10 prime numbers) without actually storing them all in memory.</li><li><strong>Compared to an Array:</strong> We have now unlocked the beautiful for-in loop syntax, as well as powerful standard library methods like .map, .filter, and .reduce. However, we still do not have a guaranteed .count or [index] access, and we still cannot safely assume we can loop over it twice.</li></ul><p><strong>Standard Library Example:</strong></p><p>The stride function creates a Sequence that generates numbers mathematically, rather than storing them.</p><pre>let countdown = stride(from: 3, to: 0, by: -1)<br><br>// The Sequence unlocks the for-in loop syntax<br>for number in countdown {<br>    print(number) <br>}</pre><h3>3. Collection: The Multi-Pass, Indexed Upgrade (Sets &amp; Dictionaries)</h3><p>Now we step into the big leagues. Collection is a protocol that inherits from Sequence, but it adds massive stability guarantees: multi-pass safety (you can loop over it safely as many times as you want) and knowing its own .count.</p><p>Crucially, Collections also unlock <strong>Indexing</strong>. However, an index doesn’t have to be a simple integer (0, 1, 2).</p><p><strong>Enter Sets and Dictionaries:</strong></p><p>Both Set and Dictionary are standard library Collections backed by <strong>hash tables</strong>. To ensure ultra-fast lookups, they take your data, scramble it through a mathematical formula (a hash), and scatter it into random &quot;buckets&quot; in memory.</p><p>Because the items are not lined up in a predictable order, asking a Set for &quot;item number 0&quot; is meaningless. Instead, they use specialized, opaque index types (like Set.Index or Dictionary.Index) that act like GPS coordinates pointing to a specific bucket.</p><p><em>(Note: In a Dictionary, </em><em>dict[0] might work if your keys are integers, but that is a </em><strong><em>Key</em></strong><em> lookup, not a true Collection Index lookup!)</em></p><ul><li><strong>Real-World Use Case:</strong> Storing a collection of unique user IDs (Set) or mapping user IDs to profile data (Dictionary) where fast lookups are far more important than the order of the items.</li><li><strong>Compared to an Array:</strong> We have unlocked almost everything: multi-pass safety, total count, and subscript indexing. But we aren’t quite at an Array yet, because our indices are complex coordinates, not simple integers.</li></ul><p><strong>Standard Library Example:</strong></p><p>Notice how we must ask the Set and Dictionary for their specific “GPS coordinates” to use an index.</p><pre>let fruits: Set = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;]<br>let userAges: [String: Int] = [&quot;Alice&quot;: 25, &quot;Bob&quot;: 30]<br><br>// We unlocked multi-pass and count!<br>print(fruits.count) // 3<br><br>// We unlocked indexing! But it&#39;s not a simple integer.<br>let firstFruitIndex = fruits.startIndex<br>print(fruits[firstFruitIndex]) // Prints a valid fruit in O(1) time<br><br>// For Dictionaries, the true index returns a tuple of (Key, Value)<br>let firstDictIndex = userAges.startIndex<br>print(userAges[firstDictIndex].key)   // e.g., &quot;Bob&quot;<br>print(userAges[firstDictIndex].value) // e.g., 30</pre><h3>4. Array: The Concrete Reality</h3><p>Finally, we arrive at the Array.</p><p>Unlike the previous three, which are protocols (blueprints), an Array is a <strong>concrete data structure</strong>. It adopts the Collection protocol, but makes highly specific choices tailored for everyday convenience.</p><p>An Array guarantees that its elements are stored right next to each other in memory (contiguous storage), and it mandates that its indices are strictly simple Int values.</p><ul><li><strong>Real-World Use Case:</strong> Ordered lists where the exact position matters, like rendering rows in a UI table or maintaining a top-10 leaderboard.</li><li><strong>Compared to an Array:</strong> Well, it <em>is</em> the Array. You finally unlock the zero-based array[0] access, along with mutating methods that shuffle memory around, like .append() and .insert().</li></ul><p><strong>Standard Library Example:</strong></p><pre>var temperatures = [72.5, 74.0, 71.8] <br><br>temperatures.append(75.2) // Array-specific memory manipulation<br>print(temperatures[0])    // Concrete Integer indexing unlocked!</pre><h3>Conclusion: Answering the Question</h3><p>So, why can you loop over a Set like an Array, but not access it by index?</p><p>Because both Set and Array conform to the abstract <strong>Sequence</strong> protocol, which is the master key that unlocks the for-in loop. They both know how to hand you their items one by one.</p><p>However, they diverge at the concrete implementation level. An Array stores data side-by-side, making a simple integer index ([0], [1]) mathematically logical. A Set scatters its data randomly using a hash table for speed, meaning &quot;item 0&quot; doesn&#39;t logically exist. It still has an index (because it is a Collection), but it&#39;s a complex Set.Index coordinate, not an integer.</p><h3>The Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WoFx1vyx4dhlfU8d8WSUdw.png" /></figure><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Theory is great, but let’s be honest, we are here to build cool stuff.</p><p>If you want to put that Swift knowledge to the test and flex those coding muscles, check out following medium articles:</p><ol><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong> I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09e87c4f0d99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is reading data dangerous in a concurrent environment?]]></title>
            <link>https://medium.com/@darshandodia/why-is-simply-looking-at-data-inherently-dangerous-in-a-concurrent-environment-9dea00c29a59?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dea00c29a59</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 07:27:26 GMT</pubDate>
            <atom:updated>2026-02-23T20:05:12.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pPfiNr91yygSx74s" /><figcaption>Photo by <a href="https://unsplash.com/@usmanbim94?utm_source=medium&amp;utm_medium=referral">Usman Malik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When building concurrent applications in Swift, you will inevitably encounter a scenario where multiple threads need to access and modify the same data structure. Standard library collections like Dictionary and Array are incredibly fast value types, but they are not thread-safe. If two threads try to interact with them at the wrong time, your app will instantly crash.</p><p>If you can confidently answer the following four questions, you have a solid grasp of concurrency fundamentals. If not, it’s time to level up your understanding of Grand Central Dispatch (GCD):</p><ol><li>How do you prevent a shared data structure from crashing under multi-threaded pressure?</li><li>How do you eliminate the massive performance bottlenecks caused by traditional locking mechanisms?</li><li>Why is simply “looking” at data (reading) inherently dangerous in a concurrent environment?</li><li>What is the fundamental difference between <em>thread</em> behavior and <em>queue</em> behavior, and why does confusing them lead to data corruption?</li></ol><p>Ready to put your skills to the test? Let’s dive in.</p><h4>Phase 1: How do you prevent a shared data structure from crashing under multi-threaded pressure?</h4><p><strong>The Problem:</strong> How do we prevent a shared dictionary from crashing when multiple threads access it simultaneously?</p><p>The most straightforward solution is a Mutex (Mutual Exclusion) lock. In GCD, we can achieve this using a DispatchSemaphore with a value of 1.</p><p>Think of this semaphore as a single key to a room. Before a thread can read or write to the dictionary, it must take the key (wait()). When it is finished, it puts the key back (signal()). Because there is only one key, it is physically impossible for two threads to touch the dictionary at the same time.</p><pre>class SemaphoreDictionary&lt;Key: Hashable, Value&gt; {<br>    private var dictionary = [Key: Value]()<br>    private let semaphore = DispatchSemaphore(value: 1)<br>    <br>    func read(key: Key) -&gt; Value? {<br>        semaphore.wait()<br>        let value = dictionary[key]<br>        semaphore.signal()<br>        return value<br>    }<br>    <br>    func write(value: Value, key: Key) {<br>        semaphore.wait()<br>        dictionary[key] = value<br>        semaphore.signal()<br>    }<br>}</pre><p>This perfectly protects the dictionary, but it creates a massive performance bottleneck. If your app has dozens of threads constantly trying to fetch data, forcing them to line up one-by-one just to <em>read</em> a value wastes valuable computing time. Semaphores keep data safe, but they block everything.</p><blockquote><strong><em>Answer to Question 1:</em></strong><em> You prevent a shared data structure from crashing by using a mutual exclusion lock (like </em><em>DispatchSemaphore). This acts as a single key that strictly serializes access to the data structure, ensuring only one thread can ever interact with it at a time.</em></blockquote><h4>Phase 2: How do you eliminate the massive performance bottlenecks caused by traditional locking mechanisms?</h4><p><strong>The Problem:</strong> If most of our operations are just reading data, why should readers wait for each other? Is there a better way?</p><p>Yes. The solution to this bottleneck is the <strong>Reader-Writer Lock</strong> pattern, implemented in Swift using a concurrent DispatchQueue and a .barrier flag.</p><p>A concurrent queue allows multiple tasks to run at the exact same time. If 100 threads want to read from the dictionary, the concurrent queue lets them all read simultaneously. No waiting.</p><p>However, when a thread needs to write new data, it submits the task using the .barrier flag. The queue sees the barrier, waits for all current readers to finish, locks out any new readers, and executes the write operation <em>entirely alone</em>. Once the write is done, the queue opens back up for concurrent reading.</p><pre>class BarrierDictionary&lt;Key: Hashable, Value&gt; {<br>    private var dictionary = [Key: Value]()<br>    private let queue = DispatchQueue(label: &quot;com.example.dictQueue&quot;, attributes: .concurrent)<br>    <br>    func read(key: Key) -&gt; Value? {<br>        var result: Value?<br>        queue.sync { // Note the &#39;sync&#39; here<br>            result = dictionary[key]<br>        }<br>        return result<br>    }<br>    <br>    func write(value: Value, key: Key) {<br>        queue.async(flags: .barrier) {<br>            self.dictionary[key] = value<br>        }<br>    }<br>}</pre><p>This pattern gives you maximum read performance while ensuring writes are completely safe. But looking closely at the read method above raises an important conceptual question.</p><blockquote><strong><em>Answer to Question 2:</em></strong><em> You eliminate the performance bottleneck of locks by implementing a Reader-Writer pattern using a concurrent </em><em>DispatchQueue and a </em><em>.barrier flag. This allows infinite concurrent reads without waiting, but temporarily isolates the queue for exclusive, serial access during a write.</em></blockquote><h4>Phase 3: Why is simply “looking” at data (reading) inherently dangerous in a concurrent environment?</h4><p><strong>The Problem:</strong> In the barrier example, we put the read operation inside a queue’s sync block. Why do read operations need protection at all? Isn&#39;t reading just looking at data?</p><p>It is highly intuitive to assume that looking at data is a harmless, non-destructive act. But standard library dictionaries are dynamic; they resize themselves behind the scenes.</p><p>If a background thread adds a new key-value pair, the dictionary might realize it has run out of allocated memory. To fix this, it silently destroys its current memory layout and copies everything into a brand-new, larger block of memory.</p><p>If you attempt to read a value without forcing the read to happen on the queue (bypassing the sync block), your read operation might occur at the exact microsecond the dictionary is destroying its old memory block. Your thread attempts to read memory that no longer exists, resulting in an immediate EXC_BAD_ACCESS crash.</p><p>Reads <em>must</em> be synchronized on the queue so the barrier mechanism knows they exist and can prevent writes from overlapping with them.</p><blockquote><strong><em>Answer to Question 3:</em></strong><em> Reading is inherently dangerous because standard library collections are dynamic. If you read without synchronization while another thread writes, the collection might be resizing and destroying its old memory layout. This causes your read operation to hit deallocated memory, resulting in an immediate crash.</em></blockquote><h4>Phase 4: What is the fundamental difference between thread behavior and queue behavior, and why does confusing them lead to data corruption?</h4><p><strong>The Problem:</strong> If sync perfectly protects our read operation by making the thread wait, why can&#39;t we just use sync on the concurrent queue for our write operations instead of dealing with the .barrier flag?</p><p>This is the single most common point of confusion in Grand Central Dispatch: <strong>conflating thread behavior with queue behavior.</strong></p><p>Calling sync only pauses the <em>calling thread</em>. It tells the queue, &quot;I am giving you this task, and my thread will wait right here until you finish it.&quot;</p><p>However, <strong>the queue itself is still concurrent</strong>. If Thread A and Thread B both call a sync write operation at the same time, the concurrent queue will happily accept both tasks and execute them both simultaneously. You will have two threads modifying the dictionary&#39;s memory at the exact same moment, causing data corruption and a crash.</p><p>Swift</p><pre>class SyncVsBarrierExample {<br>    private var dictionary = [String: String]()<br>    private let queue = DispatchQueue(label: &quot;com.example.queue&quot;, attributes: .concurrent)<br>    <br>    // ❌ FATAL ERROR: Multiple threads calling this will write simultaneously<br>    func dangerousWrite(value: String, key: String) {<br>        queue.sync { <br>            self.dictionary[key] = value <br>        }<br>    }<br>    <br>    // ✅ SAFE: The barrier forces the queue to act serially for this one block<br>    func safeWrite(value: String, key: String) {<br>        queue.async(flags: .barrier) { <br>            self.dictionary[key] = value <br>        }<br>    }<br>}</pre><p>The .barrier flag is the <em>only</em> mechanism that instructs the concurrent queue to temporarily drop its concurrent nature, lock the doors, and execute the block entirely alone.</p><blockquote><strong><em>Answer to Question 4:</em></strong><em> The fundamental difference is that </em><em>sync pauses the </em>calling thread<em>, but it doesn&#39;t change the concurrent nature of the </em>queue<em>. If a queue is concurrent, multiple threads can submit </em><em>sync blocks simultaneously, and the queue will execute them all at once. Confusing thread pausing (</em><em>sync) with queue isolation (a </em><em>.barrier) allows overlapping writes, leading to data corruption.</em></blockquote><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Theory is great, but let’s be honest, we are here to build cool stuff.</p><p>If you want to put that Swift knowledge to the test and flex those coding muscles, check out following medium articles:</p><ol><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong> I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dea00c29a59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The mystery of “some” in SwiftUI]]></title>
            <link>https://medium.com/@darshandodia/the-mystery-of-some-in-swiftui-e17e53fecace?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e17e53fecace</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 05:58:03 GMT</pubDate>
            <atom:updated>2026-02-10T05:58:03.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dxCviZMV5NjoG5XU" /><figcaption>Photo by <a href="https://unsplash.com/@hjkp?utm_source=medium&amp;utm_medium=referral">henry perks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have ever written a line of SwiftUI, you have seen it. It’s sitting right there in the boilerplate code:</p><pre>var body: some View { <br>    // some view<br>}</pre><p>It is easy to dismiss some as just &quot;SwiftUI magic,&quot; but it exists to solve a very specific, low-level problem involving computer memory.</p><p>To understand why we need some, we first have to talk about how Swift actually stores data.</p><h3>How stuff is stored in Swift</h3><blockquote>Here is the most important concept to understand about Swift (and SwiftUI): <strong>It prefers Value Types (Structs).</strong></blockquote><p>When you create a Class (Reference Type), the object lives in the <strong>Heap </strong>memory. You simply hold a tiny “pointer” to it. A pointer is always the same size, let’s say 8 bytes. It’s like holding a slip of paper with a pizza place’s address on it. The slip of paper is always small, regardless of whether the restaurant is a small or huge.</p><p><strong>SwiftUI Views are different.</strong> They are <strong>Structs</strong>. They live on the <strong>Stack</strong>. The Stack is incredibly fast, but it is strict. To put something on the Stack, the compiler must know <em>exactly</em> how big it is before the program even runs.</p><ul><li>A Text view might be 16 bytes.</li><li>A VStack containing two images might be 150 bytes.</li></ul><h3>The Opaque Types</h3><p>This is where some comes in. It is officially called an <strong>Opaque Type</strong>.</p><pre>func makePizza() -&gt; some View {<br>    return Text(&quot;Pepperoni&quot;)<br>}</pre><p>By using some, you are entering into a secret pact with the compiler</p><ul><li><strong>Publicly:</strong> You tell the rest of the app, “I am returning some View. Don&#39;t worry about the details.&quot;</li><li><strong>Privately:</strong> The compiler looks inside your function, sees you are returning a Text, and says, &quot;Okay! Text is 16 bytes. I will reserve exactly 16 bytes of space.&quot;</li></ul><p><strong>This is the magic trick.</strong> You get the clean, abstract code of a Protocol (“It’s just a View”), but you get the raw performance of Stack memory (“It’s exactly 16 bytes”).</p><p>The compiler is happy because it knows the size (Static Dispatch). You are happy because you don’t have to write ModifiedContent&lt;Text, _PaddingLayout&gt;.</p><h3>Why can’t we just return “View”?</h3><p>Now that you understand the memory constraints, the answer to “Why not just return View? i.e the conforming protocol&quot; becomes obvious.</p><pre>// ❌ Error: Protocol &#39;View&#39; can only be used as a generic constraint...<br>func makePizza() -&gt; View { ... }</pre><p>You are asking the compiler to reserve space for &quot;A View.&quot; The compiler asks: <em>&quot;Okay, which one? A tiny </em><em>Text or a massive </em><em>List?&quot;</em></p><p>You answer: <em>“I’m not telling.”</em></p><blockquote>The compiler panics. Since it can’t predict the size, it cannot allocate stack memory. Hence you cannot simply return a View</blockquote><blockquote>In Swift terms, the View protocol does not have a fixed memory layout.</blockquote><p>Additionally, View has an associatedtype called Body. To render a view, Swift needs to know what that Body type is. If you just return a raw View, you have erased that information.</p><p>Due to same reasons you can’t use “any” either.</p><h4>Why Doesn’t some work with if/else?</h4><p>At this point, you might spot a flaw in the some View logic.</p><p>I told you that some View is strict, it demands you return the <strong>exact same type</strong> every time. So, how on earth do you write an if/else statement?</p><pre>// ❌ Error: Function declares an opaque return type <br>// but has no return statements in its body...<br>func makeChoice(isHungry: Bool) -&gt; some View {<br>    if isHungry {<br>        return Text(&quot;Pizza&quot;) // Type: Text<br>    } else {<br>        return Image(&quot;Apple&quot;) // Type: Image<br>    }<br>}</pre><p>Above code fails because Text and Image are different sizes. The compiler can&#39;t build a single box that fits both perfectly.</p><h4>The solution: @viewBuilder</h4><p>This is where @ViewBuilder saves the day.</p><p>When you add @ViewBuilder to a function (or use it inside a body), Swift doesn&#39;t return one view <em>or</em> the other. It performs a fusion. It silently wraps both views into a brand new, single type called _ConditionalContent&lt;Text, Image&gt;</p><pre>@ViewBuilder<br>func makeChoice(isHungry: Bool) -&gt; some View {<br>    if isHungry {<br>        Text(&quot;Pizza&quot;)<br>    } else {<br>        Image(&quot;Apple&quot;)<br>    }<br>}</pre><blockquote>This wrapper type generated through “ViewBuilder” has a fixed size that accommodates both options, keeping the compiler happy and the Stack optimized.</blockquote><h3>Why Objective-C didn’t care</h3><p>If you’re from the Objective-C era, you remember returning id or UIView* freely.</p><p>Objective-C didn’t have the same problem because <strong>Objective-C didn’t deliver pizzas; it only delivered addresses.</strong></p><p>In Objective-C, everything is a Class (Reference Type). You never passed the object itself; you passed a <strong>Pointer</strong>. Since every pointer is exactly the same size (8 bytes), the compiler didn’t care if it pointed to a tiny string or a massive list of strings. It just passed the 8-byte address and figured out the rest later.</p><p>It was flexible, sure. But it was slower.</p><h3>Summary</h3><p>SwiftUI is obsessed with speed. It wants to put everything on the fast “Stack” memory, which requires knowing the exact size of every view at compile time.</p><ul><li><strong>some View</strong> lets the compiler see the size (Fast) while letting you hide the type name (Clean).</li><li><strong>View</strong> (raw protocol) is mathematically impossible to use on the Stack because it has no defined size.</li></ul><p>So next time you type some View, you aren&#39;t just satisfying the compiler, you are helping it optimize for speed and efficiency.</p><p><strong>Brain feeling a little bigger?</strong> 🧠<br>Theory is great, but let’s be honest, we are here to build cool stuff.</p><p>If you want to put that Swift knowledge to the test and flex those coding muscles, check out following medium articles:</p><ol><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong> I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e17e53fecace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Mutating and Copy-in-Copy-out Powers Swift: Under the Hood]]></title>
            <link>https://medium.com/@darshandodia/how-mutating-and-copy-in-copy-out-power-swift-under-the-hood-de60cc712552?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/de60cc712552</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[deep-dives]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 20:16:47 GMT</pubDate>
            <atom:updated>2026-02-05T20:20:02.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LN6-e_rBbcmTDKKr" /><figcaption>Photo by <a href="https://unsplash.com/@juvnsky?utm_source=medium&amp;utm_medium=referral">Anton Maksimov 5642.su</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have all been there. You are happily coding away, building a Swift struct. You decide it’s time for that struct to grow up and change one of its own properties. You write the line of code, hit build, and Xcode slaps you with its favorite red stop sign:</p><blockquote>“Left side of mutating operator isn’t mutable: ‘self’ is immutable”</blockquote><p>Excuse me? I defined the property as a var. Why is self crashing the party?</p><p>You sigh, add the mutating keyword before the func, Xcode is appeased, and you move on with your life. But what just happened? Why did you need to ask permission?</p><p>The answer lies deep in the architectural difference between value types and reference types, and a little piece of compiler sleight-of-hand called “Copy-In Copy-Out.”</p><p>Let’s pop the hood and see how Swift handles mutation without causing total anarchy.</p><h3>The Secret Identity of self</h3><p>Before we get to mutation, we need to talk about self.</p><p>When you write an instance method inside a struct (or a class), it feels like the method just inherently “knows” about the properties around it. But that’s not the truth</p><pre>struct Spaceship {<br>    var fuelLevel = 100<br>    <br>    func reportStatus() {<br>        // How does it know what &#39;fuelLevel&#39; is?<br>        print(&quot;Fuel is at \(fuelLevel)%&quot;)<br>    }<br>}</pre><p><strong>It’s not magic.</strong></p><p>Under the hood, the Swift compiler quietly rewrites your method to accept an invisible first parameter: self.</p><p>Your nice reportStatus() method actually looks something like this to the compiler:</p><pre>// Internal representation (pseudocode)<br>func reportStatus(self: Spaceship) {<br>    print(&quot;Fuel is at \(self.fuelLevel)%&quot;)<br>}</pre><p>Here is the kicker: By default, in a value type like a struct, that invisible self parameter is passed as a <strong>constant</strong>. It’s read-only. <br>It’s like a museum exhibit .. you can look, but if you touch, security (the compiler) kicks you out.</p><h3>Enter the mutating keyword</h3><p>When you want to change a property inside a struct method, you are effectively trying to modify that read-only self parameter. The compiler rightly freaks out.</p><p>By adding the mutating keyword, you are asking the compiler to change the rules of engagement. You are telling it: &quot;Hey, instead of passing self as a constant, pass it as an <strong>inout</strong> parameter.&quot;</p><pre>struct Spaceship {<br>    var fuelLevel = 100<br>    <br>    // The &#39;mutating&#39; keyword flips the switch<br>    mutating func engageHyperdrive() {<br>        fuelLevel -= 50<br>    }<br>}</pre><pre>// Internal representation (pseudocode)<br>// Notice the &#39;inout&#39; upgrade!<br>func engageHyperdrive(self: inout Spaceship) {<br>    self.fuelLevel -= 50<br>}</pre><p>Suddenly, self isn&#39;t a museum exhibit anymore. It’s a Google Doc with full edit access.</p><h3>The Magic Trick: Copy-In Copy-Out</h3><p>This is where things get weird. Since structs are value types, they don’t pass references around like classes do. So, how does inout actually modify the original variable if it doesn&#39;t have a pointer to its memory address?</p><p>Swift uses a mechanism that sounds like a bureaucratic nightmare but is actually quite brilliant: <strong>Copy-In Copy-Out</strong> (sometimes called call-by-value-result).</p><p>When you call a mutating method on a struct variable, here is the three-step dance that happens internally:</p><ul><li><strong>Copy-In:</strong> Swift takes your original struct instance and makes a temporary <em>copy</em> of it to pass into the method.</li><li><strong>Execution:</strong> The method runs and furiously modifies that temporary copy. The original struct is sitting outside, oblivious, sipping iced tea.</li><li><strong>Copy-Out:</strong> The moment the method finishes, Swift takes that modified temporary copy and <em>overwrites the original variable entirely</em> with the new version.</li></ul><p>It’s like borrowing your friend’s notebook, rewriting a whole page in a different location, and then sneaking it back into their backpack, replacing the original notebook before they notice.</p><h3>The Bouncer: Why You Need var</h3><p>Understanding Copy-In Copy-Out explains why you can’t call a mutating method on a struct defined with let.</p><pre>let trustyShip = Spaceship()<br>// Error: Cannot use mutating member on immutable value: &#39;trustyShip&#39; is a &#39;let&#39; constant<br>trustyShip.engageHyperdrive()</pre><p>Remember step 3: <strong>Copy-Out</strong>. The very last thing a mutating method does is <em>reassign the original variable</em> with the new, modified value.</p><p>If you define your struct instance with let, you have sworn an oath to the compiler that this variable will never be reassigned. The compiler knows that a mutating method’s ultimate goal is reassignment, so it stops you at the door.</p><p>To use mutation, the instance itself <em>must</em> be a var to survive the Copy-Out step.</p><h3>The Danger Zone: Threading and Race Conditions</h3><p>Copy-In Copy-Out is great for single-threaded code, but it becomes a horror movie in a multi-threaded environment.</p><p>Imagine two threads trying to call mutating methods on the same struct variable at the exact same time.</p><ul><li>Thread A “Copies-In” the struct (Value: 10).</li><li>Thread B “Copies-In” the <em>same</em> struct (Value: 10) before Thread A finishes.</li><li>Thread A changes its copy to 20 and “Copies-Out,” overwriting the original.</li><li>Thread B changes its copy to 30 and “Copies-Out,” overwriting Thread A’s work.</li></ul><p>This is a classic <strong>Race Condition</strong>. <br>Data gets lost, overwritten, or corrupted because the “Copy-Out” step violated Swift’s “Law of Exclusivity” (No two processes must access the same memory when one of them is writing).</p><p><strong>The Solution?</strong> <br>Don’t use mutating structs for shared state across threads. <br>In modern Swift, if you need mutable state that is safe to access concurrently, wrap it in an <strong>Actor</strong>.</p><p>Actors are reference types that act like strict librarians, forcing threads to form a neat, orderly queue before they can touch the data, preventing the chaos of simultaneous Copy-Outs.</p><h3>Summary</h3><p>The mutating keyword isn&#39;t just syntactic sugar to make Xcode happy. It’s a signal to the compiler to fundamentally change how self is handled, switching from a read-only view to a read-write inout flow managed by the clever Copy-In Copy-Out dance.</p><p>Next time you type mutating, take a second to appreciate the invisible work Swift is doing to keep your value semantics intact while still letting you change things up.</p><p><strong>Brain feeling a little bigger?</strong> 🧠 <br>Theory is great, but let’s be honest, we are here to build cool stuff. If you want to put that Swift knowledge to the test and flex those coding muscles, check these out:</p><ol><li><a href="https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872">Recreate that sleek <strong>CRED credit card animation</strong> in SwiftUI: Implementation</a></li><li><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Build a <strong>Custom Network Listener and Mocker</strong> in Swift: Implementation</a></li></ol><p><strong>Don’t be a stranger!</strong> I’m always cooking up new projects and insights. <br>Come say hi (or roast my code): <br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a> <br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de60cc712552" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why CRED’s iOS Card Animation Feels So Good!]]></title>
            <link>https://medium.com/@darshandodia/why-creds-ios-card-animation-feels-so-good-0655d97d5872?source=rss-6059a18e39a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/0655d97d5872</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftui-animation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Darshan Dodia]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 19:37:36 GMT</pubDate>
            <atom:updated>2026-02-05T20:26:37.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V1ngDrCHjqw3hNG3" /><figcaption>Photo by <a href="https://unsplash.com/@averye457?utm_source=medium&amp;utm_medium=referral">Avery Evans</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We have all come across apps where the animations are so fluid and delightful, they instantly elevate the user experience. As a designer, creating these animations can be a fun, creative process, but for developers, bringing them to life often means navigating a maze of complexity and frustration.</p><p>In this Medium article, I will walk you through a step-by-step tutorial on implementing a credit card spread animation inspired by the CRED app.</p><p>You can find the complete code here: <a href="https://github.com/Darshan-D/Cred-CardSpreadAnimation">Github Link</a></p><p><a href="https://github.com/Darshan-D/Cred-CardSpreadAnimation">GitHub - Darshan-D/Cred-CardSpreadAnimation: Mimics the credit card spread animation from the CRED App.</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD4nyYXyJoEs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD4nyYXyJoEs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD4nyYXyJoEs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/59dae6027e74222764a1273435497519/href">https://medium.com/media/59dae6027e74222764a1273435497519/href</a></iframe><p>Let’s deconstruct how to build this animation in SwiftUI. While it may look complex, the implementation relies on a clean separation of concerns, a solid handle on state management, and a straightforward application of animation principles.</p><p>The final animation is achieved through three core concepts:</p><ol><li><strong>State-Driven UI:</strong> Using @State variables as the “levers” to control every phase of the animation.</li><li><strong>Interpolation:</strong> Applying simple math to calculate a view’s properties (like offset and scale) as it moves between two defined states.</li><li><strong>Seamless View Transition:</strong> Employing a clever presentation trick to switch from an animated preview to a fully interactive view.</li></ol><h3>Part 1: The State Architecture</h3><p>The foundation of any SwiftUI animation is its state. To build our card stack, we need a few key variables to act as the “brain” of our operation.</p><pre>/// The source of truth for the card data.<br>@State private var cards: [CardInfo] = sampleCards<br><br>/// Tracks the user&#39;s raw gesture input in real-time. This is our live feedback.<br>@State private var dragOffset: CGSize = .zero<br><br>/// A boolean that defines the animation&#39;s target state: `false` for stacked, `true` for spread.<br>@State private var isSpreadForAnimation: Bool = false<br><br>/// A boolean to trigger the presentation of the separate, fully scrollable list view.<br>@State private var showExpandedListView: Bool = false</pre><ul><li><strong>dragOffset</strong>: Think of this as the raw, chaotic energy from the user’s finger. It follows the gesture precisely, giving the interaction its immediate, connected feel.</li><li><strong>isSpreadForAnimation</strong>: This is the “manager” that decides the final goal. When it flips to true, it tells the cards, “Okay, everyone, gracefully move to your spread-out positions.” This drives the clean, non-interactive part of the animation.</li><li><strong>showExpandedListView</strong>: This is our “stagehand,” waiting in the wings to seamlessly switch the scenery once the first act of our animation is complete.</li></ul><h3>Part 2: The Core Logic — A Quick Trip to Math Class</h3><p>Okay, deep breaths. We are going to look at the math that makes this work. The good news is, it’s all based on one simple concept you already understand .. <strong>interpolation</strong>.</p><p>Think of a dimmer switch. 0% is off. 100% is fully on. 50% is halfway. Interpolation is just finding any value in between. The formula for this is:</p><p><em>currentValue = startValue + (endValue — startValue) * progress</em></p><p>Our <em>progress</em> will be a number from <em>0.0 </em>to <em>1.0</em>.</p><h4>The Brains: getTransitionProgress()</h4><p>Our first job is to turn the messy <em>dragOffset</em> into a clean progress value between 0.0 and 1.0. This is the job of getTransitionProgress().</p><pre>/// Calculates the current progress of the spread/stack animation, from 0.0 (stacked) to 1.0 (spread).<br>private func getTransitionProgress(for dragOffsetY: CGFloat) -&gt; CGFloat {<br>    let transitionSensitivity = Configuration.cardViewHeight // How much drag completes the transition.<br>    <br>    if isSpreadForAnimation {<br>        // We&#39;re already spread. A downward drag (positive offsetY) should move progress back to 0.<br>        return 1.0 - min(1.0, max(0, dragOffsetY / transitionSensitivity))<br>    } else {<br>        // We&#39;re stacked. An upward drag (negative offsetY) should move progress towards 1.<br>        return min(1.0, max(0, -dragOffsetY / transitionSensitivity))<br>    }<br>}</pre><p>This function takes the raw drag and does two things:</p><ol><li>It divides the drag distance by a sensitivity value (the height of a card) to get a raw progress number.</li><li>It uses min(1.0, max(0, …)) to <strong>clamp</strong> the result. This is a fancy way of saying we’re putting the value in a safe little box, ensuring it never goes below 0.0 or above 1.0.</li></ol><h4>The Muscles: calculateYOffset() and calculateScale()</h4><p>Now that we have a clean progress value, we can use our interpolation formula to calculate the final position and size of each card.</p><p>Let’s look at <em>calculateYOffset()</em>:</p><pre>private func calculateYOffset(for stackIndex: Int, dragOffsetY: CGFloat) -&gt; CGFloat {<br>    // The top card is special. It just follows your finger.<br>    if stackIndex == 0 {<br>        return dragOffsetY<br>    }<br>    <br>    // 1. Define the two &quot;goalposts&quot;: where the card is when stacked, and where it is when spread.<br>    let yForStacked = CGFloat(stackIndex) * Configuration.stackedYOffset<br>    let yForSpreadList = CGFloat(stackIndex) * (Configuration.cardViewHeight + Configuration.listSpacing)<br>    <br>    // 2. Get our clean 0-to-1 progress value.<br>    let transitionProgress = getTransitionProgress(for: dragOffsetY)<br>    <br>    // 3. Interpolate! Find the current position based on the progress.<br>    return yForStacked + (yForSpreadList - yForStacked) * transitionProgress<br>}</pre><p>That’s it! We’re just telling SwiftUI, “Here’s the start position, here’s the end position, and here’s how far along the path you should be right now.” The calculateScale function does the exact same thing, but for the card’s size.</p><h3>Part 3: The Secret — It’s All Smoke and Mirrors</h3><p>Here comes the fun part. The part that makes this animation feel so magical when the cards are completely spread out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jW9L_WSFBg73k3vNDDNCUA.png" /></figure><p>You might think we make our <em>ZStack</em> of animating cards scrollable once it’s spread out. You could try, but you’d enter a world of pain, fighting gestures and ScrollView internals. There is a much, much sneakier way.</p><p><strong>We use two different views.</strong></p><p>The user <strong><em>thinks</em></strong> they are watching one continuous animation. What they are <strong><em>actually</em></strong> seeing is <strong>two different views</strong>!</p><p>Here’s the switcheroo, explained by our DragGesture’s .onEnded block:</p><pre>.onEnded { value in<br>    // ...<br>    if dragDistance &lt; -dragStateChangeThreshold {<br>        // 1. Tell the cards to animate to their spread-out positions.<br>        self.isSpreadForAnimation = true<br>        <br>        // 2. THE MISDIRECTION: While the user is watching the pretty animation,<br>        // we secretly start a timer.<br>        DispatchQueue.main.asyncAfter(deadline: .now() + Configuration.transitionDelay) {<br>            <br>            // 3. THE REVEAL: After the timer fires, we slap a completely different,<br>            // simple, scrollable list view (`ExpandedCardListView`) on top of everything.<br>            self.showExpandedListView = true<br>        }<br>    }<br>    // ...<br>}</pre><p>The trick is to make sure the final resting state of our <em>animatingCardsLayer</em> looks <em>exactly</em> like the top of the <em>ExpandedCardListView</em>. When the new view appears, the user’s eye doesn’t register the switch. They just see the cards they were dragging settle into a list, which they can now magically scroll.</p><p>Dismissing the list works in reverse. When <em>ExpandedCardListView</em> is dismissed, its onDismiss callback simply flips our “master switch” (<em>isSpreadForAnimation = false</em>), and the original view underneath gracefully animates back into a neat stack.</p><h3>And That’s a Wrap!</h3><p>By combining clean state management, a bit of simple interpolation math, and a clever UI trick, we have created a complex, professional-looking animation without any mind-bending code.</p><p>The next time you see a slick animation, remember: it might not be as complicated as it looks. It might just be a little bit of math, and a whole lot of well-timed smoke and mirrors.</p><p>Now go build something magical! ✨</p><p>Also checkout my other article on how to mock / monitor network responses locally without any third party app:</p><p><a href="https://medium.com/@darshandodia/mock-smarter-not-harder-an-api-stubbing-tools-journey-c7ee519b39ad">Mock Smarter, Not Harder: An API Stubbing Tool’s Journey</a></p><p><strong>Don’t be a stranger!</strong> I’m always cooking up new projects and insights.<br>Come say hi (or roast my code):<br>🐙 <a href="https://github.com/Darshan-D"><strong>GitHub</strong></a><br>💼 <a href="https://www.linkedin.com/in/darshan-dodia/"><strong>LinkedIn</strong></a></p><p>Cheers 🙌🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0655d97d5872" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>