<?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 Amanprajapati on Medium]]></title>
        <description><![CDATA[Stories by Amanprajapati on Medium]]></description>
        <link>https://medium.com/@amanp183rajapati?source=rss-0e28be922806------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gHBBglHYuqKEEmQZ</url>
            <title>Stories by Amanprajapati on Medium</title>
            <link>https://medium.com/@amanp183rajapati?source=rss-0e28be922806------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:18:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amanp183rajapati/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[I watched Apple unveil Liquid Glass — and felt behind before it even shipped]]></title>
            <link>https://medium.com/@amanp183rajapati/i-watched-apple-unveil-liquid-glass-and-felt-behind-before-it-even-shipped-f52f102492e3?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/f52f102492e3</guid>
            <category><![CDATA[apple-liquid-glass]]></category>
            <category><![CDATA[apple-wwdc]]></category>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 18:14:52 GMT</pubDate>
            <atom:updated>2026-06-01T18:14:52.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*jmsiKH2VfCdnvcTTME6Dxg.jpeg" /></figure><p><strong>A developer’s honest story about curiosity, the weight of keeping up, and what happened when I finally stopped watching and started building.</strong></p><p>THE MOMENT IT STARTED</p><p>Every year, the same feeling.</p><p>WWDC opens. Apple walks onto the stage. And before the session is even halfway through, a quiet voice in the back of my head starts its familiar routine — <em>you haven’t finished what they showed last year. You still haven’t explored that API from two years ago. And now this.</em></p><p>This year, that thing was Liquid Glass.</p><p>I watched the keynote like thousands of other iOS developers. I saw the UI morph. I saw those surfaces catch light the way real glass does — with depth, with refraction, with a quality that looked less like a screen and more like something physical you could reach into. And somewhere between admiration and mild anxiety, I thought: I need to understand how this actually works.</p><blockquote>“Every year Apple ships something beautiful. And every year I feel the gap between what they showed and what I know how to build.”</blockquote><p>But I didn’t open Xcode that day. I did what most of us do — I kept scrolling.</p><p><strong>THE PINTEREST MOMENT : —</strong></p><p>A few weeks after WWDC, Liquid Glass started appearing everywhere. Pinterest. Dribbble. Twitter. Design inspiration accounts were exploding with it — buttons that looked like water, cards that felt like frosted crystal, navigation bars that seemed to float above the content beneath them.</p><p>I kept saving them. Screenshot after screenshot. Not because I was going to use them — I just liked looking at them. The way you linger on something beautiful without quite knowing what to do with it.</p><p>Then one morning I stopped saving and started asking. How is this actually built? Not the concept — the code. What does Apple’s API look like for this? Does it exist yet? Can I use it today?</p><p>I opened Safari. Typed the most developer thing you can type: <em>SwiftUI Liquid Glass how to use.</em></p><p>Then I went to the source — Apple’s own documentation. And what I found there changed the direction of my next few weeks entirely.</p><p><strong>GOING TO THE SOURCE : —</strong></p><p>Apple’s documentation for Liquid Glass is surprisingly clean. The concept is clear: this isn’t a visual trick layered on top of existing APIs. It’s a new rendering primitive — a first-class material that the system computes in real time, sampling the colors and content beneath a view and refracting them like actual glass would.</p><p>You can’t fake this with .ultraThinMaterial and a white stroke overlay. I know because I tried. The result looked like frosted plastic — dull, flat, nothing like what I’d been saving on Pinterest.</p><p>The real API is different. Simpler in some ways than I expected. But it required me to think about UI construction differently — not stacking modifiers until something looks right, but trusting a system that handles the physics of light and depth at a level I don’t have direct access to.</p><p>That was the first real lesson. And I hadn’t written a single line of production code yet.</p><p><strong>THE DECISION : -</strong></p><p>I could have stopped at documentation. Read it, nodded, filed it away as something to use someday.</p><p>But I’ve done that before — with every WWDC feature I never quite found the time for. And I was tired of the accumulation. Tired of the gap between things I’d seen and things I actually understood.</p><p>So I made a decision that felt small but turned out not to be: I would build a component library. Not an app. Not a demo. A proper, open-source, Swift Package Manager library called LiquidGlassKit — with tokens, modifiers, and real reusable components built entirely on the iOS 26 Liquid Glass API.</p><p>The goal wasn’t to ship something people would use. The goal was to understand something deeply. Building forces a kind of understanding that reading never can.</p><blockquote>“Reading documentation tells you what something is. Building tells you what it costs.”</blockquote><p>THE FIRST ERROR</p><p>I opened Xcode 26 Beta, created a new Swift Package, and wrote what felt like a perfectly reasonable first line:</p><pre>.glassEffect(Glass().tint(.blue).interactive())<br><br>error: &#39;Glass&#39; cannot be constructed because it has no accessible initializers</pre><p>error: ‘Glass’ cannot be constructed because it has no accessible initializers</p><p>It is a special kind of humbling — when you are confident enough to type something without checking, and the compiler corrects you in four words.</p><p>I went back to the documentation. Read more carefully this time. Slower. The way you read when you’re no longer in a hurry to feel smart.</p><p>Turns out Apple didn’t give developers a Glass() constructor. They gave us something better — a purpose-built button style and a view modifier that does everything correctly without requiring you to configure the rendering yourself.</p><pre>Button(&quot;Get Started&quot;) { }<br>  .buttonStyle(.glass)          // for buttons<br><br>Text(&quot;Hello&quot;)<br>  .padding()<br>  .glassEffect()              // for any view<br><br>GlassEffectContainer {<br>  // your glass views here — they merge<br>}                             // into one crystal surface</pre><p>GlassEffectContainer was the piece most early tutorials skipped. Without it, glass elements sit independently on screen — visually separate, like ice cubes in a glass rather than the glass itself. Inside the container, they blend. They share light. They feel like one surface. That’s the difference between something that looks like Liquid Glass and something that actually is it.</p><p><strong>WHAT I BUILT — AND WHAT IT TAUGHT ME : -</strong></p><p>Over the following days I built the library properly. First the foundation: LGTokens — a single file holding every radius, spacing, opacity, shadow, and animation value the library would ever use. Design DNA, written once, referenced everywhere.</p><p>Then GlassModifier — a reusable ViewModifier so no component would ever repeat the same setup. Then LGButton, the first real component. Primary, secondary, and destructive variants. Spring animation on press. Symbol effects that bounce on tap. All of it sitting on the correct iOS 26 API, wrapped in a GlassEffectContainer, previewed over a gradient with blurred color blobs behind it — because Liquid Glass needs a rich background to reveal what it actually is.</p><p>The first time the preview loaded and I saw the real refraction — the crystal clarity, the depth, the way the color beneath the button bent slightly through the surface — I understood why I’d been saving those Pinterest images for weeks.</p><p>It wasn’t the visual. It was the feeling of finally knowing how the visual was made.</p><blockquote>THE THING UNDERNEATH THE THING : —</blockquote><p>There’s a pattern I keep running into in Apple’s newer APIs. The old approach was: give developers the raw ingredients and let them cook. The new approach is increasingly: here is the dish, trust that we cooked it correctly, focus on what you’re trying to say rather than how the renderer works.</p><p>Liquid Glass is the most visible expression of that shift yet. Apple isn’t asking you to understand the refraction math. They’re asking you to place your content, choose your container, and let the system do the physics.</p><p>For developers who love control — and most of us do — this is uncomfortable at first. It feels like a black box. It feels like giving something up.</p><p>But when you actually work with it, when you stop trying to replicate it manually and start using it the way it was designed, something clicks. The result is better than anything you could have stacked together yourself. And you realize the control you were holding onto was just friction dressed up as craftsmanship.</p><blockquote>“The result is better than anything you could have stacked together yourself. The control you were holding onto was just friction dressed up as craftsmanship.”</blockquote><p><strong>FOR EVERY DEVELOPER WHO FELT BEHIND : -</strong></p><p>I started this with that familiar WWDC feeling — the quiet accumulation of things I hadn’t learned yet, features I’d bookmarked and never revisited, APIs I understood conceptually but couldn’t build from memory.</p><p>I still have that list. It’s still long. Apple will add to it again next June, and the June after that.</p><p>But Liquid Glass taught me something I want to carry into every future WWDC: the gap closes faster than you think when you stop watching and start building. Even one component. Even one file. Even one compile error that sends you back to the documentation to read more carefully.</p><p>The curiosity that started with a Pinterest scroll and ended with an open-source Swift Package — that’s the whole job, really. Stay curious. Go to the source. Build the thing you don’t fully understand yet.</p><p>The glass was always there. You just have to stop trying to fake it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wK4IbUDfsEaqWZBIq1na6w.jpeg" /></figure><p><em>I hope you enjoyed this story. 🚀<br>Keep hustling, keep coding, and keep life sorted .</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f52f102492e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Bachelor Struggles Life: Understanding ARC in iOS]]></title>
            <link>https://medium.com/@amanp183rajapati/from-bachelor-struggles-life-understanding-arc-in-ios-cae03bc726f0?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/cae03bc726f0</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 21:31:17 GMT</pubDate>
            <atom:updated>2025-09-10T21:31:17.825Z</atom:updated>
            <content:encoded><![CDATA[<p>Strong, weak, and unowned references explained with chores, groceries, and married life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*j-iLEfbLvB8GDUzyLnQWwQ.jpeg" /></figure><h3>ARC in iOS: From Bachelor Life</h3><p>When an <strong>engineer guy</strong> working 9–5 in a metro city, life felt like an endless loop. He’d go to the office, come back to his rented flat, and then the real struggle started: cleaning the room, washing clothes, cooking, and filling up groceries. Weekends? No rest. Just more chores.</p><p>That was his life cycle. Everything was on him — a little real story everyone can see around.</p><h3>🚀 Enter partner (ARC’s Arrival)</h3><p>Then one day, the engineer guy got married to a wonderful woman — also an engineer. Suddenly, life changed. Now they worked together, shared responsibilities, and even had time to chill out.</p><p>He wasn’t alone anymore. The workload was automatically balanced. This is exactly what <strong>Automatic Reference Counting (ARC)</strong> in iOS does.</p><h3>🧑‍💻 The Bachelor = Manual Memory Management</h3><p>As a bachelor, the engineer guy had to <strong>retain and release responsibilities manually</strong>. Forget laundry one week? His room looked like a memory leak. Do it too soon? He had nothing to wear — just like an app crashing because of an over-release.</p><p>Before ARC, developers had to do this for every object. Painful and error-prone.</p><h3>Life with ARC :</h3><p>After marriage, responsibilities were shared automatically. The engineer guy didn’t need to keep track of who would cook or clean — things just happened in balance.</p><p>That’s how ARC works. It automatically inserts the retain and release calls for you. When no one needs an object anymore, it quietly deallocates it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*nIs1OrSzD4sHL70aeTvYUA.jpeg" /></figure><blockquote>This story is make fun with remember ARC in real life. so let’s deep dive into the technical story.</blockquote><p><strong>What is ARC in ios ??????</strong></p><p>Automatic Reference Counting (ARC) is a memory management feature in Swift that automatically manages the allocation and deallocation of objects in your code. It helps you avoid memory leaks and manage memory efficiently without requiring manual memory management.</p><p><strong>How ARC works :::::::: — — — —??</strong></p><p>ARC works by tracking the number of strong references to each object in your code. When an object has no more strong references, it is deallocated and its memory is freed. Strong references are the default type of reference in Swift, but you can also use weak and unowned references to break strong reference cycles.</p><h3>Strong references :-</h3><p>A strong reference keeps a strong hold on an object, meaning it prevents the object from being deallocated. As long as there is at least one strong reference to an object, it will remain in memory.</p><pre>// this example with fun story<br>class Husband {<br>    var wife: Wife? // strong reference<br>}<br>class Wife {<br>    var husband: Husband? // strong reference<br>}</pre><p>To resolve strong reference cycle swift provides weak and Unowned References.</p><h3>Weak references :-</h3><p>It is an optional reference to an object that does not keep a strong hold on the object. It will return nil when the object it refers to is deallocated. It is generally used where the referenced objects lifecycle is not guaranteed to outlive the referencing object.We can declare weak references using the <strong>weak</strong> Keyword.</p><pre>class Wife {<br>    weak var husband: Husband? // weak reference avoids cycle<br>}</pre><h3>Unowned References :-</h3><p>It is a non-optional reference to an object that does not keep a strong hold on the object as compared to a weak reference. It assumed that the reference object will never become nil, while the reference object is still alive. It is generally used where you know that the referenced objects life is guaranteed to be at least as long as the referencing objects lifetime. We can declare unowned references using the <strong>unowned</strong> Keyword.</p><pre>class BankAccount {<br>    unowned var owner: Wife // always assumes owner exists &#39;evey home is technically wife is the owner&#39;.<br>}</pre><h3>🎯 The Takeaway</h3><ul><li><strong>Bachelor life = Manual retain/release</strong> (tiring, error-prone)</li><li><strong>Married life = ARC</strong> (automatic, shared responsibilities)</li><li><strong>Strong references = Shared responsibilities</strong></li><li><strong>Weak references = Optional support</strong></li><li><strong>Unowned references = Permanent, no-questions-asked bond</strong></li></ul><p>ARC, like a supportive partner, keeps life running smoothly without the engineer guy micromanaging every little thing.</p><p>So whenever the engineer guy writes Swift code, he smiles — because he knows his app is living the <strong>married life with ARC</strong>, not the <strong>bachelor life of manual memory management</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*2pSSmDusg4bKHnNAOZgq6g.png" /></figure><blockquote>I hope you enjoyed this story. 🚀<br> Keep hustling, keep coding, and keep life sorted — just like ARC does for iOS.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cae03bc726f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Lifecycle Explained -Through the Eyes of an Indian Family]]></title>
            <link>https://medium.com/@amanp183rajapati/ios-lifecycle-explained-through-the-eyes-of-an-indian-family-56365a9e7eea?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/56365a9e7eea</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Sat, 26 Jul 2025 09:40:50 GMT</pubDate>
            <atom:updated>2025-07-26T09:40:50.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESXa2Q-EMNA6-w_zaMRQ8A.jpeg" /></figure><h3>🏡 The Story of the Indian Family: Understanding View Controllers in iOS</h3><p>Once upon a time, in the heart of India, lived the family.<br> Their household ran smoothly not because everything was perfect, but because everyone had a <strong>role</strong> — just like in an iOS app, where each <strong>View Controller</strong> plays a special part on each screen.</p><h3>👨‍👩‍👧‍👦 Meet the Indian Family</h3><ul><li><strong>Papa (father)(ViewController)</strong> — The <strong>manager of the home</strong>.</li><li><strong>Mummy (mother)(View)</strong> — The <strong>face of the home</strong>, everything you see and feel.</li><li><strong>childern (UI Elements)</strong> — The <strong>buttons</strong>, <strong>labels</strong>, and <strong>text fields</strong> — the ones who interact with you.</li><li><strong>Dadaji (AppDelegate)</strong> — The wise elder who starts the whole house and watches over all.</li></ul><h3>🧠 Papa (father)— The View Controller</h3><p>Papa (father)is the <strong>brain</strong> of the house.<br> He doesn’t directly decorate or cook, but he makes <strong>sure everything runs smoothly</strong>:</p><ul><li>When guests arrive (users open the app), he tells Mummy(mummy) what to prepare (load the view).</li><li>He tells his childern what to do when someone asks a question (respond to button taps).</li><li>He decides what happens next — like going from the living room to the kitchen (navigating screens).</li></ul><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    print(&quot;Everything is set up in the house!&quot;)<br>}</pre><h3>👩 Mummy (Mother)— The View</h3><p>Mummy (mother)is the <strong>soul of the UI</strong>.<br> She:</p><ul><li>Sets up the sofa, curtains, and tea cups (buttons, images, labels).</li><li>Makes the house look <strong>beautiful and welcoming</strong>.</li></ul><p>But she doesn’t act on her own. She listens to Papa’s (father) instructions (ViewController’s logic).</p><h3>🧒👧 Childern — The Interactive Elements</h3><p>Riya is like the <strong>Login button</strong> — when you tap her, something happens.<br> Rahul is the <strong>text field</strong> — he listens and stores what you say.</p><p>But remember:<br> They’re <strong>only functional</strong> when papa (father) connects them to actions:</p><pre>@IBAction func loginTapped(_ sender: UIButton) {<br>    print(&quot;child responded to the Login button!&quot;)<br>}</pre><h3>👴 Dadaji — The App Delegate</h3><p>He’s the elder who <strong>starts the house every morning</strong>.</p><ul><li>He <strong>opens the door</strong> (app launch).</li><li>Prepares basic utilities like water and electricity (background tasks).</li><li>Then he tells Papa (father) (View Controller) to take over the daily duties.</li></ul><pre>func applicationDidFinishLaunching(_ application: UIApplication) {<br>    print(&quot;Dadaji: Beta, start the day!&quot;)<br>}</pre><h3>🏃‍♂️ Going to School — Navigation Controller</h3><p>When childern leave home for school, who manages where they go?</p><p>Enter the <strong>Auto-rickshaw Uncle</strong> — also known as the <strong>Navigation Controller</strong>!</p><p>He knows how to:</p><ul><li>Pick them up from home (push the current screen).</li><li>Drop them to school (navigate to a new screen).</li><li>Bring them back safely (pop back).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wwVAeZxiMhO5kNy3BAPfg.png" /></figure><h3>🛏️📅 Scene: A Morning in the Indian House</h3><p>Let’s say it’s a <strong>Monday morning</strong>, and the house (the app screen) is just about to wake up.</p><h3>🧱 Step 1: loadView() – Building the House</h3><p>Before anything happens, <strong>someone must build the house</strong>.</p><p>In our story, this is what happens when <strong>Mummy (Mother)gets the home ready</strong> — making the beds, setting up the kitchen, cleaning the floor.</p><p>👩‍🍳 But she doesn’t do it on her own!<br> She does it <strong>only if needed</strong>, when there’s no <strong>Storyboard</strong> or <strong>XIB</strong> pre-made.</p><p>So:</p><ul><li>If you design the UI in <strong>Storyboard</strong>, you don’t usually touch loadView.</li><li>But if you want to build everything manually with code, <strong>you override </strong><strong>loadView()</strong>.</li></ul><p>🧠 <strong>Think of it like this</strong>:<br> loadView() = <em>&quot;Create the stage before the actors come in.&quot;</em></p><pre>override func loadView() {<br>    // Build your entire view hierarchy here<br>    let mainView = UIView()<br>    mainView.backgroundColor = .white<br>    self.view = mainView<br>}</pre><h3>🪄 Step 2: viewDidLoad() – Setting Things Up</h3><p>Now that the house is built, <strong>Papa (father)walks in</strong> to set up the day’s plan.</p><p>This is where he:</p><ul><li>Assigns tasks to childern(e.g., set button actions).</li><li>Opens the morning newspaper (fetch data).</li><li>Checks if everything is placed correctly (adjusts UI).</li><li>Maybe sets a reminder for the day (setup logic).</li></ul><p>This method is <strong>always called</strong> after the view is loaded (whether from Storyboard or programmatically).</p><p>🧠 <strong>Think of it like this</strong>:<br> viewDidLoad() = <em>&quot;Everything’s ready. Now prepare it for use.&quot;</em></p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    print(&quot;Papa (father): Let’s start the day!&quot;)<br>    <br>    label.text = &quot;Welcome!&quot;<br>    button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)<br>}</pre><p><strong>You rarely override </strong><strong>loadView() unless you&#39;re doing manual UI creation (no storyboard or XIB).<br> But you almost always override </strong><strong>viewDidLoad() to do setup work.</strong></p><h3>Scene: Guests Are Coming to Visit the IndianHouse</h3><p>The Indian family loves hosting guests (users navigating to their screen). Let’s continue with our family analogy.It’s morning, and <strong>a guest is about to arrive</strong> at the Sharma house (i.e., a new screen is about to appear).</p><p><strong>Papa (father)</strong>gets a notification:</p><blockquote><strong><em>“Beta, guests are on their way!”</em></strong></blockquote><p>So what does he do?</p><ul><li>He checks if the tea is ready ☕️</li><li>Makes sure the lights are on 💡</li><li>Tells Riya to wear proper clothes 👗</li><li>Updates the welcome message 📝</li></ul><p>He doesn’t <strong>change the furniture</strong> (that’s layout), but he <strong>prepares things just before the guest walks in.</strong><br> viewWillAppear(_:) is called <strong>just before the view appears on screen</strong>, every time it’s about to be shown.</p><p>You use it to:</p><ul><li>Refresh UI if needed</li><li>Start animations</li><li>Update data that might’ve changed</li></ul><pre>override func viewWillAppear(_ animated: Bool) {<br>    super.viewWillAppear(animated)<br>    print(&quot;Papa (father): Hurry, guests are coming. Let’s get ready!&quot;)<br>    greetingLabel.text = &quot;Namaste!&quot;<br>}</pre><p>🛋️ viewWillLayoutSubviews() — <strong>Rearranging the Furniture</strong></p><p>Now, before the guests step in, <strong>Mummy (Mother)</strong>walks around the house and says:</p><blockquote><em>“Hmm… the sofa looks too close to the window. Let’s shift it a little.”<br> “Move the dining table to the side.”</em></blockquote><p>She’s not changing who’s visiting or what the kids are doing — <br> She’s just <strong>rearranging the layout</strong>, so the house looks perfect <strong>based on the current space</strong> (like screen size or orientation).</p><h4><strong>viewWillLayoutSubviews()</strong></h4><p>is called <strong>every time before the view lays out its subviews.</strong></p><p>You use it to:</p><ul><li>Adjust positions of UI elements</li><li>Handle rotation/resizing changes</li><li>Manually tweak frame-based layout</li></ul><pre>override func viewWillLayoutSubviews() {<br>    super.viewWillLayoutSubviews()<br>    print(&quot;Mummy (mother): Let me adjust the sofa before guests come in.&quot;)<br>    <br>    imageView.frame = CGRect(x: 20, y: 100, width: view.frame.width - 40, height: 200)<br>}</pre><p><strong>viewDidAppear(_:) – The Guest Has Arrived!</strong></p><p>As soon as the guest steps into the Sharma house,<br> Papa Sharma stands up and says:</p><blockquote><em>“Ah, welcome! You’re finally here. Let’s begin the fun.”</em></blockquote><p>This is where:</p><ul><li>Animations begin 🌀</li><li>Videos autoplay 📺</li><li>Analytics tracking starts 📊</li></ul><pre>override func viewDidAppear(_ animated: Bool) {<br>    super.viewDidAppear(animated)<br>    print(&quot;Papa (father): Welcome, Guest. Let’s begin!&quot;)<br>}</pre><h4>viewWillDisappear(_:) – The Guest Is About to Leave</h4><p>Now the guest is about to leave, so Papa starts winding down the evening.</p><ul><li>He stops the music 🎵</li><li>Pauses any ongoing activities</li><li>Saves any in-progress work</li></ul><pre>override func viewWillDisappear(_ animated: Bool) {<br>    super.viewWillDisappear(animated)<br>    print(&quot;Papa (father): Guests are leaving soon. Wrap it up.&quot;)<br>}</pre><h4>viewDidDisappear(_:) –</h4><p>The Guest Has Left the Building . As soon as the guest steps out, Papa closes the door behind them and sighs…</p><ul><li>Cleans up mess (temporary UI cleanup)</li><li>Stops tracking</li><li>Ends background tasks</li></ul><pre>override func viewDidDisappear(_ animated: Bool) {<br>    super.viewDidDisappear(animated)<br>    print(&quot;Papa (father): Guest has left. Time to relax.&quot;)<br>}</pre><h4>deinit –</h4><h4>Papa (father)Retires (View Controller is Gone)</h4><p>One day, if the app no longer needs this screen, the system releases it from memory.</p><blockquote><em>Papa Sharma quietly packs his bags and retires to the hills. 🧳🌄</em></blockquote><p>This is the deinit method — called <strong>once when the ViewController is destroyed</strong>.</p><pre>deinit {<br>    print(&quot;Papa (father): My time here is done. Goodbye, world!&quot;)<br>}</pre><p>Use it to:</p><ul><li>Clean up observers</li><li>Close connections</li><li>Release memory</li></ul><h4>didReceiveMemoryWarning() –</h4><p>The House is Running Out of Space! One sudden day, the Sharma house is overloaded with guests and food and photos! Dadaji yells:</p><blockquote><em>“There’s no space left in the house! Throw out unnecessary stuff!”</em></blockquote><p>This is iOS sending a <strong>memory warning</strong> when your app uses too much memory.</p><pre>override func didReceiveMemoryWarning() {<br>    super.didReceiveMemoryWarning()<br>    print(&quot;Dadaji: Delete what&#39;s not needed now!&quot;)<br>    // Clear caches, images, temporary data<br>}</pre><h4>viewWillTransition(to:with:) –</h4><p>House Rotation (Orientation Change) The house gets rotated (maybe flipped or resized).</p><p>Mummy (father)quickly runs to rearrange the furniture.</p><blockquote><em>“Turned sideways? Okay, move the sofa, shift the table!”</em></blockquote><p>This method is triggered <strong>when the device rotates</strong>.</p><pre>override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {<br>    super.viewWillTransition(to: size, with: coordinator)<br>    print(&quot;Mummy (Mother): Rotate ho gaya! Rearranging furniture.&quot;)<br>}</pre><p>Use it to:</p><ul><li>Adjust layout for landscape/portrait</li><li>Handle custom animations during rotation</li></ul><blockquote><em>“An app without structure is like a home without harmony.<br> A screen without a ViewController is like a family without a Papa (father).”<br> — </em>An iOS Dev with ❤️ for clean code</blockquote><p>✨ Keep coding with purpose.<br> ✨ Keep architecting with clarity.<br> ✨ And like the Sharma family…</p><blockquote><strong><em>“Keep Hustling, Keep Growing.”</em></strong><em> 💪📱🚀</em></blockquote><p>If you ever feel lost in your code… Just remember Papa (father)saying:</p><blockquote><em>“Beta, viewDidLoad karo… aur zindagi set ho jaayegi.” 😄</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56365a9e7eea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“A Story of AppDelegate and SceneDelegate”]]></title>
            <link>https://medium.com/@amanp183rajapati/a-story-of-appdelegate-and-scenedelegate-45087f07312e?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/45087f07312e</guid>
            <category><![CDATA[father-and-son]]></category>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 13:02:36 GMT</pubDate>
            <atom:updated>2025-07-25T13:06:29.477Z</atom:updated>
            <content:encoded><![CDATA[<p>In iOS development, two core players quietly run the show behind every app: AppDelegate and SceneDelegate. Think of them as a powerful father-son duo—one handling the heavy lifting in the background, the other orchestrating what users see on screen.</p><p>This article is here to make sure you <strong>truly understand</strong> how these two work together. We’ll <strong>deep dive</strong> into their responsibilities, differences, and real-life analogies to help you grasp their importance — not just technically, but conceptually.</p><p>By the end, you’ll see how the foundation (AppDelegate) and the stage (SceneDelegate) combine to create a smooth, responsive iOS experience. Let&#39;s begin.</p><p>In a little town called <strong>iOSville (iosworld or hometown)</strong>, there lived a wise and hardworking person named <strong>AppDelegate(father)</strong>.</p><p>He had been around since the beginning (around starting era), quietly managing everything behind the scenes —</p><p>📦 loading data, 🔒 setting up security, 📡 connecting to servers, and making sure the house (the app) ran smoothly.</p><p>But as the world of iOS changed, and things got more modern and dynamic,<br><strong> AppDelegate[person(father)]</strong>realized he couldn’t do everything alone anymore.</p><p>So, he turned to his young and energetic<strong> son, SceneDelegate.</strong></p><blockquote><em>“Son,” said </em><strong><em>AppDelegate(father)</em></strong><em>, “I’ve prepared everything.<br> The logic is strong. The services are ready. The app is alive.<br> Now it’s time for you… to show the world what we’ve built together.”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*VW0cIFxYxjFPuKhy5cjTsA.jpeg" /></figure><p><strong>SceneDelegate(son show full potencial)</strong>, full of energy, took over the <strong>front stage</strong>.<br> 🎨 He built the windows,<br> 🪟 set the root view controllers,<br> 💫 brought the UI to life,<br> and made sure users could interact with their beautiful app smoothly.</p><p>Every time the app went to sleep, paused, or woke up — <strong>SceneDelegate</strong> was there.<br> He handled transitions like a smooth performer, making his father proud.</p><p>Together, they were unstoppable.<br> The father managed the <strong>foundation</strong>.<br> The son managed the <strong>face</strong>.</p><p>And whenever someone opened the app, the son would smile and whisper to the user:</p><blockquote><strong><em>“Look what me and my father built… just for you.” 💙</em></strong></blockquote><p><strong>If you’re still confused about what is app life cycle and AppDelegate. Please read my blog </strong><a href="https://medium.com/@amanp183rajapati/appdelegate-the-brain-of-an-ios-application-0cea33fb6a47"><strong>The brain of ios application</strong></a><strong>.</strong></p><p>I hope by now you’re aware of AppDelegate, how app delegate interact to user event and app life cycle.</p><h3>Advantages of SceneDelegate:-</h3><ul><li>From iOS 13, the responsibilities of AppDelegate have been split between AppDelegate and SceneDelegate.</li><li>This is the result of new multi-window support feature that is introduced with iPad-OS.</li><li>The UIScene API allows us to create multiple instances of our app&#39;s UI as separate instances in the application switcher.</li></ul><h3>SceneDelegate’s responsibilities:-</h3><ul><li>There are several methods in the SceneDelegate.swift file by default:</li></ul><ol><li><strong>sceneDidDisconnect(_:)</strong> is called when a scene has been disconnected from the app (Note that it can reconnect later on.)</li><li><strong>sceneDidBecomeActive(_:)</strong> is called when the user starts interacting with a scene, such as selecting it from the app switcher</li><li><strong>sceneWillResignActive(_:)</strong> is called when the user stops interacting with a scene, for example by switching to another scene</li><li><strong>sceneWillEnterForeground(_:)</strong> is called when a scene enters the foreground, i.e. starts or resumes from a background state</li><li><strong>sceneDidEnterBackground(_:)</strong> is called when a scene enters the background, i.e. the app is minimised but still present in the background.</li></ol><p><strong>UIScene and UISceneDelegateClassName:-</strong></p><ul><li>Now app can run multiple instance of UI at the same time.</li><li>Appdelegate is no longer responsible for setting up the UI and handling UI related lifecycle events, such as going to the foreground or background.</li><li>Every instance of apps UI is represented by UIScene object.</li><li>How UIApplication notify app events through the app delegate, a scene does this through scene delegate</li><li>You typically work with UIWindowScene and UIWindowSceneDelegate</li></ul><h3>UIWindowScene</h3><ul><li>UIWindowScene is a subclass of UIScene and the most common type of scene you’ll interact with.</li><li>You shouldn’t instantiate UIWindowScene directly. UIKit will create it for you</li></ul><h3>UIWindowSceneDelegate</h3><ul><li>UIWindowSceneDelegate is a delegate protocol that extends from UISceneDelegate and contains the core methods which are used to respond UIWindowScene lifecycle events.</li></ul><h3>UISceneSession</h3><ul><li>The life cycle of scene sessions is handled by UIApplicationDelegate</li><li>Every scene(window) is managed by an UISceneSession</li><li>Which holds all the configuration data and state restoration data needed to create a scene object.</li></ul><h3>UISceneConfiguration</h3><ul><li>This object contains information that tells UIKit how to instantiate your scene. You configure a UISceneConfiguration in code or in your <strong>Info.plist</strong>.This looks as follows</li></ul><p>Zoom image will be displayed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*RcdUU4CqFn5NtZoT.png" /></figure><ul><li>Application Session Role suggest that you can have multiple configurations in your Info.plist .</li><li>Enable Multiple Windows key is false by default.</li><li>Setting Enable Multiple Windows property to YES will allow users to open multiple windows of your application on iPadOS (or even on macOS)</li></ul><p><strong><em>The most important information is kept inside the items in the Application Session Role array is</em></strong></p><ul><li>The name of this configuration, which needs to be unique</li><li>The class name of the scene UIWindowScene</li><li>The class name of the delegate for this scene, which is normally SceneDelegate</li><li>The name of the storyboard that contains the initial UI for this scene — If your using storyboard set this property else no need.</li></ul><p><strong>Changes to the AppDelegate and it’s responsibilities:-</strong></p><ul><li>This is still main entry point for iOS 13+ application. System calls appdelegate methods for application level life cycle events.</li><li>In apple’s default templet, you can find below three methods</li></ul><ol><li><strong>func application(_:didFinishLaunchingWithOptions:) -&gt; Bool</strong></li></ol><ul><li>This method is used to perform application setup.</li><li>In iOS 12 or earlier, you might have used this method to create and configure a UIWindow object and assigned a UIViewController instance to the window to make it appear.Now appdelegate is no longer responsible for this</li></ul><p><strong>2. </strong><strong>func application(_:configurationForConnecting:options:) -&gt; UISceneConfiguration</strong></p><ul><li>This method is called whenever your application is expected to supply a new scene, or window for iOS to display.</li><li>This method is not called when your app launches initially, it’s only called to obtain and create new scenes</li></ul><p><strong>3. </strong><strong>func application(_:didDiscardSceneSessions:)</strong></p><ul><li>This method is called whenever a user discards a scene.</li><li>You can use this function to dispose of resources that these scenes used, because they’re not needed anymore.</li></ul><blockquote><em>In addition to these default methods, </em><em>AppDelegate can still be used to open URLs, catch memory warnings, detect when your app will terminate, detect when a user has registered for remote notifications and more.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zc2kDMpZ7MZb0O5ncE6nhg.png" /><figcaption>The life cycle of scene</figcaption></figure><p>Next time you build an iOS app, remember:</p><ul><li>Let the <strong>father set the foundation</strong>.</li><li>Let the <strong>son bring it to life</strong>.</li><li>And together, they will deliver something truly great.</li></ul><p>This is more than code.<br> It’s a <strong>partnership between logic and light.</strong><br> Between <strong>AppDelegate and SceneDelegate</strong>.</p><p><strong>“Code hard, debug harder, and hustle smartest.” 💡💻</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45087f07312e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AppDelegate: The Brain of an iOS Application]]></title>
            <link>https://medium.com/@amanp183rajapati/appdelegate-the-brain-of-an-ios-application-0cea33fb6a47?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cea33fb6a47</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 11:06:47 GMT</pubDate>
            <atom:updated>2025-07-25T11:06:47.998Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why am I saying this? The brain of an iOS application is the AppDelegate. Is that correct? Don’t believe me; read it then use your own brain and decide.</strong></p><p>So let’s start:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUqemb8nIvKUhElThAAVfw.jpeg" /></figure><p><strong>AppDelegate is the application delegate object. It inherits from the UIResponder class and implements the UIApplicationDelegate protocol.</strong></p><ul><li>The main entry point into iOS apps is UIApplicationDelegate, a protocol that you need to implement in your app to receive notifications about user events, such as app launch, entering the background or foreground, termination, and opening a push notification.</li><li>UIResponder class makes AppDelegate have the ability to respond to user events and UIApplicationDelegate enables the AppDelegate to be an application delegate object to manage and respond to the life cycle of the application.</li></ul><p>🧩 <strong>All Responsibilities of AppDelegate:</strong></p><p><strong>1. 🟢 </strong><strong>application(_:didFinishLaunchingWithOptions:)</strong></p><pre>func application(<br>  _ application: UIApplication,<br>  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>) -&gt; Bool</pre><p><strong>Called when:</strong> The app has completed launching.</p><p><strong>Use cases:</strong></p><ul><li>Set up analytics, Firebase, SDKs</li><li>Customize UI appearance</li><li>Initialize root view controller</li><li>Register for push notifications</li></ul><p><strong>2. 🟡 </strong><strong>applicationWillResignActive(_:)</strong></p><pre>func applicationWillResignActive(_ application: UIApplication)</pre><p><strong>Called when:</strong> App is about to go from active to inactive (e.g., incoming call or SMS).</p><p><strong>Use cases:</strong></p><ul><li>Pause ongoing tasks</li><li>Disable timers</li><li>Mute audio or games</li><li>Throttle down OpenGL rendering</li></ul><p><strong>3. 🔴 </strong><strong>applicationDidEnterBackground(_:)</strong></p><pre>func applicationDidEnterBackground(_ application: UIApplication)</pre><p><strong>Called when:</strong> App enters background.</p><p><strong>Use cases:</strong></p><ul><li>Save user data</li><li>Release shared resources</li><li>Invalidate timers</li><li>Store app state for restoration</li><li>Start background tasks</li></ul><p><strong>4. 🟠 </strong><strong>applicationWillEnterForeground(_:)</strong></p><pre>func applicationWillEnterForeground(_ application: UIApplication)</pre><p><strong>Called when:</strong> App is transitioning from background to foreground.</p><p><strong>Use cases:</strong></p><ul><li>Undo changes made when entering background</li><li>Refresh UI or data</li></ul><p><strong>5. 🟢 </strong><strong>applicationDidBecomeActive(_:)</strong></p><pre>func applicationDidBecomeActive(_ application: UIApplication)</pre><p><strong>Called when:</strong> App becomes active again (after being in background or inactive).</p><p><strong>Use cases:</strong></p><ul><li>Restart paused tasks</li><li>Refresh UI</li><li>Reconnect to services (like WebSockets)</li></ul><p><strong>6. ❌ </strong><strong>applicationWillTerminate(_:)</strong></p><pre>func applicationWillTerminate(_ application: UIApplication)</pre><p><strong>Called when:</strong> App is about to terminate (not guaranteed to be called in background termination).</p><p><strong>Use cases:</strong></p><ul><li>Save important data</li><li>Perform cleanup</li><li>Release resources</li></ul><p><strong>7. 📩 </strong><strong>application(_:didReceiveRemoteNotification:fetchCompletionHandler:)</strong></p><pre>func application(<br>  _ application: UIApplication,<br>  didReceiveRemoteNotification userInfo: [AnyHashable : Any],<br>  fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void<br>)</pre><p><strong>Called when:</strong> A remote push notification is received with content available for background fetch.</p><p><strong>Use cases:</strong></p><ul><li>Update content silently in the background</li><li>Sync data from server</li></ul><p><strong>8. 🧭 </strong><strong>application(_:open:options:)</strong></p><pre>func application(<br>  _ app: UIApplication,<br>  open url: URL,<br>  options: [UIApplication.OpenURLOptionsKey : Any] = [:]<br>) -&gt; Bool</pre><p><strong>Called when:</strong> App is asked to open a URL (like deep links).</p><p><strong>Use cases:</strong></p><ul><li>Handle custom URL schemes</li><li>Open specific views from links (e.g., myapp://profile?id=123)</li></ul><p><strong>9. 🔔 </strong><strong>application(_:didRegisterForRemoteNotificationsWithDeviceToken:)</strong></p><pre>func application(<br>  _ application: UIApplication,<br>  didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data<br>)</pre><p><strong>Called when:</strong> Device successfully registers for push notifications.</p><p><strong>Use cases:</strong></p><ul><li>Send device token to server</li></ul><p><strong>10. 🚫 </strong><strong>application(_:didFailToRegisterForRemoteNotificationsWithError:)</strong></p><pre>func application(<br>  _ application: UIApplication,<br>  didFailToRegisterForRemoteNotificationsWithError error: Error<br>)</pre><p><strong>Called when:</strong> Registration for push notifications fails.</p><p><strong>Use cases:</strong></p><ul><li>Handle and log errors</li></ul><p><strong>11. ⏳ </strong><strong>application(_:performFetchWithCompletionHandler:)</strong></p><pre>func application(<br>  _ application: UIApplication,<br>  performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void<br>)</pre><p><strong>Called when:</strong> iOS wakes up your app in the background to fetch new data.</p><p><strong>Use cases:</strong></p><ul><li>Sync or fetch new data for widgets or news apps.</li></ul><p>Keep building, keep experimenting, and never stop learning.</p><blockquote><em>“Code hard, debug harder, and hustle smartest.” 💡💻</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cea33fb6a47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVC IN IOS : A Drive Through Model, View & Controller]]></title>
            <link>https://medium.com/@amanp183rajapati/mvc-in-ios-a-drive-through-model-view-controller-5701d41e0c1c?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/5701d41e0c1c</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 17:39:41 GMT</pubDate>
            <atom:updated>2025-07-20T17:39:41.991Z</atom:updated>
            <content:encoded><![CDATA[<h3>MVC IN IOS : 🚗A Drive Through Model, View &amp; Controller</h3><h3>The best way to understand code architecture is to get in the driver’s seat.</h3><p>· <a href="#89bd">What is MVC?</a><br>· <a href="#3d56">Why is MVC important?</a><br>· <a href="#a91f">For example: -</a><br>· <a href="#fd02">When we Use MVC ?</a><br>· <a href="#46af">When We Use Other Architecture ?</a></p><p>As a young Man i’m big fan of car’s . A car with the engine humming and skyscrapers rushing past — I realized: this car was the perfect metaphor for one of iOS’s most fundamental design patterns — <strong>MVC: Model, View, Controller. </strong>Let me take you for a ride.</p><p>let’s break it :</p><p>M :- Model imagine a blue-print, think about the blueprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*3uMamXN8BO6VAHJe23DuWg.jpeg" /><figcaption>The model of car(blueprint)</figcaption></figure><p>View :- how imagination looks like in real life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*28iUYPRG06-vHERrn1eFTA.jpeg" /><figcaption>The View of Car .</figcaption></figure><p>Controller :- who’s communicate between the model and application data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0aIGZNcoMMxoMmnyFmKFg.png" /><figcaption>The Whole car controller.</figcaption></figure><h3>What is MVC?</h3><ul><li>The <strong>Model</strong> is where your data resides. Things like persistence, model objects, parsers, managers, and networking code live there.</li><li>The <strong>View</strong> layer is the face of your app. Its classes are often reusable as they don’t contain any domain-specific logic. For example, a UILabel is a view that presents text on the screen, and it’s reusable and extensible.</li><li>The <strong>Controller</strong> mediates between the view and the model via the delegation pattern. In an ideal scenario, the controller entity won’t know the concrete view it’s dealing with. Instead, it will communicate with an abstraction via a protocol. A classic example is the way a UITableView communicates with its data source via the UITableViewDataSource protocol.</li></ul><p><strong>The Model :- </strong>is responsible for the <strong>data and business logic</strong> of the application. It contains the data that the application uses and provides methods to <strong>access</strong> and <strong>manipulate</strong> that <strong>data</strong>. The Model is also responsible for <strong>performing</strong> any <strong>calculations</strong> or other processing necessary to <strong>generate</strong> that <strong>data</strong>. In iOS development, the Model is often implemented as a set of data objects or a data layer.</p><p><strong>The View:-</strong> The View is responsible for <strong>presenting</strong> the <strong>user</strong> <strong>interface</strong> of the application. It defines <strong>how</strong> the <strong>data</strong> from the Model <strong>is presented</strong> to the user, such as by using labels, text fields, or images. The View is also responsible for <strong>handling user input</strong>, such as <strong>button</strong> <strong>taps</strong> or <strong>gestures</strong>.</p><p><strong>The Controller</strong> :- acts as the <strong>intermediary</strong> between the Model and the View. It receives user input from the View, <strong>interacts</strong> with the Model to perform any necessary operations, and <strong>updates</strong> the View to <strong>reflect</strong> the changes in the Model. In iOS development, the Controller is often implemented as a view controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*bCLeDAjPt5s9rKY1QclZVw.png" /><figcaption>The ER Design</figcaption></figure><h3>Why is MVC important?</h3><ul><li>By separating the application into these three distinct components, MVC promotes <strong>modularity</strong>, which allows for easier <strong>testing</strong> and <strong>maintenance</strong> of the application.</li><li>The <strong>separation of responsibilities</strong> also allows developers to work on specific parts of the application <strong>without affecting other parts</strong>. This makes it easier to add new features or <strong>modify</strong> existing ones <strong>without breaking</strong> other parts of the application.</li><li>MVC also promotes <strong>reusability</strong>. Because the components are separated and have specific <strong>responsibilities</strong>, they can be <strong>reused</strong> in other parts of the application or in other applications entirely. This can <strong>save development time</strong> and <strong>reduce the complexity</strong> of the application.</li></ul><h3><strong>For example: -</strong></h3><p>in <strong>UIKit, </strong>the communication between the layers happens through well-defined interfaces<strong>:</strong></p><ul><li>The Model is represented by the <strong>data objects</strong> and <strong>data sources </strong>and communicates with the Controller layer through a delegate pattern or by sending notifications.</li><li>The View is represented by the <strong>interface elements</strong> such as <strong>labels</strong> <strong>buttons</strong>, <strong>text fields </strong>and communicates with the Controller layer through target-action or delegation.</li><li>The Controller is represented by the <strong>view controllers and </strong>acts as an intermediary between the Model and View layers, and is responsible for processing user input and updating the View layer accordingly.</li></ul><p>In <strong>SwiftUI:</strong></p><ul><li>The Model is represented by the <strong>data objects and state.</strong></li><li>The View is represented by the <strong>view hierarchy and modifiers.</strong></li><li>The Controller is represented by the <strong>view model</strong>.</li></ul><p>Apple’s use of MVC in their UI libraries helps to ensure <strong>consistency</strong> and <strong>maintainability</strong> across apps. Because the architecture is well-defined and widely understood, developers can easily create new features and modify existing ones. It also allows for easier <strong>collaboration</strong> between developers, as each component has a well-defined responsibility.</p><h3>When we Use MVC ?</h3><ul><li>When the application has a <strong>clear separation of concerns</strong>: The MVC pattern is appropriate when the application has a clear separation of concerns between the data, the user interface, and the logic.</li><li>When the application has a <strong>well-defined user interface</strong>: The MVC pattern is appropriate when the application has a well-defined user interface, as the View component is responsible for presenting the user interface to the user.</li><li>When the application requires <strong>modularity and reusability</strong>: The MVC pattern is appropriate when the application requires modularity and reusability, as each component has a distinct responsibility and can be reused in other parts of the application or in other applications entirely.</li></ul><h3>When We Use Other Architecture ?</h3><ul><li>When the application has a <strong>complex user interface</strong>: In this case, a more specialized architecture, such as Model-View-ViewModel (MVVM) or Model-View-Presenter (MVP), may be more appropriate.</li><li>When the application has a <strong>large data model</strong>: In this case, a more specialized architecture, such as Clean Architecture or Domain-Driven Design, may be more appropriate.</li></ul><h3>Thank you for reading! 👨🏼‍💻</h3><h3>🌟 End of the Ride</h3><p>This was just the beginning — a short drive through one of iOS’s most classic architectures. But just like a car has more than just its frame, apps have more than just MVC.</p><p>In future stories, I’ll dive deeper — into MVVM, VIPER, Clean Architecture — and show how each one plays out in the real world.</p><p>Till then…</p><blockquote><strong><em>Enjoy the ride, trust the process, and never stop building.</em></strong></blockquote><blockquote><em>Life’s a journey — keep hustling. 🛠️🚀</em></blockquote><p><strong>— Aman Prajapati</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5701d41e0c1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[☕ “Your Usual, Aman?” — How iOS Apps Remember You with UserDefaults.]]></title>
            <link>https://medium.com/@amanp183rajapati/your-usual-aman-how-ios-apps-remember-you-with-userdefaults-794214fe0bf3?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/794214fe0bf3</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 10:51:21 GMT</pubDate>
            <atom:updated>2025-07-19T10:51:21.811Z</atom:updated>
            <content:encoded><![CDATA[<h3>☕ “Your Usual, Aman?” — How iOS Apps Remember You with UserDefaults.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*0eqirPEG4LWD_b3kpn6mlw.png" /></figure><p>You walk into your favorite coffee shop. The barista gives you a warm smile and says,</p><blockquote><em>“Your usual, Aman?”</em></blockquote><p>You pause for a second, surprised — but then smile back.<br> She remembered.</p><p>No ID, no loyalty card, no reminders — just a small, thoughtful detail that makes your day feel a little more <em>yours</em>.</p><p>Now, imagine if your favorite apps were just as smart.<br> If they remembered your name, your preferences, or the last screen you left off on — without asking again and again.</p><p>That’s the magic of <strong>UserDefaults</strong> in iOS.</p><h3>A brief introduction to UserDefaults</h3><p>The UserDefaults class provides a simple way to store small pieces of data persistently across app launches. Whether it&#39;s user preferences, flags, or other app settings, UserDefaults is efficient, easy to use, and deeply integrated into the iOS/macOS ecosystem.</p><p>By default, developers often use the singleton instance UserDefaults.standard to store data. This approach works well for simple use cases, but it has its limitations as your app scales.</p><h4>“No matter how perfect or terrible something seems, there’s always a flip side.”</h4><h3>The problems with UserDefaults.standard</h3><p>The UserDefaults.standard instance is a shared, global instance that allows you to store preferences across your app. While this approach may work for small apps, it introduces a number of problems when scaling your application. Let&#39;s take a look at some of these challenges:</p><h3>1. Limited flexibility</h3><p>The default UserDefaults.standard instance is not flexible when it comes to managing multiple data sources. For example, if your app requires different configurations for various modules or even different app extensions, using a single UserDefaults.standard instance can create confusion and lead to data pollution. All the data is stored in one shared space, leading to possible conflicts between different settings or modules.</p><h3>2. Concurrency issues</h3><p>UserDefaults.standard is not designed for concurrent access, and as apps become more complex with multi-threaded operations, concurrent access to UserDefaults.standard can lead to unpredictable behavior. Since it is a singleton instance, race conditions may occur if different parts of your app attempt to read and write to the defaults simultaneously.</p><h3>3. Testing and separation of concerns</h3><p>When relying on UserDefaults.standard throughout the app, testing becomes cumbersome. If you need to mock or isolate certain preferences for unit tests, it’s challenging to decouple this shared instance. Having a dedicated UserDefaults suite for each module, extension, or feature makes it easier to mock or reset settings during testing.</p><h3>4. App Extensions and iCloud</h3><p>When you have multiple app extensions (e.g., Today Widgets, WatchKit extensions), you may need to manage different sets of preferences. UserDefaults.standard doesn&#39;t handle this well because all extensions share the same settings. In such cases, using a separate UserDefaults Suite for each extension ensures that preferences are isolated correctly.</p><h3>Key advantages of using CustomUserDefaults (UserDefaults suite)</h3><h3>1. Separation of concerns</h3><p>By using a custom suite for each feature or extension, you can easily separate data into logical units. This is particularly useful when working with large applications or app extensions that have distinct preferences or settings. It improves maintainability and clarity of your codebase.</p><h3>2. Enhanced flexibility</h3><p>You can create as many custom suites as needed, giving you full flexibility over how data is stored and accessed. For instance, you can create a suite for each user (in a multi-user app), separate suites for different app features, or even separate suites for different environments (development, staging, production).</p><h3>3. Concurrency handling</h3><p>By using different suites, concurrent writes and reads to UserDefaults become more predictable. Each suite manages its own isolated store of data, reducing the chance of race conditions or data corruption. This is especially important for apps with complex multi-threaded or background tasks.</p><h3>4. Testing &amp; Isolation</h3><p>When you use custom UserDefaults suites, you can isolate the preferences for each module, making it much easier to write unit tests and mock preferences. You can reset or mock the preferences per suite without affecting other parts of your app.</p><h3>5. Better compatibility with App Extensions</h3><p>When working with multiple app extensions, such as a Today widget, a WatchKit app, or even a Share extension, using different suites for each extension ensures that the settings and preferences are kept separate. This avoids the potential issues of conflicting settings between extensions.</p><h3>6. Improved debugging</h3><p>Debugging issues related to settings or preferences becomes easier when you use separate suites. Instead of sifting through a shared UserDefaults.standard instance, you can target specific suites, streamlining the debugging process.</p><h3>When to use UserDefaults suite?</h3><p>In most scenarios, using the default UserDefaults.standard should suffice, especially for small apps or when you&#39;re working with global app settings. However, as your app becomes more complex, there are several cases where using UserDefaults Suite will be beneficial:</p><ul><li><strong>Multiple App extensions</strong>: When you have Today Widgets, WatchKit, or other app extensions that need separate preferences.</li><li><strong>Feature-specific settings</strong>: When you need isolated settings for individual features or modules (e.g., user preferences for notifications or dark mode).</li><li><strong>Large apps</strong>: When managing a large application with many configurations or user settings that need to be logically separated.</li><li><strong>Concurrency</strong>: When you’re dealing with multi-threaded operations and need to ensure safe access to UserDefaults.</li></ul><h3>Conclusion</h3><p>While UserDefaults.standard has served as a simple and effective solution for basic settings storage, it’s no longer the best fit for modern iOS applications that require flexibility, modularity, and scalability. Using UserDefaults Suite (or CustomUserDefaults) provides enhanced separation of concerns, concurrency handling, and a cleaner architecture overall.</p><p>As an iOS developer with over a decade of experience, I highly recommend adopting the UserDefaults Suite approach for any large or feature-rich app. This technique not only improves maintainability but also ensures a more predictable, testable, and scalable architecture, helping you build better, more robust applications.</p><p>“Fueled by coffee, driven by bugs.”</p><p>Thank You Keep Hustle…….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794214fe0bf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[✨ “Masala Chai and Swift Extensions — Adding Flavor Without Changing the Base”]]></title>
            <link>https://medium.com/@amanp183rajapati/masala-chai-and-swift-extensions-adding-flavor-without-changing-the-base-757bad357b2b?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/757bad357b2b</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Fri, 04 Jul 2025 14:48:43 GMT</pubDate>
            <atom:updated>2025-07-04T14:48:43.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>🫚✨ <strong>“Masala Chai and Swift Extensions — Adding Flavor Without Changing the Base”</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*EUcRi3wYBIU8XzaCmBfr5g.jpeg" /></figure><p>Every evening after college, I had one ritual I never missed: making myself a cup of chai. The recipe was always simple and consistent:</p><ul><li>Toss in a little <strong>adrak (ginger)</strong> when I needed warmth + <strong>Milk + Water + Sugar + Tea Leaves</strong> — the classic, reliable formula that powered many of my late-night coding sessions.</li></ul><p>But even that had limits.</p><h3>🍵 <strong>The Maitri Amruttulya Revelation:</strong></h3><p>One evening, in desperate need of a break from my room-made experiments, I wandered out and found a small stall near a local bakery: <strong>Maitri</strong> <strong>Amruttulya</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*xVpPI1uKna5fnBe89tkyxQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*gQ9j8KKntYrUct9Ud0kC_w.avif" /></figure><p>Their chai ? Next level</p><p>It wasn’t the usual masala chai — it had a <strong>signature twist</strong> I couldn’t quite decode. A bold blend of spices, paired with <strong>crispy handmade bakery biscuits</strong> that melted in your mouth.</p><p>That wasn’t just a cup of tea — it was an <em>experience</em>.<br>And what fascinated me most was this:</p><blockquote><strong>they didn’t change the original chai formula; they simply <em>enhanced</em> it.</strong></blockquote><p>🧠 <strong>And That’s When It Hit Me… This Is Swift Extensions!</strong></p><p>Just like my chai journey, when coding in Swift, we often start with a <strong>basic class</strong> — simple, functional, dependable. after complete the code and we want more functional class. so we didn’t change the original class; we simply enhanced it using the <strong>extension.</strong></p><h3><strong>Extension :</strong></h3><p>In Swift (and iOS development), an <strong>extension</strong> is a powerful feature that lets you <strong>add new functionality</strong> to existing <strong>classes, structs, enums, or protocols</strong> — even if you don’t own their source code (like String, Int, UIViewController, etc.).</p><pre>class Chai {<br>    func makeBasicChai() {<br>        print(&quot;Making chai with milk, water, sugar, and tea leaves ☕&quot;)<br>    }<br>}</pre><pre>//But sometimes, we want to enhance the behavior. Add a few spices.//<br>//Without rewriting the class or subclassing it, Swift gives us a powerful tool: extensions.<br><br>extension Chai {<br>    func addAdrak() {<br>        print(&quot;Added adrak (ginger) 🫚 for a mood swing boost!&quot;)<br>    }<br><br>    func addElaichi() {<br>        print(&quot;Added elaichi (cardamom) 🌿 for that fresh aroma!&quot;)<br>    }<br><br>    func amruttulyaSpecial() {<br>        print(&quot;✨ Added Amruttulya-style masala blend with bakery biscuit 🍪&quot;)<br>    }<br>}<br><br>let eveningChai = Chai()<br>eveningChai.makeBasicChai()<br>eveningChai.addElaichi()<br>eveningChai.amruttulyaSpecial()</pre><blockquote>Note :If you define an extension to add new functionality to an existing type, the new functionality will be available on all existing instances of that type, even if they were created before the extension was defined.</blockquote><h3><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/extensions/#Computed-Properties">Computed Properties</a>:</h3><p>Extensions can add computed instance properties and computed type properties to existing types.These properties are read-only computed properties, and so they’re expressed without the get keyword, for brevity.</p><pre>let aMarathon = 42.km + 195.m<br>print(&quot;A marathon is \(aMarathon) meters long&quot;)<br>// Prints &quot;A marathon is 42195.0 meters long&quot;</pre><blockquote>Note: Extensions can add new computed properties, but they can’t add stored properties, or add property observers to existing properties.</blockquote><h3><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/extensions/#Methods">Methods</a> :</h3><p>Extensions can add new instance methods and type methods to existing types. The following example adds a new instance method called repetitions to the Int type:</p><pre>extension Int {<br>    func repetitions(task: () -&gt; Void) {<br>        for _ in 0..&lt;self {<br>            task()<br>        }<br>    }<br>}<br></pre><p>The repetitions(task:) method takes a single argument of type () -&gt; Void, which indicates a function that has no parameters and doesn’t return a value.</p><p>After defining this extension, you can call the repetitions(task:) method on any integer to perform a task that many number of times:</p><pre>3.repetitions {<br>    print(&quot;Hello!&quot;)<br>}<br>// Hello!<br>// Hello!<br>// Hello!</pre><h3><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/extensions/#Mutating-Instance-Methods">Mutating Instance Methods</a> :</h3><p>Instance methods added with an extension can also modify (or <em>mutate</em>) the instance itself. Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation.</p><pre>extension Int {<br>    mutating func square() {<br>        self = self * self<br>    }<br>}<br>var someInt = 3<br><br>someInt.square()<br>// someInt is now 9<br>// The example adds a new mutating method called square to Swift’s Int type, which squares the original value:</pre><p>💡 <strong>Why This Matters in Swift (and Life)</strong></p><p>Swift <strong>extensions</strong> allow you to:</p><p>✅ Add new <strong>methods</strong>, <strong>computed properties</strong>, or <strong>conformances</strong><br> ✅ Keep your code <strong>modular</strong> and <strong>clean</strong><br> ✅ Reuse logic <strong>without subclassing</strong><br> ✅ Avoid touching the original implementation — <strong>just like not changing the base chai</strong></p><p>In short: <strong>you enhance, not replace</strong>.</p><blockquote><strong>Whether it’s your evening drink or your app architecture, sometimes the best way to evolve is to extend.</strong></blockquote><h3>💬 “Always keep the hustle buddy — just like chai, life gets richer with every thoughtful addition.”</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757bad357b2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The protocol’s Cafe : ‘just Boys being Boys’]]></title>
            <link>https://medium.com/@amanp183rajapati/the-protocols-cafe-just-boys-being-boys-0b19d3994d86?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b19d3994d86</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 20:29:09 GMT</pubDate>
            <atom:updated>2025-07-02T20:29:09.905Z</atom:updated>
            <content:encoded><![CDATA[<h3>The protocol’s Cafe : ‘just Boys being Boys’</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*UKDmOGjSOlJQXiKR7cpong.png" /></figure><p>One casual Sunday, my friends and I walked into our favorite spot in town — <strong>The Protocol Café</strong>. We didn’t need to ask how things worked. We’d been there many times before. In fact, every customer — new or old — followed the same simple steps.</p><p>As we entered, the waiter greeted us with a polite smile and handed us the menu. we scanned through it quickly and each picked our favorite: <strong>“kadak chai with no sugar”</strong> (because, you know, health freaks 😎) along with some warm <strong>bun maska</strong> (that’s pav with a good spread of butter — heavenly combo!). the food arrived soon. We sipped, we dipped, we devoured.</p><p>When it was time to pay, my friend Aayush reached for his wallet. But another one chimed in,<br> <strong>“Bhai, is baar tu kar de. Agli baar main kar dunga.”</strong><br> Just classic boys’ stuff — the unspoken <em>protocol</em> of friendship. we walked out with full stomachs and happy hearts.</p><h3>Now, here’s the twist:</h3><p>In swift programming, <strong>protocols</strong> work the same way.</p><p>When I write code — especially in Swift — and I want different parts of my app to behave a certain way, I define a <strong>protocol</strong>. It’s like saying: <strong>‘<em>Hey, if you’re going to act like a waiter (or a button, a screen, a feature), you must do A, B, and C.’</em></strong></p><h3><strong>Protocols :</strong></h3><p>A protocol defines a blueprint of methods, properties, and other requirements that can be adopted by classes, structs, or enums. It defines a contract that conforming types must adhere to.</p><pre>// Protocol sysntax<br>protocol Benchers{<br>    // protocol definition goes here<br>}<br><br>// Multiple protocols can be listed, and are separated by commas:<br>struct Benchers: FirstProtocol, AnotherProtocol {<br>    // Brnchers definition goes here<br>}<br><br>// If a class has a superclass, list the superclass name before any protocols it adopts, followed by a comma:<br>class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {<br>    // class definition goes here<br>}</pre><h3><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols#Property-Requirements">Property Requirements</a> :</h3><p>A protocol can require any conforming type to provide an instance property or type property with a particular name and type. The protocol doesn’t specify whether the property should be a stored property or a computed property — it only specifies the required property name and type. The protocol also specifies whether each property must be gettable or gettable <em>and</em> settable.</p><p>If a protocol requires a property to be gettable and settable, that property requirement can’t be fulfilled by a constant stored property or a read-only computed property. If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it’s valid for the property to be also settable if this is useful for your own code.</p><p>Property requirements are always declared as variable properties, prefixed with the var keyword. Gettable and settable properties are indicated by writing { get set } after their type declaration, and gettable properties are indicated by writing { get }.</p><pre>protocol SomeProtocol {<br>    var mustBeSettable: Int { get set }<br>    var doesNotNeedToBeSettable: Int { get }<br>}</pre><p>Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:</p><pre>protocol AnotherProtocol {<br>    static var someTypeProperty: Int { get set }<br>}</pre><h3><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols#Method-Requirements">Method Requirements</a>:</h3><p>Protocols can require specific instance methods and type methods to be implemented by conforming types. These methods are written as part of the protocol’s definition in exactly the same way as for normal instance and type methods, but without curly braces or a method body. Variadic parameters are allowed, subject to the same rules as for normal methods. Default values, however, can’t be specified for method parameters within a protocol’s definition.</p><p>As with type property requirements, you always prefix type method requirements with the static keyword when they’re defined in a protocol. This is true even though type method requirements are prefixed with the class or static keyword when implemented by a class:</p><pre>protocol SomeProtocol {<br>    static func someTypeMethod()<br>}<br>// following example defines a protocol with a single instance method requirement:<br>protocol RandomNumberGenerator {<br>    func random() -&gt; Double<br>}</pre><h3><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols#Mutating-Method-Requirements">Mutating Method Requirements</a>:</h3><p>It’s sometimes necessary for a method to modify (or <em>mutate</em>) the instance it belongs to. For instance methods on value types (that is, structures and enumerations) you place the mutating keyword before a method’s func keyword to indicate that the method is allowed to modify the instance it belongs to and any properties of that instance. This process is described in <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/methods#Modifying-Value-Types-from-Within-Instance-Methods"><strong>Modifying Value Types from Within Instance Methods</strong></a><strong>.</strong></p><pre>protocol Togglable {<br>    mutating func toggle()<br>}</pre><p>If you implement the Togglable protocol for a structure or enumeration, that structure or enumeration can conform to the protocol by providing an implementation of the toggle() method that’s also marked as mutating.</p><h3><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/protocols#Initializer-Requirements">Initializer Requirements</a>:</h3><p>You can implement a protocol initializer requirement on a conforming class as either a designated initializer or a convenience initializer. In both cases, you must mark the initializer implementation with the required modifier:</p><pre>protocol SomeProtocol {<br>    init(someParameter: Int)<br>}</pre><p>And just like that café, everything in my app knows how to behave — no confusion, no chaos. so yeah, next time someone asks me what a <strong>protocol</strong> is, I’ll just smile and say: ‘<strong><em>It’s how I get my chai and bun maska— every single time, without fail’ .</em></strong></p><p>i am explain the above briefly in any person asked me in technically what is the <strong>protocol in swift</strong>.</p><p>Because <strong>engineers like me? We live on rules… even if it starts with a kadak chai.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*A8XYRZpyEDJaSfKi9o30nQ.png" /><figcaption>with kadak chai ☕☕</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b19d3994d86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Two-Line Answers to Impactful Explanations — My Journey Through Technical Interviews]]></title>
            <link>https://medium.com/@amanp183rajapati/from-two-line-answers-to-impactful-explanations-my-journey-through-technical-interviews-4addbd7b61a4?source=rss-0e28be922806------2</link>
            <guid isPermaLink="false">https://medium.com/p/4addbd7b61a4</guid>
            <dc:creator><![CDATA[Amanprajapati]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 10:19:55 GMT</pubDate>
            <atom:updated>2025-06-30T10:19:55.065Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From Two-Line Answers to Impactful Explanations — My Journey Through Technical Interviews</strong></h3><p><em>By Aman Prajapati</em></p><p>Like many fresh graduates stepping into the world of technical interviews like me, I believed that knowing the definition of a concept was enough. After all, I had studied it, practiced it, and even built projects using it. So when the interviewer asked, <em>“What is a closure in Swift?”</em>, I confidently replied, <em>“Closures are self-contained blocks of functionality that can be passed around in code with simple example .”</em></p><p>A good definition, right?</p><p>Wrong.</p><p>The interviewer looked at me and smiled politely:<br> <strong>“That’s correct, but can you explain it in more detail, maybe with an example?”</strong></p><p>That’s when it hit me — giving a textbook definition wasn’t enough. The interviewer wasn’t just testing my memory. They were trying to understand if I really knew <strong>how</strong> the concept works and <strong>why</strong> it matters in real-world programming.</p><p><strong>Closure:</strong>- Closures are self-contained blocks of functionality that can be passed around and used in your code. They can capture and store references to any constants and variables from the context in which they are defined, making them incredibly flexible.</p><p>this is good but not stand out to other candidate’s so let’s go to the <strong>deep dive.</strong></p><pre>example : - <br>let simpleClosure = {<br> print(&quot;Hi buddy&quot;)<br>}<br>simpleClosure() <br>// Output: Hi buddy</pre><h3>Basic Syntax and Usage</h3><p>Closures in Swift have a concise syntax. Here’s a simple example of a closure that takes two integers and returns their sum:-</p><pre>let addClosure: (Int, Int) -&gt; Int = { (a, b) in<br> return a + b<br>}<br>let result = addClosure(5, 3) <br>// output = 8</pre><h3>Trailing Closures</h3><p>Trailing closures allow you to move the closure outside of the parentheses when it’s the last argument of a function, making your code cleaner .</p><ul><li><strong>Improves readability</strong>: Especially when the closure is long.</li><li><strong>Cleaner syntax</strong>: Reduces nested parentheses and improves focus on logic.</li><li><strong>Used extensively</strong> in UIKit, SwiftUI, Combine, and async code.</li></ul><pre>// Let’s take a look at an animation function in iOS:<br>UIView.animate(withDuration: 0.5, animations: {<br>    myView.alpha = 0<br>})<br><br>..........................................................<br>// Using a trailing closure, the same code becomes cleaner:<br>UIView.animate(withDuration: 0.5) {<br>    myView.alpha = 0<br>}</pre><h3>Capturing Values</h3><p>Closures can capture and store references to variables and constants from their surrounding context. Here’s an example :-</p><h3>Real-Life Analogy</h3><p>Imagine you’re packing a lunchbox for school. You take a sandwich from the kitchen — and once you leave, the kitchen is gone, but you still have your sandwich. Similarly, a closure takes variables from its surrounding scope and keeps them even when that scope is gone.</p><pre>func makeCounter() -&gt; () -&gt; Int {<br>    var count = 0<br>    return {<br>        count += 1<br>        return count<br>    }<br>}<br><br>let counter = makeCounter()<br>print(counter()) // 1<br>print(counter()) // 2<br>print(counter()) // 3</pre><p>Escaping Closures</p><p>Escaping closures are closures that are stored and called later. They’re marked with the `<a href="http://twitter.com/escaping"><strong>@escaping</strong></a>` attribute. Here’s an example.</p><h3>Real-Life Analogy</h3><p>Imagine you order food online. You give instructions to the delivery agent. You don’t stand there waiting — you go back to work. Later, the delivery agent comes back to you with your order.</p><ul><li><strong>You</strong> = the function</li><li><strong>Instructions</strong> = the closure</li><li><strong>Food delivery later</strong> = closure executes <em>after</em> the function ends</li></ul><pre>var completionHandlers: [() -&gt; Void] = []<br><br>func addCompletionHandler(_ handler: @escaping () -&gt; Void) {<br>    completionHandlers.append(handler)<br>}<br>addCompletionHandler {<br>    print(&quot;This closure was called later!&quot;)<br>}<br><br>// Later in the code...<br>completionHandlers.forEach { $0() }<br><br>// output in sql<br>This closure was called later!</pre><h3>Autoclosures</h3><p>Autoclosures are a special kind of closure that automatically wraps an expression into a closure. They’re used to delay the evaluation of an expression. Here’s an example</p><p><strong>Real-Life Analogy</strong></p><p>Think of @autoclosure like a <strong>vending machine</strong>:</p><ul><li>Normally, when you put money in, the drink comes out immediately.</li><li>But with an autoclosure, you put in the money, but the machine waits until you press the button — <strong>delayed execution</strong>.</li></ul><pre>var customersInLine = [&quot;Chris&quot;, &quot;Alex&quot;, &quot;Ewa&quot;, &quot;Barry&quot;, &quot;Daniella&quot;]<br><br>print(customersInLine.count) // Output: 5<br><br>let customerProvider = { customersInLine.remove(at: 0) }<br><br>print(customersInLine.count) // Output: 5</pre><h3>Advanced Closure Techniques</h3><p><strong>After getting comfortable with closures, trailing closures, and escaping closures, I found myself wanting to go deeper — especially when I started building real apps and preparing for interviews. Here’s what I discovered about advanced closures in Swift that helped me think and code like a pro.</strong></p><p>Swift closures support advanced techniques such as capturing lists and shorthand argument names. Here’s an example using shorthand argument names.</p><p><strong>Closures Returning Closures :</strong></p><pre>func makeMultiplier(_ factor: Int) -&gt; (Int) -&gt; Int {<br>    return { number in<br>        return number * factor<br>    }<br>}<br><br>let double = makeMultiplier(2)<br>print(double(5)) // 10 <br>// here double is the closure that capture the factor= 2. this is simpleand clean</pre><p><strong>Closure Chaining :</strong></p><pre>let increment: (Int) -&gt; Int = { $0 + 1 }<br>let square: (Int) -&gt; Int = { $0 * $0 }<br><br>let chain = { square(increment($0)) }<br>print(chain(3)) // (3 + 1)^2 = 16</pre><p><strong>Shorthand Argument Names :</strong></p><pre>let numbers = [1, 2, 3, 4]<br>let squares = numbers.map { $0 * $0 }<br>print(squares) <br>//output  [1, 4, 9, 16]</pre><h3>Closures as Parameters and Inline Logic</h3><p>Functions that accept closures allow dynamic behavior injection.</p><pre>func perform(operation: () -&gt; Void) {<br>    print(&quot;Before operation&quot;)<br>    operation()<br>    print(&quot;After operation&quot;)<br>}<br><br>perform {<br>    print(&quot;Doing something important&quot;)<br>}</pre><h3>Memory Management and Retain Cycles</h3><p>Closures can <strong>strongly capture </strong><strong>self</strong>, which may lead to <strong>retain cycles</strong>. This is common in escaping closures used in async callbacks.</p><pre>class MyViewController {<br>    var name = &quot;Aman&quot;<br>    <br>    func fetchData() {<br>        someAsyncCall { [weak self] in<br>            print(&quot;Data fetched for \(self?.name ?? &quot;unknown&quot;)&quot;)<br>        }<br>    }<br>}<br>// Use [weak self] or [unowned self] to avoid memory leaks.</pre><p><strong>Closures with Multiple Parameters and Return Types :</strong></p><pre>let operation: (Int, Int) -&gt; String = { a, b in<br>    return &quot;Result is \(a + b)&quot;<br>}<br>print(operation(2, 3)) <br>// Result is 5 output</pre><h4>Error Handling with Closures:</h4><p><strong>This function accepts a throwing closure and passes through the error. The use of </strong><strong>rethrows means it only throws if the closure throws — making your API safer.</strong></p><pre>func execute(_ work: () throws -&gt; Void) rethrows {<br>    try work()<br>}<br>try execute {<br>    throw NSError(domain: &quot;Test&quot;, code: 123, userInfo: nil)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*rJU5aVk9SZWJm_LD5YCRHg.jpeg" /></figure><h3>Next Time? I’m Ready.</h3><p>So now, when the interviewer asks:</p><blockquote><em>“Can you explain that a bit more?”</em></blockquote><p>I smile and think to myself:<br> <strong>“Yes. I’ve been waiting for that.”</strong></p><p>Because this time, I’m not just answering — <br> I’m communicating like a real engineer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4addbd7b61a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>