<?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 Mahi Garg on Medium]]></title>
        <description><![CDATA[Stories by Mahi Garg on Medium]]></description>
        <link>https://medium.com/@mahigarg?source=rss-e5928b71dc78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oVVEowmHvUnZAvNRDj14Cw.jpeg</url>
            <title>Stories by Mahi Garg on Medium</title>
            <link>https://medium.com/@mahigarg?source=rss-e5928b71dc78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:46:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahigarg/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[Count with where clause (count(where:)) in Swift]]></title>
            <link>https://medium.com/@mahigarg/count-with-where-clause-count-where-in-swift-fad641215633?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/fad641215633</guid>
            <category><![CDATA[swift-programing-language]]></category>
            <category><![CDATA[swift-6]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift-filter]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:53:47 GMT</pubDate>
            <atom:updated>2024-11-12T07:53:47.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>In Swift, the <em>count(where:)</em> method is a powerful tool for filtering and counting elements in a collection that meet specific criteria. This method is part of the Swift Standard Library’s extensions to <em>Sequence</em> and allows for a concise and expressive way to determine how many elements in a collection match a given predicate.</p><p><em>count(where:)</em> method is introduced in Swift 6.0 that performs the equivalent of a <em>filter()</em> and count in a single pass. This saves the creation of a new array that gets immediately discarded, and provides a clear and concise solution to a common problem. Keep in mind this is only available from Swift 6.0 only.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/count-with-where-clause-in-swift/">https://mahigarg.github.io/blogs/count-with-where-clause-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>What is count(where:)?</h3><p>The count(where:) method returns the number of elements in a collection that satisfy a specified condition (predicate). It’s a convenient way to count elements without having to filter the collection first and then count the resulting array, which makes the code both more readable and efficient.</p><h3>Syntax</h3><p>The general syntax for <em>count(where:)</em> is:</p><pre>let count = collection.count(where: { predicate })<br>//or <br>let count = collection.count { predicate }</pre><p>Here, collection is the sequence you are working with, and <em>{ predicate }</em> is a closure that takes an element of the sequence and returns a Bool indicating whether the element should be counted.</p><h3>Examples Using Different Types of Sequences</h3><h4>1. Array</h4><p>An array is an ordered collection that can contain duplicates and allows random access.</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/count-with-where-clause-in-swift/">https://mahigarg.github.io/blogs/count-with-where-clause-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fad641215633" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Property Observers (willset & didset) in Swift]]></title>
            <link>https://medium.com/@mahigarg/property-observers-willset-didset-in-swift-8257a35bc5f8?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/8257a35bc5f8</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift-coding]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-properties]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:47:09 GMT</pubDate>
            <atom:updated>2024-11-12T07:47:09.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>Property observers in Swift are an incredibly useful feature that allows you to monitor and respond to changes in a property’s value. They are especially handy when you want to perform additional tasks whenever a property is set or updated, such as updating the UI, logging data, or enforcing business logic.</p><p>In this blog, we’ll dive into what property observers are, how they work, and how to use them in your Swift code with practical examples.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/property-observers-willset-didset-in-swift/">https://mahigarg.github.io/blogs/property-observers-willset-didset-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>What are Property Observers?</h3><p>Property observers observe and respond to changes in a property’s value. You can define property observers for both stored properties (properties with an initial value) and computed properties. Property observers do not trigger for the initial assignment (when the property is first initialized); they only react when the property’s value is explicitly set.</p><h4>Swift provides two kinds of property observers:</h4><ul><li><em>willSet</em>: Called just before the value is set.</li><li><em>didSet</em>: Called immediately after the value has been set.</li></ul><h3>Syntax for Property Observers</h3><p>Here is the basic syntax:</p><pre>var property: Type {<br>    willSet {<br>        // Code executed just before the property is set<br>    }<br>    didSet {<br>        // Code executed immediately after the property is set<br>    }<br>}</pre><p>Let’s now explore these observers with examples.</p><h3>Using didSet to Track Property Changes</h3><p>Suppose we have a class that represents a <em>UserProfile</em> where we want to keep track of the user’s age. We can use the <em>didSet</em> observer to react whenever the age property changes:</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/property-observers-willset-didset-in-swift/">https://mahigarg.github.io/blogs/property-observers-willset-didset-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8257a35bc5f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Associated types in Swift]]></title>
            <link>https://medium.com/@mahigarg/associated-types-in-swift-d7d7da116426?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7d7da116426</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-protocol]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift-generic-types]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:42:46 GMT</pubDate>
            <atom:updated>2024-11-12T07:42:46.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>Swift’s powerful generics system allows developers to write flexible and reusable code. One of the core features of generics is associated types, which are used in protocols to define placeholder types that get specified later when the protocol is adopted by a class, struct, or enum. Understanding associated types is crucial when working with Swift’s protocols, and in this blog, we’ll explore their concept, usage, and real-world examples.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/associated-types-in-swift/">https://mahigarg.github.io/blogs/associated-types-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>What Are Associated Types?</h3><p>Associated types in Swift are placeholders that define types that will be provided when a protocol is adopted. They allow protocols to work with generic types without specifying what those types are upfront. When you declare an associated type, you’re essentially saying, “I don’t care what the type is right now, but the conforming type will specify it later.”</p><p>Syntax</p><p>You declare an associated type in a protocol using the <em>associatedtype</em> keyword:</p><pre>protocol SomeProtocol {<br>    associatedtype Item<br>    func doSomething(with item: Item)<br>}</pre><p>In this protocol, <em>Item</em> is an associated type. Any type that conforms to <em>SomeProtocol</em> will need to define what <em>Item</em> refers to.</p><h3>Why Use Associated Types?</h3><p>Associated types make protocols more flexible by allowing them to work with generic types. Instead of defining a protocol that works with one specific type, you can define a protocol that works with any type, which will be specified later when the protocol is implemented.</p><p>Basic Example</p><p>Let’s start with a simple example. Suppose we want to create a protocol for a container that can hold items of any type. We don’t know the type of the items at the time of protocol declaration, but the conforming type will be specified later.</p><pre>protocol Container {<br>    associatedtype Item<br>    var items: [Item] { get set }<br>    <br>    func add(item: Item)<br>    func getItem(at index: Int) -&gt; Item<br>}</pre><p>Here, <em>Container</em> is a protocol that defines an associated type <em>Item</em>. The protocol also defines an array <em>items</em> that holds elements of type <em>Item</em> and functions to add and retrieve items from the container.</p><p>Now, let’s conform to this protocol using a <em>StringContainer</em> that holds strings:</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/associated-types-in-swift/">https://mahigarg.github.io/blogs/associated-types-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7d7da116426" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Round vs Floor vs Ceil: Swift]]></title>
            <link>https://medium.com/@mahigarg/round-vs-floor-vs-ceil-swift-eb209aa4759f?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb209aa4759f</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programing-language]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:38:00 GMT</pubDate>
            <atom:updated>2024-11-15T02:53:52.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>In Swift, working with floating-point numbers often requires you to round values to their nearest whole number or perform specific types of rounding. The three primary functions that help with this are:</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/round-vs-floor-vs-ceil-swift/">https://mahigarg.github.io/blogs/round-vs-floor-vs-ceil-swift/</a> <em>and later reposted on Medium.</em></p><ul><li><em>round()</em>: Rounds a number to the nearest integer.</li><li><em>floor()</em>: Rounds a number down to the largest integer less than or equal to the number.</li><li><em>ceil()</em>: Rounds a number up to the smallest integer greater than or equal to the number.</li></ul><p>In this blog post, we’ll break down the differences between these functions, how and when to use each one, and show practical examples for real-world applications.</p><h3>The round() Function</h3><p>The <em>round()</em> function in Swift rounds a floating-point number to the nearest integer. If the decimal part of the number is 0.5 or greater, <em>round()</em> will round up; otherwise, it rounds down.</p><p>Example:</p><pre>let value1 = 5.4<br>let roundedValue1 = value1.rounded()<br>print(roundedValue1)  // Output: 5.0<br><br>let value2 = 5.6<br>let roundedValue2 = value2.rounded()<br>print(roundedValue2)  // Output: 6.0</pre><p>Key points:</p><ul><li><strong>Rounding down</strong>: Numbers less than 0.5 will round down to the nearest whole number.</li><li><strong>Rounding up</strong>: Numbers greater than or equal to 0.5 will round up to the nearest whole number.</li></ul><p>Example with negative numbers:</p><pre>let negativeValue1 = -5.4<br>print(negativeValue1.rounded())  // Output: -5.0<br><br>let negativeValue2 = -5.6<br>print(negativeValue2.rounded())  // Output: -6.0</pre><p>With negative numbers, <em>round()</em> behaves similarly: if the decimal part is less than -0.5, it rounds away from zero (down in magnitude); otherwise, it rounds toward zero.</p><h3>The floor() Function</h3><p>The <em>floor()</em> function always rounds a floating-point number down to the largest integer less than or equal to the number. This behavior remains consistent regardless of the decimal part of the number.</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/round-vs-floor-vs-ceil-swift/">https://mahigarg.github.io/blogs/round-vs-floor-vs-ceil-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb209aa4759f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[try catch and throws: Error handling in Swift]]></title>
            <link>https://medium.com/@mahigarg/try-catch-and-throws-error-handling-in-swift-46d72c05f6f2?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/46d72c05f6f2</guid>
            <category><![CDATA[swift-programing-language]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[error-handling-in-swift]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:29:37 GMT</pubDate>
            <atom:updated>2024-11-12T07:29:37.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>Error handling is an essential feature of modern programming languages, allowing developers to gracefully manage runtime issues without crashing an app. Swift has a robust error-handling system based on the concepts of throwing, catching, propagating, and handling errors. In this blog, we will explore how error handling works in Swift using <em>try</em>, <em>catch</em>, and <em>throws</em> with detailed explanations and practical examples.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/try-catch-and-throws-error-handling-in-swift/">https://mahigarg.github.io/blogs/try-catch-and-throws-error-handling-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>What is Error Handling?</h3><p>Error handling in Swift enables you to anticipate and handle potential failures in your code. Instead of allowing your app to crash when it encounters a problem, error handling lets you catch the error, examine it, and decide how to respond — whether by fixing the issue, retrying, or informing the user.</p><p>In Swift, functions or methods that can throw errors are marked with the <em>throws</em> keyword, and any error handling is done using <em>do</em>, <em>try</em>, <em>catch</em>, and <em>throw</em> statements.</p><h3>Defining Errors</h3><p>Errors in Swift must conform to the <em>Error</em> protocol. Typically, errors are represented using <em>enum</em> types because they are ideal for listing various error conditions.</p><p>Here’s a basic example of how to define custom errors:</p><pre>enum FileError: Error {<br>    case fileNotFound<br>    case unreadable<br>    case encodingFailed<br>}</pre><p>In this example, <em>FileError</em> represents a few potential issues when dealing with files: the file might not exist, it might be unreadable, or encoding the file’s contents might fail.</p><h3>Throwing Errors</h3><p>A function or method can indicate that it might throw an error by adding the <em>throws</em> keyword to its declaration. When you need to signal an error in such a function, use the <em>throw</em> keyword followed by an error value.</p><pre>func readFile(named filename: String) throws -&gt; String {<br>    guard filename == &quot;example.txt&quot; else {<br>        throw FileError.fileNotFound<br>    }<br>    <br>    return &quot;File contents here&quot;<br>}</pre><p>In the <em>readFile</em> function, an error is thrown if the file’s name is anything other than <em>example.txt</em>. This function is marked with <em>throws</em> to indicate that it can throw errors.</p><h3>Handling Errors with do, try, and catch</h3><p>When you call a function that throws an error, you must handle the potential error. This is where the <em>do</em>, <em>try</em>, and <em>catch</em> keywords come into play.</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/try-catch-and-throws-error-handling-in-swift/">https://mahigarg.github.io/blogs/try-catch-and-throws-error-handling-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46d72c05f6f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Class Hierarchy of UIButton, UILabel, and UIImageview in Swift]]></title>
            <link>https://medium.com/@mahigarg/class-hierarchy-of-uibutton-uilabel-and-uiimageview-in-swift-dc8693480412?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc8693480412</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[programing-language]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:23:54 GMT</pubDate>
            <atom:updated>2024-11-12T07:23:54.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>When building user interfaces in iOS applications, UIKit provides a wide array of components, each designed for specific use cases. Three of the most commonly used UI components are <em>UIButton</em>, <em>UILabel</em>, and <em>UIImageView</em>. These components share a common ancestor in the UIKit class hierarchy but serve different purposes and exhibit different behaviors.</p><p>In this blog, we will explore and compare the class hierarchy of these three key UIKit elements, starting from their root superclass and understanding the differences in their inheritance trees.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/class-hierarchy-of-uibutton-uilabel-and-uiimageview-in-swift/">https://mahigarg.github.io/blogs/class-hierarchy-of-uibutton-uilabel-and-uiimageview-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>1. UIButton Class Hierarchy</h3><p><em>UIButton</em> is a user-interactive component that triggers actions in response to user events such as taps. As a subclass of <em>UIControl</em>, it provides various control-specific behaviors such as touch handling and event generation. Let’s break down its class hierarchy:</p><ul><li>NSObject</li><li>UIResponder</li><li>UIView</li><li>UIControl</li><li>UIButton</li></ul><p>Explanation:</p><ul><li><strong>NSObject</strong>: The root class of most Objective-C and Swift classes, it provides fundamental behavior such as memory management.</li><li><strong>UIResponder</strong>: Inherited from <em>NSObject</em>, it enables event handling, including touch events, gestures, and motion events. Every UI element that can handle user interactions is a subclass of UIResponder.</li><li><strong>UIView</strong>: As a subclass of <em>UIView</em>, <em>UIButton</em> gains the ability to render itself on the screen, manage layout, and respond to touch events.</li><li><strong>UIControl</strong>: <em>UIControl</em> introduces event-handling features specific to user controls, such as buttons, sliders, or switches. It enables the <em>UIButton</em> to trigger actions and handle UI events like touches and taps.</li><li><strong>UIButton</strong>: The final class in the hierarchy, <em>UIButton</em>, adds additional functionality for handling user taps, configuring titles, images, and styling.</li></ul><p>Key Features:</p><ul><li>User interaction enabled.</li><li>Supports customizable titles, images, and states (e.g., highlighted, disabled).</li><li>Triggers events when tapped.</li></ul><h3>2. UILabel Class Hierarchy</h3><p><em>UILabel</em> is a non-interactive UI element primarily used for displaying static or dynamic text. It provides text styling and layout options, but it doesn’t inherit from <em>UIControl</em> as it doesn’t handle user events.</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/class-hierarchy-of-uibutton-uilabel-and-uiimageview-in-swift/">https://mahigarg.github.io/blogs/class-hierarchy-of-uibutton-uilabel-and-uiimageview-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc8693480412" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Sided Range in Swift]]></title>
            <link>https://medium.com/@mahigarg/one-sided-range-in-swift-e19194b17f4e?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/e19194b17f4e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programing-language]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:15:38 GMT</pubDate>
            <atom:updated>2024-11-12T07:15:38.075Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>Swift provides a powerful way to work with collections through ranges, which define a sequence of values with a start and an end. In addition to the traditional closed (<em>...</em>) and half-open (<em>..&lt;</em>) ranges, Swift introduces one-sided ranges, a feature that makes working with sequences and collections more flexible and concise.</p><p>In this post, we’ll explore what one-sided ranges are, how to use them, and some practical examples to demonstrate their power.</p><p><em>This post was originally posted at </em><a href="https://mahigarg.github.io/blogs/one-sided-range-in-swift/">https://mahigarg.github.io/blogs/one-sided-range-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>What is a One-Sided Range?</h3><p>In Swift, ranges typically have both a start and an end. However, there are scenarios where you might only care about one side of the range — either the starting point or the endpoint. That’s where one-sided ranges come in.</p><p>Types of One-Sided Ranges</p><p>There are two types of one-sided ranges in Swift:</p><ol><li>From a starting index to the end: <em>start...</em></li><li>From the beginning to an ending index: <em>...end</em></li></ol><p>These ranges don’t require both a starting and an ending index, allowing you to specify only one side.</p><h3>One-Sided Range Syntax</h3><p>From a Starting Index to the End (start…)</p><p>The one-sided range <em>start...</em> starts at the specified <em>start</em> index and goes all the way to the end of the collection.</p><pre>let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>let subset = numbers[3...] // Starts from index 3 to the end<br>print(subset)  // Output: [4, 5, 6, 7, 8, 9, 10]</pre><p>In this example, <em>3...</em> is a one-sided range that starts at index 3 (which is the number 4 in the <em>numbers</em> array) and goes to the end of the array.</p><p>From the Beginning to an Ending Index (…end)</p><p>The one-sided range <em>...end</em> starts from the beginning of the collection and goes up to the specified <em>end</em> index.</p><pre>let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br>let subset = numbers[...4]  // Ends at index 4 (inclusive)<br>print(subset)  // Output: [1, 2, 3, 4, 5]</pre><p>Here, the range <em>...4</em> means “from the beginning to index 4”, and it includes the value at index 4, which is the number 5.</p><h3>Practical Examples of One-Sided Ranges</h3><p>1. Slicing an Array</p><p>One-sided ranges are especially useful for slicing arrays. You can grab either the “tail” or “head” of an array in a very concise way.</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/one-sided-range-in-swift/">https://mahigarg.github.io/blogs/one-sided-range-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e19194b17f4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[some Vs any in Swift]]></title>
            <link>https://medium.com/@mahigarg/some-vs-any-in-swift-589c5ce0da70?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/589c5ce0da70</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[swift-programing-language]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 07:08:43 GMT</pubDate>
            <atom:updated>2024-11-12T07:10:15.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>Swift 5.7 introduced two powerful keywords, <em>some</em> and <em>any</em>, to work with protocols in generic programming. Although they serve different purposes, they both deal with protocols and types. If you’re unfamiliar with how to use them or what sets them apart, this blog post will clarify their differences and show you practical examples.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/some-vs-any-in-swift/">https://mahigarg.github.io/blogs/some-vs-any-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>What are some and any?</h3><p>Before Swift 5.7, protocols with associated types and generic constraints often made code complex to read. Swift introduced <em>some</em> and <em>any</em> as simpler, more powerful tools for abstracting over types that conform to protocols.</p><ul><li><em>some</em>: Refers to an opaque type — a specific type that conforms to a protocol but the exact type isn’t revealed. It enforces that the type remains the same throughout the function or property.</li><li><em>any</em>: Refers to an existential type — any type that conforms to a protocol, allowing multiple conforming types to be used interchangeably.</li></ul><p>Let’s break these down further.</p><h3>Using some for Opaque Types</h3><p>When you use <em>some</em>, Swift returns a concrete, specific type that conforms to a protocol, but you don’t know exactly which type it is. The compiler enforces that the same type is returned each time, ensuring consistency.</p><p>Example: some in Action</p><p>Consider a function that returns a value conforming to the Shape protocol:</p><pre>protocol Shape {<br>    func area() -&gt; Double<br>}<br><br>struct Circle: Shape {<br>    let radius: Double<br>    func area() -&gt; Double {<br>        return .pi * radius * radius<br>    }<br>}<br><br>struct Square: Shape {<br>    let side: Double<br>    func area() -&gt; Double {<br>        return side * side<br>    }<br>}<br><br>func makeShape() -&gt; some Shape {<br>    return Circle(radius: 5)<br>}<br><br>let shape = makeShape()<br>print(shape.area()) // Output: 78.53981633974483</pre><p>In this example, the <em>makeShape()</em> function returns <em>some Shape</em>, meaning it returns a specific type that conforms to <em>Shape</em> — in this case, a <em>Circle</em>. However, users of the function don’t need to know that the return type is <em>Circle</em>; they only need to know it conforms to <em>Shape</em>.</p><p>Key point: The type returned by <em>some</em> must remain consistent. For example, you cannot return both <em>Circle</em> and <em>Square</em> from the same function using <em>some Shape</em>.</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/some-vs-any-in-swift/">https://mahigarg.github.io/blogs/some-vs-any-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=589c5ce0da70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Opaque in Swift]]></title>
            <link>https://medium.com/@mahigarg/opaque-in-swift-d86347644227?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d86347644227</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[swift-programing-language]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 06:49:12 GMT</pubDate>
            <atom:updated>2024-11-11T07:06:30.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>Swift is known for its powerful type system and support for generics, which allows you to write flexible and reusable code. However, there are situations where generics can become overly complex or expose too much internal detail. To help with this, Swift introduced opaque types (using the some keyword) in Swift 5.1. Opaque types allow us to hide the underlying type while still maintaining strong type safety.</p><p>In this blog, we’ll explore what opaque types are, how they differ from protocols with associated types and existential, and look at practical examples where using <em>some</em> can simplify code.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/opaque-in-swift/">https://mahigarg.github.io/blogs/opaque-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>What is an Opaque Type?</h3><p>An opaque type in Swift is a way to hide the exact type returned by a function or property while still retaining type information for the compiler. This allows the caller to know the type exists and is the same across invocations but doesn’t reveal the specific type. It is often used with the <em>some</em> keyword, which specifies that the returned value conforms to a particular protocol but keeps the concrete type hidden.</p><p>Here’s a simple example of an opaque type:</p><pre>func makeOpaqueShape() -&gt; some Shape {<br>    return Circle(radius: 5)<br>}</pre><p>In this case, the function <em>makeOpaqueShape</em> returns some type that conforms to the <em>Shape</em> protocol, but the caller does not need to know the specific type (<em>Circle</em> in this case). All the caller knows is that the result conforms to the <em>Shape</em> protocol.</p><h3>Why Use Opaque Types?</h3><p><strong>Opaque types are useful when:</strong></p><ul><li>You want to hide the implementation details of a type but still maintain type safety.</li><li>You want to avoid exposing complex or unnecessary type information to the caller.</li><li>You want to avoid the performance overhead of boxing types (like with protocol existentials).</li><li>You want a simple alternative to returning types with generics, without making your code overly complex.</li></ul><p>Opaque types offer several advantages over using protocol types (also known as existentials), especially when you need to preserve the concrete type for operations like comparisons or optimizations that rely on the specific type.</p><h3>Opaque Types vs. Protocols with Associated Types</h3><p>Opaque types are different from protocol existentials, especially in cases where associated types or <em>Self</em> requirements are involved. Let’s clarify the distinction with an example.</p><p>Protocol Existentials Example</p><p>Suppose you have a protocol:</p><pre>protocol Shape {<br>    func area() -&gt; Double<br>}</pre><p>And you want to return something that conforms to this protocol:</p><pre>func makeShape() -&gt; Shape {<br>    return Circle(radius: 5)<br>}</pre><p>This works because <em>Circle</em> conforms to <em>Shape</em>. However, the type information is erased, meaning you lose the concrete type and only know that it conforms to <em>Shape</em>. If we want to keep the exact type hidden while ensuring the return type is consistent across invocations, we can use <em>some</em> (an opaque type).</p><p>Opaque Type Example</p><pre>func makeOpaqueShape() -&gt; some Shape {<br>    return Circle(radius: 5)<br>}</pre><p>The key difference here is that with <em>some Shape</em>, the caller still knows the return type conforms to <em>Shape</em>, but the compiler also knows that the return type will always be the same specific type across different invocations. In contrast, the existential version (<em>Shape</em>) can return any conforming type, and you lose the specific type information.</p><h3>Practical Example: Geometric Shapes</h3><p>Let’s see how this works with a more detailed example involving geometric shapes.</p><h4>Step 1: Define a Protocol</h4><p>We’ll define a <em>Shape</em> protocol that requires a method to compute the area of the shape</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/opaque-in-swift/">https://mahigarg.github.io/blogs/opaque-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d86347644227" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access Modifiers in Swift]]></title>
            <link>https://medium.com/@mahigarg/access-modifiers-in-swift-d08c1b36d296?source=rss-e5928b71dc78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d08c1b36d296</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-access-control]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[swift-programing-language]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Mahi Garg]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 06:42:00 GMT</pubDate>
            <atom:updated>2024-11-11T06:42:00.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jdJTBeYfkRbTA-aoSrcisQ.jpeg" /></figure><p>Access control is a fundamental feature in Swift that allows you to define the visibility and accessibility of various parts of your code. By using access modifiers, you can encapsulate implementation details and restrict unintended access to your code, ensuring safety and modularity.</p><p><em>This blog was originally posted at </em><a href="https://mahigarg.github.io/blogs/access-modifiers-in-swift/">https://mahigarg.github.io/blogs/access-modifiers-in-swift/</a> <em>and later reposted on Medium.</em></p><h3>Swift offers five access levels:</h3><ul><li><strong>Open</strong>: The most permissive access level; it allows subclassing and overriding outside the module.</li><li><strong>Public</strong>: Allows access outside the module but prevents subclassing and overriding.</li><li><strong>Internal</strong>: Default access level, allowing access within the same module.</li><li><strong>Fileprivate</strong>: Restricts access to the same file.</li><li><strong>Private</strong>: The most restrictive level, limiting access to the enclosing declaration.</li></ul><p>In this blog, we’ll dive into each of these access modifiers, explain their differences, and look at examples.</p><h3>1. Open: Maximum Accessibility and Flexibility</h3><p><em>open</em> is the most permissive access modifier in Swift. It allows the code entity (class, method, or property) to be accessed, subclassed, and overridden from any module, including outside the module in which it is defined. It is primarily used for frameworks where you intend to allow other developers to extend your code.</p><p>Example:</p><pre>// Module A<br>open class Animal {<br>    open func makeSound() {<br>        print(&quot;Some generic sound&quot;)<br>    }<br>}<br>// Module B<br>import ModuleAclass Cat: Animal {<br>    override func makeSound() {<br>        print(&quot;Meow!&quot;)<br>    }<br>}<br><br>let myCat = Cat()<br>myCat.makeSound()  // Output: &quot;Meow!&quot;</pre><p>In this case, the <em>Animal</em> class and its <em>makeSound()</em> method are marked open, allowing them to be subclassed and overridden in another module.</p><p>Key Points:</p><ul><li><strong>Accessible</strong>: Anywhere (inside and outside the module).</li><li><strong>Subclassing</strong>: Allowed in any module.</li><li><strong>Overriding</strong>: Allowed in any module.</li></ul><h3>2. Public: Controlled External Access</h3><p><em>public</em> allows access to entities from outside the module, but unlike <em>open</em>, it prevents subclassing and method overriding outside the module.</p><h4>Please continue reading at <a href="https://mahigarg.github.io/blogs/access-modifiers-in-swift/">https://mahigarg.github.io/blogs/access-modifiers-in-swift/</a></h4><p>That’s all for now. You can read my other interesting blogs <a href="https://mahigarg.github.io/blogs/">here</a>. Feel free to use my open-source iOS components in your app, listed <a href="https://mahigarg.github.io/opensourcecontribution/">here</a>. Or drop an <a href="/service/mailto:mahi7garg@gmail.com">email</a>, if you didn’t find what you are looking for and need help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d08c1b36d296" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>