<?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 Gagan Joshi on Medium]]></title>
        <description><![CDATA[Stories by Gagan Joshi on Medium]]></description>
        <link>https://medium.com/@gaganjoshi.dev?source=rss-d2fc50549c17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LIbQ6e0d4GBYTg0bMP3pRw.jpeg</url>
            <title>Stories by Gagan Joshi on Medium</title>
            <link>https://medium.com/@gaganjoshi.dev?source=rss-d2fc50549c17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:10:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gaganjoshi.dev/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[When AI Becomes the Historian, Who Decides What We Remember?]]></title>
            <link>https://medium.com/@gaganjoshi.dev/when-ai-becomes-the-historian-who-decides-what-we-remember-52b0fb5c3c94?source=rss-d2fc50549c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b0fb5c3c94</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Gagan Joshi]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 15:37:55 GMT</pubDate>
            <atom:updated>2026-11-05T15:37:55.149Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The risk isn’t that AI lies to us. It’s that one day we stop checking.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r15VJa3y6UTZ5qSuDZis_A.png" /></figure><p>Think of something you have known since childhood. A story your grandparents told you. A place, an event, a name. You have never had a reason to doubt it.</p><p>Now fast-forward twenty years. You ask an AI about it, and it confidently tells you a different story. You rephrase the question, ask again, look for another source. Every answer points the same way. Slowly, you begin to doubt your own memory.</p><p>The records won’t have disappeared. Archives, newspapers and libraries will still exist. We’ll simply have stopped reading them.</p><h3>A small version of this has already happened</h3><p>I remember when Google started personalising search results by location. I had a feeling the internet would never be quite the same again.</p><p>Picture someone in Punjab who regularly searches for new music. Their results fill up with Punjabi artists, new releases and local events. Then they move to South India, and over a few months their results shift to regional music, local news and nearby events. There is nothing wrong with that, and personalisation is genuinely useful. But two people searching for the same thing no longer see the same internet.</p><p>What is coming is different, and the difference matters.</p><p><strong>Search personalisation changes what you see. AI changes what you are told.</strong> The first gives you a different list of links, and you can still compare them. The second gives you one confident answer, with nothing next to it to compare against.</p><h3>It’s already happening, in small ways</h3><p>In February 2024, Google paused Gemini’s ability to generate images of people after it produced historically inaccurate depictions, including images in response to prompts like “the Founding Fathers” and “1943 German soldier.” Nobody set out to rewrite history. A well-intentioned system simply got it wrong, at scale, with complete confidence.</p><p>Deliberate design is a different story. In early 2025, when DeepSeek, a Chinese AI model, topped app store charts, researchers and journalists found that it deflected questions about the 1989 Tiananmen Square protests and other topics sensitive in China. One analysis found it avoided around 85% of prompts on such subjects. Researchers at Northeastern University later showed that the model could be pushed to reveal information it otherwise withheld, which they described as a gap between what the AI tells you and what it actually knows.</p><p>If accidents can distort the record, and design can quietly withhold it, it’s fair to ask what happens when this becomes the main way people learn about the past.</p><h3>History was never neutral, but this is different</h3><p>Textbooks, governments and publishers have always shaped how the past is told. That isn’t new. What is new is the combination: AI speaks to each of us privately, in a warm and conversational voice, tailored to us, and rarely shows its sources. Propaganda used to be a poster on a wall. This is a trusted voice in your pocket.</p><p>Today’s models are built by companies with commercial interests, trained on data that carries its own cultural and political biases, and operated under very different national rules. Now imagine every country eventually running its own dominant AI ecosystem, each emphasising its achievements and softening its mistakes. The real danger is that most people wouldn’t notice. They’d just call it knowledge.</p><h3>Who controls the source of truth?</h3><p>These are the questions I think we should be asking:</p><ul><li>Who decides which historical sources count as reliable?</li><li>Who makes sure uncomfortable facts aren’t quietly left out?</li><li>Who audits what goes into training these models?</li><li>If two AI systems give different accounts of the same event, how do we find out what actually happened?</li></ul><p>We spent centuries recording history in books, photographs, newspapers, monuments and personal accounts. What happens when people stop going back to them, and “just ask the AI” becomes the way we learn about the past?</p><h3>Sovereignty without propaganda: what India needs</h3><p>Let me raise an obvious objection to myself. If I’m worried about every country having its own AI version of history, why argue for an Indian AI?</p><p>Because the danger isn’t national AI. It’s <strong>unaccountable</strong> AI. A sovereign model with open datasets, public audits and multiple documented perspectives is a safeguard. One without them is just a different propaganda machine.</p><p>For India, building a model is not enough. What goes into it matters just as much. Here is what I think we need:</p><ol><li><strong>Independent historical datasets.</strong> Digitise and preserve records with verifiable sources, not just popular summaries.</li><li><strong>Regional language representation.</strong> Our literature, oral histories and local knowledge are thinly represented in global AI systems. If a story isn’t in the data, the AI cannot tell it.</li><li><strong>Transparent training.</strong> We should be able to trace and audit where an AI’s answers come from.</li><li><strong>Independent verification.</strong> Libraries, universities and archives should be able to validate historical claims without depending on any single technology provider.</li><li><strong>Plural answers.</strong> On contested history, AI should present the documented perspectives instead of choosing one and calling it the truth.</li></ol><p>None of this is about rejecting global AI. It’s about keeping the ability to question it, verify it and build alternatives.</p><h3>The bigger question</h3><p>We talk about AI in terms of intelligence, computing power, jobs and economic growth. We talk far less about the possibility that AI becomes the main way a generation understands its past.</p><p>Today we use Google to find information. Tomorrow we may simply ask. And if the answer is incomplete, biased or selectively framed, how would anyone know what is missing?</p><p>The biggest AI race may not be about who builds the smartest model. It may be about who gets to say what happened.</p><p><strong>When our children ask AI about our past, will it tell them what happened, or what someone wants them to believe happened?</strong></p><p><em>If different countries’ AI systems tell different versions of the same events, how should we decide which one to trust? I’d like to hear your answer in the comments.</em></p><ul><li><a href="https://techcrunch.com/tag/google-gemini-image-generation-historical-people-inaccuracies/">Google pauses Gemini’s image generation of people (TechCrunch)</a></li><li><a href="https://fox7austin.com/news/google-suspends-gemini-ai-inaccurate-images">Google suspends Gemini after inaccurate images (Fox 7 Austin)</a></li><li><a href="https://techcrunch.com/2025/01/29/deepseeks-ai-avoids-answering-85-of-prompts-on-sensitive-topics-related-to-china">DeepSeek’s AI avoids answering 85% of prompts on “sensitive topics” related to China (TechCrunch)</a></li><li><a href="https://www.nbcnews.com/tech/innovation/deepseek-censorship-china-rcna189594">On DeepSeek, you can watch AI navigate censorship in real time (NBC News)</a></li><li><a href="https://www.khoury.northeastern.edu/khoury-researchers-find-political-censorship-in-chinese-ai-model-and-explain-how-to-get-around-it/">Khoury researchers find political censorship in Chinese AI model (Northeastern University)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b0fb5c3c94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can You Write a Custom View Modifier?]]></title>
            <link>https://medium.com/@gaganjoshi.dev/can-you-write-a-custom-view-modifier-1054faf321d2?source=rss-d2fc50549c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/1054faf321d2</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui-viewmodifier]]></category>
            <category><![CDATA[viewmodifier]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Gagan Joshi]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 16:53:08 GMT</pubDate>
            <atom:updated>2026-07-25T16:53:08.625Z</atom:updated>
            <content:encoded><![CDATA[<p>A custom view modifier is how you turn a repeated SwiftUI style into a named, reusable API — and that’s exactly what this interview question is probing.</p><p>This one shows up often enough in SwiftUI interviews that it’s worth having ready. It’s not a trick question. When it does come up, interviewers usually want a quick signal: can you move past .padding().background(.red) pasted on every screen, and actually name that look?</p><p>Most candidates know modifiers exist. Fewer can build one cleanly under pressure.</p><h3>What a strong answer looks like</h3><p>You’re expected to:</p><ol><li>Conform to ViewModifier</li><li>Style content inside body</li><li>Expose a View extension so usage reads like a built-in modifier</li><li>Explain <em>why</em> — reuse, clarity, one place to change</li></ol><h3>The code</h3><pre>import SwiftUI<br><br>struct PaddedRedBackground: ViewModifier {<br>    func body(content: Content) -&gt; some View {<br>        content<br>            .padding()<br>            .background(.red)<br>    }<br>}<br><br>extension View {<br>    func paddedRedBackground() -&gt; some View {<br>        modifier(PaddedRedBackground())<br>    }<br>}<br><br>struct Parent: View {<br>    var body: some View {<br>        Text(&quot;Hello World&quot;)<br>            .paddedRedBackground()<br>    }<br>}</pre><p>The extension lets you call .paddedRedBackground() instead of typing .modifier(PaddedRedBackground()) every time — so it feels like a normal SwiftUI modifier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1054faf321d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own map, filter, and reduce in Swift]]></title>
            <link>https://medium.com/@gaganjoshi.dev/build-your-own-map-filter-and-reduce-in-swift-a2f7810052b1?source=rss-d2fc50549c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2f7810052b1</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Gagan Joshi]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 10:16:56 GMT</pubDate>
            <atom:updated>2026-07-25T10:16:56.543Z</atom:updated>
            <content:encoded><![CDATA[<p>If you can rewrite map, filter, and reduce, you don’t just use higher-order functions — you understand them.</p><p>This is also a common interview question:</p><p>“Can you implement custom higher-order functions on Array?”</p><p>Before diving into code, remember these one-liners:</p><ul><li>myFilter — Returns only the elements that pass a condition.</li><li>myMap — Transforms every element into a new value (and possibly a new type).</li><li>myReduce — Combines all elements into a single result using an initial value.</li></ul><h3>The code</h3><pre>extension Array {<br>    <br>    func myFilter(_ closure: (Element) -&gt; Bool) -&gt; [Element] {<br>        var result = [Element]()<br>        for value in self {<br>            if closure(value) {<br>                result.append(value)<br>            }<br>        }<br>        return result<br>    }<br>    <br>    func myMap&lt;T&gt;(_ closure: (Element) -&gt; T) -&gt; [T] {<br>        var result = [T]()<br>        for value in self {<br>            result.append(closure(value))<br>        }<br>        return result<br>    }<br>    <br>    func myReduce&lt;T&gt;(<br>        _ initialResult: T,<br>        _ nextPartialResult: (T, Element) -&gt; T<br>    ) -&gt; T {<br>        var result = initialResult<br>        for element in self {<br>            result = nextPartialResult(result, element)<br>        }<br>        return result<br>    }<br>}<br><br>var array = [1, 2, 3, 4, 5]<br><br>var filterArray = array.myFilter {<br>    $0 % 2 == 0<br>}<br><br>var mapArray = array.myMap {<br>    String($0 * $0)<br>}<br><br>print(filterArray)   // [2, 4]<br>print(mapArray)      // [&quot;1&quot;, &quot;4&quot;, &quot;9&quot;, &quot;16&quot;, &quot;25&quot;]<br><br>var reduceArray = array.myReduce(0, +)<br>print(reduceArray)   // 15</pre><p>Three functions. Three jobs. Same idea: pass behavior as a closure.</p><p><strong>What a higher-order function really is</strong></p><p>“A higher-order function is a function that takes another function as an argument, or returns a function as its result (or both).”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2f7810052b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do You Test a Private Function in Swift? (A Common Interview Question)]]></title>
            <link>https://medium.com/@gaganjoshi.dev/how-do-you-test-a-private-function-in-swift-a-common-interview-question-44dfd9f2584a?source=rss-d2fc50549c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/44dfd9f2584a</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[hooks]]></category>
            <dc:creator><![CDATA[Gagan Joshi]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 05:13:19 GMT</pubDate>
            <atom:updated>2026-07-24T05:13:19.927Z</atom:updated>
            <content:encoded><![CDATA[<p>This one shows up a lot in iOS interviews:</p><p>“How do you unit test a private function?”</p><p>A lot of candidates freeze. Some say, “You can’t.” Some say, “Just make it internal.” Both answers are incomplete.</p><p>You <em>can</em> test private behavior in Swift — without turning your class into a public junk drawer. One clean approach is test hooks.</p><p><strong>The interview trap</strong></p><pre>class Sample {<br>    private func myPrivate() {<br>        print(&quot;baseFunction called&quot;)<br>    }<br>}</pre><p>Now the interviewer asks: how do you test myPrivate() from XCTest?</p><p><strong>Bad instincts:</strong></p><ul><li>Make it public — too much API leakage</li><li>Make everything internal “for testing” — works, but weakens encapsulation</li><li>Skip testing it and only test giant public flows — slow, brittle, unclear failures</li></ul><p><strong>Good instinct:</strong></p><ul><li>Keep it private in production. Expose a DEBUG-only test entry point.<br>The simple version: DEBUG extension</li></ul><p>In Swift, private is visible to extensions in the same file. So this works:</p><pre>class Sample {<br>    private func myPrivate() {<br>        print(&quot;baseFunction called&quot;)<br>    }<br>}<br><br>#if DEBUG<br>extension Sample {<br>    func test_myPrivate() {<br>        myPrivate()<br>    }<br>}<br>#endif</pre><p>That’s valid. For one helper, it’s enough.</p><p>But interviews often push further: <em>How do you keep test helpers from looking like real feature APIs?</em></p><p>That’s where hooks come in.</p><pre>class Sample {<br>    private func myPrivate() {<br>        print(&quot;baseFunction called&quot;)<br>    }<br>}<br><br>#if DEBUG<br>extension Sample {<br>    struct Hooks {<br>        fileprivate let target: Sample<br>        <br>        func myPrivate() {<br>            target.myPrivate()<br>        }<br>    }<br>    <br>    var hooks: Hooks {<br>        Hooks(target: self)<br>    }<br>}<br>#endif</pre><p>Now your test reads like this:</p><pre>import XCTest<br>@testable import YourAppModule<br><br>final class SampleTests: XCTestCase {<br>    func test_myPrivate() {<br>        let sut = Sample()<br>        sut.hooks.myPrivate()<br>    }<br>}</pre><p>That sut.hooks... call is doing real work in an interview answer. It shows you care about:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44dfd9f2584a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Property Wrapper Isn’t Magic — It’s a Tiny Gatekeeper With Two Doors]]></title>
            <link>https://medium.com/@gaganjoshi.dev/your-property-wrapper-isnt-magic-it-s-a-tiny-gatekeeper-with-two-doors-03a55dc61f7f?source=rss-d2fc50549c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/03a55dc61f7f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[property-wrapper]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Gagan Joshi]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 04:23:50 GMT</pubDate>
            <atom:updated>2026-07-24T04:23:50.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Most Swift posts introduce property wrappers like this: “They’re syntactic sugar for getters and setters.” True. Also boring.</p><p>What actually matters is this: a property wrapper is a policy object. You attach a rule to a property, and Swift quietly routes every read and write through that rule. An @NonNegative wrapper is a clean example of that idea, and it also shows the part people usually skip — $ is not decoration.</p><pre>@propertyWrapper<br>struct NonNegative {<br>    <br>    var value: Int<br>    <br>    var wrappedValue: Int {<br>        set { value = newValue }<br>        get {<br>            if value &lt; 0 {<br>                return 0<br>            }<br>            return value<br>        }<br>    }<br><br>    init(wrappedValue: Int) {<br>        self.value = wrappedValue<br>    }<br>    <br>    var projectedValue: Int {<br>        return value + 10<br>    }<br>}<br><br>struct User {<br>    @NonNegative var rollno = -34<br>}<br><br>print(User().rollno)   // 0<br>print(User().$rollno)  // -24</pre><p>Two prints. Two different answers. Same underlying storage. That is the whole lesson.</p><p>When you write @NonNegative var rollno = -34, Swift stores a NonNegative wrapper and exposes rollno as wrappedValue. So User().rollno does not return -34. It returns whatever the getter decides. In this case, the value is less than zero, so the getter returns 0.</p><p>Notice the setter still stores the raw input:</p><p>set { value = newValue }</p><p>That means this wrapper is not saying “never store a negative.” It is saying “store anything, but expose a non-negative value when someone reads the property.” That is closer to a presentation rule than a strict storage validation rule. Some wrappers clamp in set so storage never holds an invalid value. This one clamps in get, so storage can still hold the original number while callers see a cleaned result.</p><p>Then comes the second door:</p><p>print(User().$rollno)</p><p>$rollno is Swift’s projection syntax for projectedValue. In this wrapper, projected value is simply value + 10, so with stored -34 you get -24.</p><p>Why does that exist? Because sometimes one property needs two views. wrappedValue is the safe public value the app should use. projectedValue is a side channel for something related — debugging, bindings, metadata, or another derived value. SwiftUI’s @State and $binding pattern is the famous version of this. This example is the teaching version: one property, two intentional outputs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03a55dc61f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boyer–Moore Majority Vote Algorithm in Swift]]></title>
            <link>https://medium.com/@gaganjoshi.dev/boyer-moore-majority-vote-algorithm-in-swift-db7215251f03?source=rss-d2fc50549c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/db7215251f03</guid>
            <dc:creator><![CDATA[Gagan Joshi]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 05:45:47 GMT</pubDate>
            <atom:updated>2025-08-12T05:45:47.567Z</atom:updated>
            <content:encoded><![CDATA[<h3>Today I’m sharing one of my favorite algorithms — the <strong>Boyer–Moore Majority Vote</strong> — written in Swift with detailed comments.</h3><h3>Problem</h3><p>Given an array, find the element that appears more than n/2 times (the <strong>majority element</strong>).<br>This algorithm works in <strong>O(n) time</strong> and <strong>O(1) space</strong>, making it super efficient.</p><pre>/// Finds the majority element in the given array using Boyer–Moore Majority Vote Algorithm.<br>/// Assumes that a majority element always exists.<br>///<br>/// - Parameter nums: The array of integers.<br>/// - Returns: The majority element.<br>func majorityElement(_ nums: [Int]) -&gt; Int {<br>    <br>    // Step 1: Start with the first element as a candidate<br>    var candidate = nums[0]<br>    <br>    // Count represents how many times the current candidate is favored<br>    var count = 0<br>    <br>    // Step 2: Traverse the array<br>    for num in nums {<br>        <br>        // If count becomes zero, choose the current number as the new candidate<br>        if count == 0 {<br>            print(&quot;Count is zero → setting candidate = \(num)&quot;)<br>            candidate = num<br>        }<br>        <br>        // If current number matches candidate, increment count<br>        if num == candidate {<br>            count += 1<br>            print(&quot;num (\(num)) == candidate (\(candidate)) → count increased to \(count)&quot;)<br>        }<br>        // Otherwise, decrement count<br>        else {<br>            count -= 1<br>            print(&quot;num (\(num)) != candidate (\(candidate)) → count decreased to \(count)&quot;)<br>        }<br>    }<br>    <br>    // Step 3: Return the candidate (guaranteed majority in problem statement)<br>    return candidate<br>}<br><br>// Example usage:<br>let nums = [1, 3, 3, 4, 3, 3, 3, 5, 6, 7, 3, 3, 3]<br>print(&quot;Majority Element: \(majorityElement(nums))&quot;)</pre><h3>How it works</h3><ol><li><strong>Candidate Selection: </strong>If count drops to zero, we pick the current element as a new candidate.</li><li><strong>Voting: </strong>If the current element matches the candidate, we increment the count.If it’s different, we decrement the count.</li><li><strong>Why it works:</strong><br>Every different element cancels out one occurrence of the candidate. Since the majority element occurs more than half the time, it will always remain at the end.</li></ol><p><strong>Time Complexity:</strong> O(n)<br><strong>Space Complexity:</strong> O(1)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db7215251f03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[For-in vs While Loop]]></title>
            <link>https://medium.com/@gaganjoshi.dev/for-in-vs-while-loop-e801ccbde924?source=rss-d2fc50549c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/e801ccbde924</guid>
            <dc:creator><![CDATA[Gagan Joshi]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 06:32:14 GMT</pubDate>
            <atom:updated>2025-07-01T06:54:39.553Z</atom:updated>
            <content:encoded><![CDATA[<p>For-in vs While Loop</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3sXugUqpvBmDKhJ6AZCSdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5NMJO2dHyCVHaR_Bwy7wQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTcRGEkxp2QmUCXRnEwo1Q.png" /></figure><pre><br>import Dispatch<br><br>func measureTime(block: () -&gt; Void) -&gt; Double {<br>    let startTime = DispatchTime.now()<br>    block()<br>    let endTime = DispatchTime.now()<br>    let nanoseconds = endTime.uptimeNanoseconds - startTime.uptimeNanoseconds<br>    let timeInterval = Double(nanoseconds) / 1_000_000_000<br>    return timeInterval<br>}<br><br><br>func test_ForLoop(array : [Int]) {<br>    var k = 0<br>    for i in 0..&lt;array.count {<br>        k += 1<br>    }<br>}<br><br>func test_WhileLoop(array : [Int]) {<br>    var k = 0<br>    var i = 0<br>    while i &lt; array.count {<br>        k += 1<br>        i += 1<br>    }<br>}<br><br>var largeArray = Array&lt;Int&gt;(repeating: 1, count: 1_000_000)<br><br>let elapsedTime_ForLoop = measureTime {<br>     test_ForLoop(array: largeArray)<br>}<br><br>let elapsedTime_WhileLoop = measureTime {<br>    test_WhileLoop(array: largeArray)<br>}<br><br></pre><pre>/*<br>The &#39;for-in&#39; loop maintains constant starting and ending points.<br>I added elements to the array in the middle of the loop. <br>Despite the dynamic change in the array&#39;s count, <br>the loop still executed only four times.<br> */<br><br>var array = [1,2,3,4]<br>var numberOfTimesLoopRuns = 0<br><br>for i in 0..&lt;array.count {<br>    if i &lt; 3 {<br>        array.append(5 + i)<br>    }<br>    numberOfTimesLoopRuns += 1<br>}<br><br>print(numberOfTimesLoopRuns)<br>print(array)<br><br><br>print(&quot;---------------------------------------------------&quot;)<br><br>/*<br>In this second example, <br>I incremented the &#39;i&#39; variable inside the loop. <br>However, it is evident that the loop ignores the updated &#39;i&#39; value <br>and continues with the originally incremented value. <br>Consequently, the loop still executed only four times.<br> */<br><br><br>array = [1,2,3,4]<br>numberOfTimesLoopRuns = 0<br><br>for var i in 0..&lt;array.count {<br>    print(&quot;before increment value of i = \(i)&quot;)<br>    i += 2<br>    print(&quot;after increment value of i = \(i)&quot;)<br><br>    numberOfTimesLoopRuns += 1<br>}<br><br>print(numberOfTimesLoopRuns)<br>print(array)</pre><pre>/*<br> The while loop, on the other hand, <br>adjusts its starting and ending points based on changes within the loop.<br> In the following example, <br>I added elements to the array in the middle of the loop. <br>Due to the dynamic change in the array&#39;s count, <br>the loop executed seven times, matching the new array count<br> */<br><br>var array = [1,2,3,4]<br>var numberOfTimesLoopRuns = 0<br><br>var i = 0<br>while i &lt; array.count {<br>   <br>    if i &lt; 3 {<br>        array.append(5 + i)<br>    }<br>    numberOfTimesLoopRuns += 1<br>    i += 1<br>}<br><br><br>print(numberOfTimesLoopRuns)<br>print(array)<br><br><br>print(&quot;---------------------------------------------------&quot;)<br><br>/*<br>In the second example using a while loop, <br>I incremented the &#39;j&#39; variable within the loop.<br>It is evident that the loop considers the updated &#39;j&#39; value <br>and continues with the newly incremented value. Consequently, <br>the loop executed only two times fewer than the original four times.<br> */<br><br><br>array = [1,2,3,4]<br>numberOfTimesLoopRuns = 0<br><br><br>i = 0<br>while i &lt; array.count {<br>    numberOfTimesLoopRuns += 1<br>    i += 2<br>}<br><br><br>print(numberOfTimesLoopRuns)<br>print(array)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e801ccbde924" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>