<?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 Swarandeep Singh Sran on Medium]]></title>
        <description><![CDATA[Stories by Swarandeep Singh Sran on Medium]]></description>
        <link>https://medium.com/@swarandeepsinghsran?source=rss-56554a6a0caf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RGNouV5ksl8ZA0bXdKWQLg.jpeg</url>
            <title>Stories by Swarandeep Singh Sran on Medium</title>
            <link>https://medium.com/@swarandeepsinghsran?source=rss-56554a6a0caf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:34:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swarandeepsinghsran/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[Combine for Swift]]></title>
            <link>https://swarandeepsinghsran.medium.com/combine-for-swift-ee403c04f9ec?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee403c04f9ec</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 12:05:31 GMT</pubDate>
            <atom:updated>2024-11-10T16:10:18.895Z</atom:updated>
            <content:encoded><![CDATA[<p>Combine is very vast topic. To better understand it, we will break it into number of articles. So, In this (first) article, we will go through the basics of combile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rRdp-jM635NrEXgH.png" /></figure><p>According to Apple’s official documentation</p><blockquote>The Combine framework provides a declarative Swift API for processing values over time. These values can represent many kinds of asynchronous events. Combine declares <em>publishers</em> to expose values that can change over time, and <em>subscribers</em> to receive those values from the publishers.<br>(<a href="https://developer.apple.com/documentation/combine">https://developer.apple.com/documentation/combine</a>)</blockquote><p>Before moving forward, lets recap what’s the difference between Declarative and Imperative</p><p><strong>Imperative</strong> means Step-by-Step approach. With an imperative approach, you manually define the steps to achieve a result.<br>Code Example:</p><pre>var numbers = [1, 2, 3, 4, 5]<br>var result = [Int]()<br><br>for number in numbers {<br>    if number &gt; 2 {<br>        result.append(number * 2)<br>    }<br>}<br>print(result)</pre><p>A <strong>declarative</strong> approach focuses on what you want to accomplish, not the exact steps to do it.</p><pre>let numbers = [1, 2, 3, 4, 5]<br>let result = numbers.filter { $0 &gt; 2 }.map { $0 * 2 }<br>print(result)</pre><p><strong>Declarative</strong> APIs make code more concise, easier to read, and often simpler to maintain. In reactive programming frameworks like Combine, RxSwift, or ReactiveSwift, declarative APIs allow developers to handle complex asynchronous operations in a readable way, without explicitly managing each state change or step in the process.</p><h3>Publishers and subscribers</h3><p><strong>Publishers</strong> and <strong>Subscribers</strong> are the two primary components for handling asynchronous data streams</p><p>A <strong>Publisher</strong> is an object that produces a stream of values over time, which other components (Subscribers) can listen to. Publishers define <em>what kind of data</em> they emit and <em>what kind of errors</em> (if any) they can produce. Publishers don’t actively produce values until a Subscriber subscribes to them.</p><h4>Key Characteristics of Publishers</h4><ol><li><strong>Types of Publishers</strong>: Publishers can produce a single value, multiple values, or even no values, depending on the type of stream or data source.</li><li><strong>Type-Safe Data and Errors</strong>: Each Publisher has two associated types:</li></ol><ul><li>Output: The type of data it emits.</li><li>Failure: The type of error it might produce (if any).</li></ul><p>3.<strong> Declarative Pipelines</strong>: You can apply various Combine operators (e.g., map, filter, debounce) to transform, filter, or process the values in a publisher&#39;s stream.</p><pre>import Combine<br><br>// A publisher that emits a single integer value<br>let numberPublisher = Just(5)<br><br>numberPublisher<br>    .map { $0 * 2 } // Transform the value by doubling it<br>    .sink { value in<br>        print(&quot;Received value: \(value)&quot;) // Output: Received value: 10<br>    }</pre><p>We can get the list of all the publisher operators in the <a href="https://developer.apple.com/documentation/combine/publisher">link</a></p><p>A <strong>Subscriber</strong> is an object that “subscribes” to a Publisher and receives the values it emits. Subscribers are responsible for defining how to handle incoming data and completion events (success or failure). When a Publisher produces new values, it sends them to its subscribers.</p><h4>Key Characteristics of Subscribers</h4><ol><li><strong>Receiving Data</strong>: Subscribers receive values from Publishers and define actions to take with those values.</li><li><strong>Completion Handling</strong>: They handle the end of the stream, which can either be:</li></ol><ul><li><strong>Finished</strong>: The Publisher has completed successfully.</li><li><strong>Failure</strong>: The Publisher has completed with an error.</li></ul><p>3<strong>. Built-In Subscribers</strong>: The Combine framework provides a built-in subscriber called sink, which allows you to define closures for handling values and completion events.</p><pre>import Combine<br><br>let namePublisher = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;].publisher<br><br>namePublisher<br>    .filter { $0.starts(with: &quot;A&quot;) } // Filter names that start with &quot;A&quot;<br>    .sink(<br>        receiveCompletion: { completion in<br>            print(&quot;Stream completed with: \(completion)&quot;)<br>        },<br>        receiveValue: { name in<br>            print(&quot;Received name: \(name)&quot;)<br>        }<br>    )</pre><h3>Relationship Between Publishers and Subscribers</h3><ul><li><strong>Subscription</strong>: When a Subscriber subscribes to a Publisher, the Publisher begins emitting values.</li><li><strong>Data Flow</strong>: Data flows from Publisher to Subscriber. This data flow is flexible and can involve transformations, filters, and combinations of multiple Publishers before reaching the Subscriber.</li><li><strong>Completion</strong>: The Publisher notifies the Subscriber when it has no more data (or if it encounters an error).</li></ul><h3>Operators</h3><p><strong>Operators</strong> are powerful methods you can use to transform, filter, combine, or handle data streams emitted by Publishers. Operators allow you to build a <em>pipeline</em> of transformations, making it easy to manipulate data before it reaches your subscribers.</p><pre>let numbers = [1, 2, 3, 4, 5].publisher<br>numbers<br>    .map { $0 * 2 }<br>    .sink { print($0) } // Output: 2, 4, 6, 8, 10</pre><p>In Combine, you can chain multiple operators together to create a <em>pipeline</em> that processes each value emitted by a Publisher, transforming and filtering the data until it reaches the Subscriber. The combination of operators gives you a powerful toolkit for handling data streams in a reactive, declarative, and highly readable way.</p><p>.sink is a method in Combine that attaches a <strong>subscriber</strong> to a Publisher and allows you to handle emitted values and completion events with custom closures. It’s one of the most commonly used ways to receive and process data from a Publisher, often making it the last step in a Combine pipeline.</p><p>When you use .sink, you have the option to define two closures:</p><ol><li><strong>Value closure</strong>: Processes each value that the Publisher emits.</li><li><strong>Completion closure</strong>: Handles the completion event, which could be a normal completion (no more values) or a failure (an error occurred).</li></ol><p>The .sink method also returns an AnyCancellable instance, which represents the subscription and lets you manage its lifecycle.</p><pre>import Combine<br><br>let publisher = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;].publisher<br><br>let cancellable = publisher.sink(<br>    receiveCompletion: { completion in<br>        switch completion {<br>        case .finished:<br>            print(&quot;Finished successfully.&quot;)<br>        case .failure(let error):<br>            print(&quot;Finished with error: \(error)&quot;)<br>        }<br>    },<br>    receiveValue: { value in<br>        print(&quot;Received value: \(value)&quot;)<br>    }<br>)<br><br>// Output:<br>// Received value: A<br>// Received value: B<br>// Received value: C<br>// Finished successfully.</pre><p>The .assign operator in Combine is used to bind (or &quot;assign&quot;) the output of a publisher to a property on an object. It’s particularly useful when you want to automatically update properties with values from a publisher’s stream without needing a custom sink or explicit subscription handling.</p><p>Syntax</p><pre>publisher<br>    .assign(to: \.property, on: object)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee403c04f9ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[clipsToBounds in Swift]]></title>
            <link>https://swarandeepsinghsran.medium.com/clipstobounds-in-swift-363aa61c524?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/363aa61c524</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 17:20:56 GMT</pubDate>
            <atom:updated>2023-03-10T17:20:56.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5ESlkpyDxC0be7ZB.png" /></figure><blockquote>A Boolean value that determines whether subviews are confined to the bounds of the view. — Apple Docs</blockquote><p>Setting this value to true causes subviews to be clipped to the bounds of the view. If set to false, subviews whose frames extend beyond the visible bounds of the view aren’t clipped. The default value is false. Some subclasses of UIView, like <a href="https://developer.apple.com/documentation/uikit/uiscrollview">UIScrollView</a>, override the default value to true.</p><p>Let us understand this with help of an example. Create a new Xcode project. Place a UIView in the centre of screen. Give it some constraints and a colour (brown in this case) to make it appear distinct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*8CDgLijzkhQt1qrOLEtTHw.png" /><figcaption>Initial Setup</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*QKDDZOqI8Rt9LTlOWRJEhA.png" /><figcaption>The Constraints that I have applied on the brown view</figcaption></figure><p>Create IBOutlet of brown view and actually name it brownView. Now add the following code to viewDidLoad method and then run the app.</p><pre>brownView.layer.cornerRadius = 40</pre><p>We get the following Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*qdm2zvSkVLsZO-DqO7jHog.png" /><figcaption>The corners get rounded.</figcaption></figure><p>Now add a new UIView inside brownView and give (0,0,0,0) constraints to it with brownView as shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9uugwCKscexoqJr22wBK7g.gif" /></figure><p>Now run the app again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*HQ-x2nL4vviCcYeCGnR7Jg.png" /></figure><p>We notice that redView has no corner radius. But why? It is inside brownView and we have given cornerRadius to brownView, and hence it should have cornerRadius.</p><p>When we give a view rounded corners in an iOS app, we may notice that the view looks rounded but any content inside it (like images or text) spills over the edges of the rounded corners. Setting clipsToBounds to true on the view ensures that the content inside the view is also cut off at the rounded corners, making everything look neat and tidy. It&#39;s like cutting a photo to fit into a picture frame - if the photo is too big, we cut off the edges so it fits nicely.</p><p>Now add this line in viewDidLoad and re-run the app</p><pre>brownView.clipsToBounds = true</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*yvB0RdJQdabG6-EfOmHrMQ.png" /><figcaption>Final Output</figcaption></figure><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=363aa61c524" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[first property in Swift]]></title>
            <link>https://swarandeepsinghsran.medium.com/first-property-in-swift-1678ea29c7a8?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1678ea29c7a8</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 15:06:02 GMT</pubDate>
            <atom:updated>2023-03-10T15:06:02.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>first property in Swift Array</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KJ2TF_azTa3fQEvH.png" /></figure><p>In this article we are going to see the importance of first property in Array Collection.</p><p>The value of the property is the first element of the collection. If the collection is empty, the value of this property is nil.</p><p>Example:</p><pre>let array = [1,2,3]<br>let element = array.first</pre><p>The value of element is 1.</p><h3><strong>Benefits of using first property instead of array[0]</strong></h3><p>first property is optional, it means that it’s value can be nil. Consider the below function.</p><pre>func getFirstElement(array: [Int]?) -&gt; Int? {<br>    return array?[0]<br>}</pre><p>Consider an empty array</p><pre>let array: [Int]? = []</pre><p>Let us pass this array into the above function and see what happens</p><pre>print(getFirstElement(array: array1))</pre><p>OOPS! The app crashed. This is because the 0th index does not exists as the array is empty. We need to return nil in this case. Let us modify our function</p><pre>func getFirstElement(array: [Int]?) -&gt; Int? {<br>    if let array = array, array.count &gt; 0 {<br>        return array[0]<br>     } else {<br>         return nil<br>     }<br>}</pre><p>This looks so lengthy and complicated for a basic functionality. first property is the solution to make it short and sweet.</p><pre>func getFirstElementUsingFirst(array: [Int]?) -&gt; Int? {<br>     return array?.first<br> }</pre><p>The above function works in every case.</p><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1678ea29c7a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Builder Pattern in Swift]]></title>
            <link>https://swarandeepsinghsran.medium.com/understanding-builder-pattern-in-swift-2de03ed4536?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2de03ed4536</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 12:44:57 GMT</pubDate>
            <atom:updated>2023-02-05T12:49:36.101Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Builder Design Pattern in Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KLu2wugJtnSro4VB.png" /></figure><p>First of all, it is necessary to understand what Design Patterns are. <a href="https://medium.com/@swarandeepsinghsran/what-are-design-patterns-2b69e4e4af92">Here is my medium article link for the same</a>.<br>It covers the intro to Design Patterns in very concise way. Please do check it in case you are completely beginner to design patterns.</p><blockquote>Builder is a creational design pattern, which allows constructing complex objects step by step.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8QHQmTWJj-gsKgFE" /></figure><p>Let us understand builder pattern with help of an example. Suppose that we are running a Pizza Shop and our aim is to make delicious pizzas for our customers. We make pizzas using struct Pizza. The struct Pizza has size, base and toppings as properties.</p><pre>struct Pizza {<br>    let size: Size<br>    let base: Base<br>    let toppings: [Topping]<br>}</pre><p>Currently we are making only sevenInches and tenInches size pizza. We have two options for pizza base thin and thick. For toppings we have five different varieties, i.e., pepperoni, sausage, mushrooms, onions and blackOlives.</p><pre>enum Size {<br>    case sevenInches<br>    case tenInches<br>}<br><br>enum Base {<br>    case thin<br>    case thick<br>}<br><br>enum Topping {<br>    case pepperoni<br>    case sausage<br>    case mushrooms<br>    case onions<br>    case blackOlives<br>}</pre><p>Now, let us create a pizza of size tenInches, with thin base and onions as toppings. It is very simple. Just create an object of struct Pizza.</p><pre>let pizza = Pizza(size: .tenInches, base: .thin, toppings: [.onions])</pre><p>Now, what if we do not know what the parameters will be. What if the parameter list is too long that we can make a mistake while making entries. Also, what if we want to create a similar pizza with just slight modifications. In that case we still have to specify all the parameters that are unchanged. That will be hell lot of work!!! So, how are we going to overcome these problems? The solution to these problems is <strong>Builder Pattern</strong>.</p><p>Builder Pattern builds object <strong>step by step</strong>. We create PizzaBuilder class that has same variables as Pizza class but here they have <strong>private setters</strong>.<br>We have functions to set Size, Base and Topping. At last we have function build to build our Pizza.</p><pre>class PizzaBuilder {<br>    <br>    private (set) var size: Size = .sevenInches<br>    private (set) var base: Base = .thick<br>    private (set) var toppings: [Topping] = []<br>    <br>    func setSize(_ size: Size) {<br>        self.size = size<br>    }<br>    <br>    func setBase(_ base: Base) {<br>        self.base = base<br>    }<br>    <br>    func addToppings(_ topping: Topping) {<br>        toppings.append(topping)<br>    }<br>    <br>    func build() -&gt; Pizza {<br>        return Pizza(size: size, base: base, toppings: toppings)<br>    }<br>}</pre><p>Now, let us build a Pizza using PizzaBuilder class.</p><pre>        let builder = PizzaBuilder()<br>        builder.setBase(.thin)<br>        builder.setSize(.tenInches)<br>        builder.addToppings(.mushrooms)<br>        builder.addToppings(.onions)<br>        let pizza = builder.build()</pre><p>First we have created an object of PizzaBuilder class and then <strong>step by step</strong> built the Pizza. Here, we can see that we have set each parameter individually and if by any chance we don’t set any parameter value then it will take its default value.</p><p>Now suppose we also want to create another pizza that has all the properties of the pizza that we have just created above and in addition to that it must also have blackOlives as Topping, so in that case we do not need to do extra work because we have the builder object that we have just created above. We simply add blackOlives as Topping using that builder object.</p><pre>builder.addToppings(.blackOlives)<br>let anotherPizza = builder.build()</pre><p><strong>Hurrah</strong>! We have just build anotherPizza of size tenInches, with thin base and onions , mushrooms and blackOlives as toppings.</p><h3>Builder Pattern Pros</h3><ol><li>Builder pattern reduces the parameters of the constructor and makes them highly readable.</li><li>Only fully constructed object will be available to client.</li><li>We can construct objects step by step.</li></ol><h3>Builder Pattern Cons</h3><ol><li>The number of lines and overall complexity of code increases in builder pattern.</li></ol><h3>When to use Builder Pattern?</h3><p>When a lot of parameters are needed in the constructor, the builder design pattern can be employed.</p><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2de03ed4536" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Singleton Design Pattern in Swift]]></title>
            <link>https://swarandeepsinghsran.medium.com/understanding-singleton-design-pattern-in-swift-ab8954212b3a?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab8954212b3a</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 10:40:53 GMT</pubDate>
            <atom:updated>2023-02-05T12:46:03.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9FCg4ZuCqKpzIdUk.png" /></figure><p>First of all, it is necessary to understand what Design Patterns are. <a href="https://medium.com/@swarandeepsinghsran/what-are-design-patterns-2b69e4e4af92">Here is my medium article link for the same</a>.<br>It covers the intro to Design Patterns in very concise way. Please do check it in case you are completely beginner to design patterns.</p><blockquote>Singleton is a design pattern that ensures a class can have only one object. Hence, Singleton pattern restricts a class to only one instance.</blockquote><p>There is a high chance that you have already used Singleton pattern in Swift. The following examples may look similar if you have worked with Apple’s framework.</p><pre>// Shared URL Session<br>let sharedURLSession = URLSession.shared<br><br>// Default File Manager<br>let defaultFileManager = FileManager.default<br><br>// Standard User Defaults<br>let standardUserDefaults = UserDefaults.standard<br><br>// Default Payment Queue<br>let defaultPaymentQueue = SKPaymentQueue.default()</pre><p>Before proceeding further, it is important to know the role of static variables.</p><blockquote>Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object.</blockquote><h3>How to implement Singleton Class?</h3><p>Let us create class Singleton that has a static variable shared and a function businessLogic that performs some task for us.</p><pre>class Singleton {<br>    <br>    static let shared = Singleton()<br>    <br>    // yes, private init!!!<br>    private init() {}<br>    <br>    func businessLogic() {<br>        // some business logic<br>        print(&quot;Business Logic Successfully implemented&quot;)<br>    }<br>}</pre><p>Note that we have used private initialiser for init(). Now, we write the code to use Singleton</p><pre>Singleton.shared.businessLogic()</pre><p>The output is as expected, it runs the function businessLogic. We see <strong><em>Business Logic Successfully implemented</em></strong> printed in the console.</p><p>Now, let us try to create another instance of Singleton class.</p><pre>let anotherInstance = Singleton()</pre><p>Xcode IDE shows an error straight away stating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYpU1fNb07dErQagcF5kZQ.png" /></figure><p>Note that we have used private initialiser for init() in our Singleton class. So, if you try to create a new instance of class Singleton it will throw an error. Hence, the principle of Singleton pattern (only one instance of a class) is verified.</p><h3>Singleton Pattern Pros</h3><ol><li>There is only one instance of a class, we can be certain of that. There is only one instance of a class, we can be certain of that.</li><li>One time initialisation</li></ol><h3>Singleton Pattern Cons</h3><ol><li>The singleton object has global access. This means the singleton object can be access from anywhere in the project.</li><li>Singleton Pattern violates Single Responsibility Principle</li></ol><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab8954212b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Strategy Pattern in Swift in easy way]]></title>
            <link>https://swarandeepsinghsran.medium.com/understand-strategy-pattern-in-swift-in-easy-way-1889a24e3784?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1889a24e3784</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 20:06:57 GMT</pubDate>
            <atom:updated>2023-01-29T20:06:57.382Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, it is necessary to understand what Design Patterns are. <a href="https://medium.com/@swarandeepsinghsran/what-are-design-patterns-2b69e4e4af92">Here is my medium article link for the same</a>.<br>It covers the intro to Design Patterns in very concise way. Please do check it in case you are completely beginner to design patterns.</p><blockquote>In computer programming, the <strong>strategy pattern</strong> (also known as the <strong>policy pattern</strong>) is a behavioural software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use. <br>-Wikipedia</blockquote><blockquote>The strategy pattern defines the family of interchangeable objects that can be fed or switched at runtime.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6izeCpr_FVGy6dAO_0RtQ.png" /><figcaption>Strategy Pattern Class Diagram</figcaption></figure><p>Here, there are three components:<br>1.<strong> Object using a Strategy</strong>: Any kind of object that needs interchangeable behaviour<br>2. <strong>Protocol Strategy:</strong> Method that every strategy must implement<br>3. <strong>Strategies:</strong> Objects that conform to the strategy protocol</p><p><strong><em>Let us understand this with help of code example</em></strong></p><p>Suppose that we are creating a functionality where the user wants to play some sports (say football, basketball, cricket, etc.). We are not sure what different kind of sports user will play. There could be more sports added on, or sports could be deleted at any point of time (i.e. the list of sports that user plays can be modified at any point of time)</p><p>So, how are we going to implement this using code? Remember the challenge is the list of sports that the user play is dynamic.</p><p>The answer is <strong>Strategy pattern</strong>. We first define a base for all the sports. The base is protocol GameStrategy. All the sports need to conform to this protocol.</p><pre>protocol GameStrategy {<br>    func playGame()<br>}</pre><p>protocol GameStrategy has blueprint of function playGame.Now, let us define a class Player that will use GameStrategy protocol</p><pre>class Player {<br>    let gameStrategy: GameStrategy<br>    <br>    init(gameStrategy: GameStrategy) {<br>        self.gameStrategy = gameStrategy<br>    }<br>    <br>    func playGame() {<br>        gameStrategy.playGame()<br>    }<br>}</pre><p>The class Player has a gameStrategy variable and a playGame function. The playGame function further executes the playGame function of gameStrategy protocol.</p><p>Suppose the user wants to play football. We implement FootballStrategy class that conforms to GameStrategy protocol.</p><pre>class FootballStrategy: GameStrategy {<br>    func playGame() {<br>        /// some football strategy<br>        print(&quot;play football&quot;)<br>    }<br>}</pre><p>playGame function for FootballStrategy class has some strategy to play football. At the end of function we have added a print statement to signal the user to play football .</p><p>Now the user also wants to play cricket. So we now implement CricketStrategy class that conforms to GameStrategy protocol.</p><pre>class CricketStrategy: GameStrategy {<br>    func playGame() {<br>        /// some cricket strategy<br>        print(&quot;play cricket&quot;)<br>    }<br>}</pre><p>Similarly, playGame function for CricketStrategy class has some strategy to play cricket. At the end of function we have added a print statement to signal the user to play cricket.</p><p>We then create an instance of Player class by passing CricketStrategy as initializer. We then execute playGame function. The output is <strong><em>play cricket.</em></strong></p><pre>var cricketPlayer = Player(gameStrategy: CricketStrategy())<br>cricketPlayer.playGame()</pre><p>We now create an instance of Player class by passing FootballStrategy as initializer. The output is <strong><em>play football.</em></strong></p><pre>var footballPlayer = Player(gameStrategy: FootballStrategy())<br>footballPlayer.playGame()</pre><p>If in future, the user want to create another sport, they can do so by first creating a class and conforming it to GameStrategy protocol and then creating an instance of Player class by passing that sport class as initializer.</p><p>So we can conclude that:<br>1. Player class is the object using a strategy<br>2. GameStrategy is the protocol strategy<br>3. CricketStrategy and FootballStrategy are different kind of strategies that conform to GameStrategy</p><h3>Advantages of Strategy Pattern</h3><ol><li>Strategy Pattern helps to write clean code because we avoid conditional nested code and we create separate class for different strategies</li><li>The algorithms are loosely coupled with the context entity. They can be changed/replaced without changing the context entity.</li><li>The strategy pattern allows you to modify the algorithm’s implementation without completely disrupting your code.</li></ol><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1889a24e3784" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Design Patterns?]]></title>
            <link>https://swarandeepsinghsran.medium.com/what-are-design-patterns-2b69e4e4af92?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b69e4e4af92</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 17:35:26 GMT</pubDate>
            <atom:updated>2023-01-25T17:35:26.132Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In software engineering, a <strong>software design pattern</strong> is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations.</blockquote><p>Design patterns can <strong>speed up</strong> the development process by providing tested, proven development paradigms. Effective software design must take into account problems that might not surface until later in the execution. Reuse of design patterns helps to <strong>eliminate minor flaws</strong> that can lead to large difficulties. Design patterns <strong>enhances code readability</strong>. Furthermore, patterns enable engineers to <strong>discuss software interactions</strong> using well-known, widely accepted terms.</p><p>To sum up Design Patterns in two words, I would say they are “<strong>Best Practices</strong>”. Design Patterns are nothing more than best practices for a particular problem you are facing. So, design patterns can help you <strong>become a better developer</strong> because you will be able to do the work much quickly saving both money and time.</p><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b69e4e4af92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[iOS] — Content Compression Resistance Priority]]></title>
            <link>https://swarandeepsinghsran.medium.com/ios-content-compression-resistance-priority-b8f0d6cd0ad7?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8f0d6cd0ad7</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 21:42:21 GMT</pubDate>
            <atom:updated>2023-01-21T21:42:21.470Z</atom:updated>
            <content:encoded><![CDATA[<h3>[iOS] — Content Compression Resistance Priority</h3><p>Before going to Content Compression Resistance Priority, it is essential to understand a term called <strong>intrinsic content size.</strong></p><p>So, what the is intrinsic content size? It is simple. It refers to the amount of space the view needs for its content to appear in an ideal state. That means how big a view should be based on what it displays.<br><strong>Example</strong>: For <strong>UILabel, </strong>the intrinsic content size is the size of the text that it displays. The same goes for <strong>UIButton</strong>.</p><blockquote><strong>Content Compression Resistance Priority: </strong>Sets the priority with which a view resists being made smaller than its intrinsic size. — Apple docs (<a href="https://developer.apple.com/documentation/uikit/uiview/1622526-setcontentcompressionresistancep">https://developer.apple.com/documentation/uikit/uiview/1622526-setcontentcompressionresistancep</a>)</blockquote><p>The above statement means that the more the content compression resistance priority, the more it will resist to growing smaller (resist to being compressed) than its content intrinsic size. Always remember that priority is a relative term. So, when there is a deadlock between two views, one should have more content compression resistance priority than the other.</p><p>Let us understand this with an example. Note that I am using Xcode Version 14.0.1 and iPhone 14 Pro as the simulator for the following example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*UytyrHL4A6wFs557URPSyw.png" /><figcaption>Initial Setup</figcaption></figure><p>I have inserted two labels (Yellow label &amp; Green label) and made them vertically centre on the view controller. For the yellow label, I have given a leading constraint of 32 px from the safe area leading, and for the green label, I have given a trailing constraint of 32 from the safe area trailing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/0*Okym2r9hFbup6Kzr.png" /><figcaption>Constraints for Yellow Label</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/0*YPS8yhZmO0T70omO.png" /><figcaption>Constraints for Green Label</figcaption></figure><p>Pretty Smooth? Let us do the confusing thing (confusing for the Auto Layout 😜). If you check, the current space between the Yellow label and the Green label is 36.67 px (maybe different in your case if you haven’t proceeded with the same configurations as me). Let us create a new constraint that makes the space between these two labels 60 px (i.e., more than the current space)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*g2N-Korzwv3uztgPfC6n2Q.gif" /></figure><p>We will notice Auto Layout throws an error. If we look into the error, we will see that Auto Layout asks us to change the Content Compression Resistance priority of any one label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*Bcb9NjXjkuBJE2U4Md8biQ.png" /><figcaption>Auto Layout Error</figcaption></figure><p>Let us first run our application without going deep into the error to see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*GHZk6A9bSxsFJgpti9ikfA.png" /><figcaption>Output on the simulator. The Yellow Label gets compressed</figcaption></figure><p>The Yellow label gets compressed to satisfy the constraint of 60 px space between both labels. Auto Layout needed clarification about which label(s) to trim to meet the 60 px constraint, hence throwing the initial error. At runtime, it randomly compressed the width of the Yellow label to break the deadlock (it may be the Green label in your case).</p><p>So, here Content Compression Resistance Priority comes into play. If we go into the size inspector tabs of both labels, we will see that both labels’ horizontal content compression resistance priority is set to 750 (the default value). This means both labels have similar content compression resistance priority. One label should have a higher priority constraint than the other to break the tie.</p><p>Now, let us change the content compression resistance priority of the Yellow label to 751 and see what happens next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*I6kJIIvjEwZMNzTbENCN8Q.gif" /><figcaption>Setting Content Compression Resistance Priority of Yellow Label to 751</figcaption></figure><p>We see that the Auto Layout error has been resolved and the Green label has compressed, and the Yellow label stays to its intrinsic content size because now it has higher content compression resistance priority than the Green label. As mentioned earlier, the one view with higher horizontal content compression resistance priority will not shrink beyond its intrinsic content size.</p><p>Now try changing the content compression resistance priority of the Green label to 752 and see what happens next 🤔.</p><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8f0d6cd0ad7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[iOS] — Content Hugging Priority]]></title>
            <link>https://swarandeepsinghsran.medium.com/ios-content-hugging-priority-3aa67bd1e459?source=rss-56554a6a0caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aa67bd1e459</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Swarandeep Singh Sran]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 11:40:31 GMT</pubDate>
            <atom:updated>2023-01-21T21:42:51.183Z</atom:updated>
            <content:encoded><![CDATA[<h3>[iOS] — Content Hugging Priority</h3><p>Before going to Content Hugging Priority, it is essential to understand a term called <strong>intrinsic content size.</strong></p><p>So, what the is intrinsic content size? It is simple. It refers to the amount of space the view needs for its content to appear in an ideal state. That means how big a view should be based on what it displays.<br><strong>Example</strong>: For <strong>UILabel, </strong>the intrinsic content size is the size of the text that it displays. The same goes for <strong>UIButton</strong>.</p><blockquote><strong>Content Hugging Priority: </strong>Sets the priority with which a view resists being made larger than its intrinsic size. — Apple docs (<a href="https://developer.apple.com/documentation/uikit/uiview/1622485-setcontenthuggingpriority">https://developer.apple.com/documentation/uikit/uiview/1622485-setcontenthuggingpriority</a>)</blockquote><p>The above statement means that the more the content hugging priority, the more it will resist to growing larger than its content intrinsic size. That is, the more the content hugging priority, the more the view will tend to <strong>hug</strong> its content and resist growing larger than the content intrinsic size. Always remember that priority is a relative term. So, when there is a deadlock between two views, one should have more content hugging priority than the other.</p><p>Let us understand this with an example. Note that I am using Xcode Version 14.0.1 and iPhone 14 Pro as the simulator for the following example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*1erP4Nu1R8JYyyDhF76NpQ.png" /><figcaption>Initial Setup</figcaption></figure><p>I have inserted two labels (Yellow label &amp; Green label) and made them vertically centre on the view controller. For the yellow label, I have given a leading constraint of 32 px from the safe area leading, and for the green label, I have given a trailing constraint of 32 from the safe area trailing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*ueTOlz64NJdWIxlJofpuTQ.png" /><figcaption>Constraints for Yellow Label</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*JLRwoevp5t3wdmh3QPUCDw.png" /><figcaption>Constraints for Green Label</figcaption></figure><p>Pretty Smooth? Let us do the confusing thing (confusing for the Auto Layout 😜). If you check, the current space between the Yellow label and the Green label is 142.67 px (maybe different in your case if you haven’t proceeded with the same configurations as me). Let us create a new constraint that makes the space between these two labels 50 px (i.e., less than the current space)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8NHoLcLiU4vFWwg0Rvai-Q.gif" /></figure><p>We will notice Auto Layout throws an error. If we look into the error, we will see that Auto Layout asks us to change the Content Hugging priority of any one label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*HYfiUXV8huOFVNyYuWgqCQ.png" /><figcaption>Auto Layout Error</figcaption></figure><p>Let us first run our application without going deep into the error to see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*r5OmfAx6qhkQ_OR5R3SeCw.png" /><figcaption>Output on the simulator. The Green Label get expanded</figcaption></figure><p>The Green label gets expanded to satisfy the constraint of 50 px space between both labels. Auto Layout needed clarification about which label(s) to grow to meet the 50 px constraint, hence throwing the initial error. At runtime, it randomly increased the width of the Green label to break the deadlock (it may be the Yellow label in your case).</p><p>So, here Content Hugging Priority comes into play. If we go into the size inspector tabs of both labels, we will see that both labels’ horizontal content hugging priority is set to 251 (the default value). This means both labels have similar content hugging priority. One label should have a higher priority constraint than the other to break the tie.</p><p>Now, let us change the content hugging priority of the Green label to 252 and see what happens next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EFGBFDe5hqyi5GOlICrTFg.gif" /><figcaption>Setting Content Hugging Priority of Green Label to 252</figcaption></figure><p>We see that the Auto Layout error has been resolved and the Yellow label has expanded, and the Green label hugs to its intrinsic content size because now it has higher content hugging priority than the Yellow label. As mentioned earlier, the one view with higher horizontal content hugging priority will not grow beyond its intrinsic content size.</p><p>Now try changing the content hugging priority of the Yellow label to 253 and see what happens next 🤔.</p><p><strong>If you found this article helpful, kindly share this story, follow me on medium and give applaud 👏. Thank You!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aa67bd1e459" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>