<?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 Rohit Sharma on Medium]]></title>
        <description><![CDATA[Stories by Rohit Sharma on Medium]]></description>
        <link>https://medium.com/@rohit236c?source=rss-e12301067d58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VGXUX-Y0mGDPxCB5wtI_Ig.jpeg</url>
            <title>Stories by Rohit Sharma on Medium</title>
            <link>https://medium.com/@rohit236c?source=rss-e12301067d58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:04:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohit236c/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[The Best Engineers Aren’t Faster Coders. They’re Better Debuggers.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@rohit236c/the-best-engineers-arent-faster-coders-they-re-better-debuggers-779f1f4ea05e?source=rss-e12301067d58------2"><img src="https://cdn-images-1.medium.com/max/1536/1*OqIe4QFBnJjJRMA10Iu46g.png" width="1536"></a></p><p class="medium-feed-snippet">After working across products like zomato, webex and Payzapp, one thing became very clear to me:</p><p class="medium-feed-link"><a href="https://medium.com/@rohit236c/the-best-engineers-arent-faster-coders-they-re-better-debuggers-779f1f4ea05e?source=rss-e12301067d58------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rohit236c/the-best-engineers-arent-faster-coders-they-re-better-debuggers-779f1f4ea05e?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/779f1f4ea05e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Sun, 10 May 2026 13:45:53 GMT</pubDate>
            <atom:updated>2026-05-10T13:45:53.376Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[BLoC in Flutter vs Combine in Swift: A Beginner’s Guide]]></title>
            <link>https://medium.com/@rohit236c/bloc-in-flutter-vs-combine-in-swift-a-beginners-guide-0b848907e796?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b848907e796</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 06:44:54 GMT</pubDate>
            <atom:updated>2025-07-27T06:55:50.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T35gt3oZq4I6raeUtEFRtQ.png" /></figure><p>When developing mobile applications, it’s important to manage how your app reacts to changes in data. Two popular methods for this are Bloc in Flutter and Combine in Swift. This guide explains both clearly for beginners, providing examples and code snippets to get you started.</p><h3>What is BLoC in Flutter?</h3><p>BLoC stands for <strong>Business Logic Component</strong>. It helps separate your application’s business logic (like fetching data or processing user inputs) from the user interface (what the user sees).</p><h4>Core Components:</h4><ul><li><strong>Events</strong>: Represent actions or inputs from the user, such as pressing a button or entering text.</li><li><strong>States</strong>: Describe the current situation or UI of the application, such as loading, success, or error.</li><li><strong>Bloc</strong>: Acts as a middleman, processing events and emitting new states accordingly.</li></ul><h4>Practical Example in Flutter</h4><p>Here’s a straightforward example of a counter app using Bloc:</p><pre>// Defining events<br>abstract class CounterEvent {}<br>class Increment extends CounterEvent {}<br>class Decrement extends CounterEvent {}</pre><pre>// Defining state<br>class CounterState {<br>  final int count;<br>  CounterState(this.count);<br>}<br>// Bloc Logic<br>import &#39;package:bloc/bloc.dart&#39;;<br>class CounterBloc extends Bloc&lt;CounterEvent, CounterState&gt; {<br>  CounterBloc() : super(CounterState(0)) {<br>    on&lt;Increment&gt;((event, emit) {<br>      emit(CounterState(state.count + 1));<br>    });<br>    on&lt;Decrement&gt;((event, emit) {<br>      emit(CounterState(state.count - 1));<br>    });<br>  }<br>}</pre><p>In this example, whenever the increment or decrement event occurs (e.g., pressing buttons), the Bloc processes these events and updates the state, which the UI can display.</p><h3>What is Combine in Swift?</h3><p>Combine is Apple’s reactive programming framework, designed to handle asynchronous events in Swift applications. It simplifies the management of data streams, helping your app respond smoothly to data changes.</p><h4>Core Components:</h4><ul><li><strong>Publisher</strong>: Emits values or events over time.</li><li><strong>Subscriber</strong>: Receives and responds to the values emitted by the publisher.</li><li><strong>Operators</strong>: Allow you to transform, filter, or manipulate the data flowing through streams.</li></ul><h4>Practical Example in Swift</h4><p>Here’s how you could build the same counter app using Combine:</p><pre>// Using Combine in a ViewController<br>import UIKit<br>import Combine<br><br>class Counter {<br>    var count = CurrentValueSubject&lt;Int, Never&gt;(0)<br>    func increment() {<br>        count.send(count.value + 1)<br>    }<br>    func decrement() {<br>        count.send(count.value - 1)<br>    }<br>}<br><br><br>class ViewController: UIViewController {<br>    let counter = Counter()<br>    var cancellable: AnyCancellable?<br>    @IBOutlet weak var countLabel: UILabel!<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Subscribe to changes from the counter<br>        cancellable = counter.count.sink { [weak self] value in<br>            self?.countLabel.text = &quot;Count: \(value)&quot;<br>        }<br>    }<br><br>    @IBAction func incrementTapped(_ sender: Any) {<br>        counter.increment()<br>    }<br><br>    @IBAction func decrementTapped(_ sender: Any) {<br>        counter.decrement()<br>    }<br>}</pre><p>In this Swift example, whenever the increment or decrement methods are called (e.g., when buttons are tapped), the CurrentValueSubject publishes the updated count, which the UI listens to and displays.</p><h3>Common Use Cases Explained</h3><p><strong>Form Validation:</strong></p><ul><li><em>Bloc:</em> Managing user input events and updating UI with validation states.</li><li><em>Combine:</em> Validating user inputs with real-time feedback using data stream filters.</li></ul><h3>Conclusion</h3><p>Both Bloc in Flutter and Combine in Swift are powerful tools to handle data changes effectively. Bloc is ideal for cross-platform development, whereas Combine integrates smoothly within Apple’s ecosystem. With a bit of practice, both can help you build responsive and maintainable apps efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b848907e796" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ What’s New in Swift 6.2 (WWDC 2025)]]></title>
            <link>https://medium.com/@rohit236c/whats-new-in-swift-6-2-wwdc-2025-1d6a1b3ddfc0?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6a1b3ddfc0</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 04:33:13 GMT</pubDate>
            <atom:updated>2025-07-03T04:33:13.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qljpjrG0RWyqHch9kWC1A.png" /></figure><p>Swift 6.2 was introduced at WWDC 2025 with significant improvements focused on performance, safety, and developer ergonomics. Let’s explore <strong>the new features</strong>, with code samples to help you visualise them.</p><h3>✨ 1️⃣ InlineArray: High-Performance, Fixed-Size Arrays</h3><p>Swift 6.2 introduces InlineArray&lt;N, Element&gt;, which lets you define arrays with <strong>fixed compile-time sizes</strong>. These arrays store their data <em>inline</em> (on the stack), cutting out heap allocations and reference counting.</p><p>✅ <strong>Benefits</strong>:</p><ul><li>Predictable memory usage.</li><li>Faster access (20–30% faster in benchmarks for tight loops).</li><li>Safer by design (no dynamic resizing).</li></ul><p><strong>Example Usage</strong>:</p><pre>var rgb: InlineArray&lt;3, UInt8&gt; = [255, 128, 64]<br>print(rgb[0]) // 255</pre><p>⚠️ You <em>can’t</em> append or remove elements. It’s designed for scenarios like:</p><ul><li>Image processing (fixed pixel data)</li><li>DSP buffers</li></ul><h3>⚡ 2️⃣ Concurrency Refinements: More Predictable Isolation</h3><p>Concurrency in Swift 6 has always aimed for safety, but sometimes felt hard to adopt. Swift 6.2 smooths the learning curve with new isolation defaults and explicit controls.</p><h3>a) nonisolated(nonsending) by Default</h3><p>Async methods on actors inherit the actor’s context unless you specify otherwise, reducing surprises and race conditions.</p><pre>actor DataManager {<br>    nonisolated func info() -&gt; String { &quot;Actor-safe info&quot; }<br>}</pre><h3>b) The @concurrent Attribute</h3><p>Want an async function to <em>truly</em> run in another context? Mark it explicitly:</p><pre>@MainActor class API {<br>    @concurrent nonisolated func fetchData() async throws -&gt; Data { ... }<br>}</pre><p>It’s now crystal clear what runs where.</p><h3>c) defaultIsolation(MainActor.self)</h3><p>A new <strong>package-level</strong> setting makes your entire module @MainActor By default, perfect for UI apps.</p><pre>// Package.swift<br>.enableFeature(&quot;DefaultIsolation(MainActor.self)&quot;)</pre><h3>🧪 3️⃣ Enhanced Interoperability</h3><p>Swift 6.2 also makes it easier to work across languages and platforms:</p><p>✅ <strong>C/C++ Interop</strong>:</p><ul><li>Even simpler bindings.</li><li>Automatic generation for many headers.</li></ul><p>✅ <strong>Java Interop</strong>:</p><ul><li>The new <strong>Swift-Java</strong> project bridges Swift to Java ecosystems.</li><li>Build cross-platform mobile libraries that can integrate with Android.</li></ul><h3>🎯 Why Upgrade to Swift 6.2?</h3><p>Swift 6.2 isn’t just a patch — it’s a meaningful evolution:</p><p>✅ Safer concurrency defaults<br> ✅ Lower-level performance control<br> ✅ Cross-language integration<br> ✅ Simpler server workflows</p><p>For iOS, macOS, visionOS, or server-side developers, it’s a compelling step forward.</p><blockquote><em>Have questions or want to see deeper code samples? Drop a comment below or connect with me here on Medium!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6a1b3ddfc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Universal Links in iOS]]></title>
            <link>https://medium.com/@rohit236c/universal-links-in-ios-22a60b71c89c?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/22a60b71c89c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[deeplink]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 09:03:13 GMT</pubDate>
            <atom:updated>2025-01-14T09:03:13.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZrL38VN5aphV9lLCmebqQ.jpeg" /><figcaption>Universal link in iOS</figcaption></figure><h3>Overview:</h3><p>Universal Links are a mechanism in iOS that allows apps to open specific content directly when a user taps on a link, rather than routing the link through a browser like Safari. They provide a seamless experience by connecting web URLs with content in the app.</p><h4>Key Features of Universal Links</h4><ol><li><strong>Seamless User Experience</strong></li></ol><ul><li>Links open directly in the app if it’s installed.</li><li>If the app isn’t installed, the link opens in Safari.</li></ul><p>2. <strong>Single URL for All Platforms</strong></p><ul><li>Universal Links use the same URL for both the web and the app, eliminating the need for separate deep link schemes.</li><li>This ensures consistent behaviour across devices and platforms.</li></ul><p>How to setup <strong>Universal</strong> links in iOS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*i1rDn9xeehGMeIHtEUaExA.png" /><figcaption>Universal link in iOS</figcaption></figure><h3>1. Configure Your Website</h3><p><strong>a. Create an Apple App Site Association (AASA) File</strong></p><ul><li>Create a file named apple-app-site-association (no file extension).</li><li>Add the following JSON structure to it:</li></ul><pre>{<br>  &quot;applinks&quot;: {<br>    &quot;apps&quot;: [],<br>    &quot;details&quot;: [<br>      {<br>        &quot;appID&quot;: &quot;&lt;TeamID&gt;.&lt;BundleIdentifier&gt;&quot;,<br>        &quot;paths&quot;: [&quot;*&quot;]<br>      }<br>    ]<br>  }<br>}</pre><ul><li>Replace &lt;TeamID&gt; with your <strong>Apple Developer Team ID</strong>.</li><li>Replace &lt;BundleIdentifier&gt; with your app&#39;s <strong>bundle identifier</strong>.</li></ul><p>Example:</p><pre>{<br>  &quot;applinks&quot;: {<br>    &quot;apps&quot;: [],<br>    &quot;details&quot;: [<br>      {<br>        &quot;appID&quot;: &quot;ABCDE12345.com.example.myapp&quot;,<br>        &quot;paths&quot;: &quot;*&quot;<br>      }<br>    ]<br>  }<br>}</pre><p><strong>b. Host the AASA File</strong></p><ol><li>Place the apple-app-site-association file at the root of your domain (https://yourdomain.com/apple-app-site-association).</li><li>Ensure the file is served over <strong>HTTPS</strong> with the Content-Type header set to application/json.</li></ol><h3>2. Configure the Apple Developer Portal</h3><ol><li>Log in to your <a href="https://developer.apple.com/">Apple Developer Account</a>.</li><li>Go to <strong>Certificates, Identifiers &amp; Profiles</strong> &gt; <strong>Identifiers</strong>.</li><li>Select your app and ensure the <strong>Associated Domains</strong> entitlement is enabled.</li><li>Save the changes.</li></ol><h3>3. Set Up Your App</h3><h4>a. Enable Associated Domains</h4><ol><li>Go to your <strong>Xcode project</strong> settings.</li><li>Select your app’s <strong>target</strong> and navigate to the <strong>Signing &amp; Capabilities</strong> tab.</li><li>Click the <strong>+ Capability</strong> button and add <strong>Associated Domains</strong>.</li><li>Add your domain with the applinks: prefix in the format:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGMGchWVZebPghVbvQq-xg.png" /><figcaption>Signing &amp; Capabilities in iOS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7wL3v1jmoTcjYnCHugFJA.png" /><figcaption>Adding associated domain in capability</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MI56YzFBDv9zX4uNIjEvA.png" /><figcaption>Associated Domain in URL</figcaption></figure><h3>4. Handle Universal Links in Your App</h3><h4>a. Implement the application(_:continue:restorationHandler:) Method</h4><p>In your AppDelegate or SceneDelegate, handle the incoming Universal Links:</p><ul><li><strong>AppDelegate.swift</strong>:</li></ul><pre>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -&gt; Void) -&gt; Bool {<br>    guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,<br>          let url = userActivity.webpageURL else {<br>        return false<br>    }<br>    <br>    // Handle the URL<br>    print(&quot;Universal Link URL: \(url)&quot;)<br>    return true<br>}</pre><p><strong>SceneDelegate.swift</strong> (if using scenes):</p><pre>func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {<br>    guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,<br>          let url = userActivity.webpageURL else {<br>        return<br>    }<br>    <br>    // Handle the URL<br>    print(&quot;Universal Link URL: \(url)&quot;)<br>}</pre><h4>b. Test in Device</h4><ol><li>Build and run the app on a device.</li><li>Open a link that matches the AASA file configuration in Safari.</li><li>Verify that the app launches and handles the URL.</li></ol><h3>5. Verify The Setup</h3><h4>a. Test with Terminal</h4><p>Run the following curl command to ensure the AASA file is accessible:</p><pre>curl -I https://yourdomain.com/apple-app-site-association</pre><p>Verify the response status is 200 OK and the Content-Type is application/json.</p><p><strong>References</strong>:</p><ul><li><a href="https://developer.apple.com/documentation/xcode/supporting-associated-domains">Supporting associated domains | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app">Supporting universal links in your app | Apple Developer Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22a60b71c89c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Class Vs Struct in Swift]]></title>
            <link>https://medium.com/@rohit236c/class-vs-struct-in-swift-39c596155057?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/39c596155057</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 04:53:31 GMT</pubDate>
            <atom:updated>2023-04-02T04:53:31.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*vRPGjZmb73ZeJ9Z6nXW7Gw.jpeg" /><figcaption>Class vs struct in swift</figcaption></figure><p>In Swift, both class and struct are used to define custom data types. However, there are some key differences between them that you should be aware of:</p><ol><li><strong>Inheritance</strong>: A class can inherit properties and methods from another class, but a struct cannot.</li><li><strong>Reference vs Value Type</strong>: A class is a reference type, which means that when you assign a class instance to a variable or constant, you&#39;re actually assigning a reference to that instance, not a copy of it. In contrast, a struct is a value type, which means that when you assign a struct instance to a variable or constant, you&#39;re actually creating a copy of that instance.</li><li><strong>Mutability</strong>: You can use the let keyword to make a class instance immutable, but you cannot do the same with a struct instance.</li><li><strong>Initialisation</strong>: A class requires an initialiser to be defined, but a struct does not. A struct automatically generates a member-wise initialiser that takes a parameter for each property in the struct.</li><li><strong>Default Member-wise Initialisation</strong>: Swift provides a default member-wise initialiser for all structs, but not for classes.</li></ol><h3>Performance Difference</h3><p>In terms of <strong>performance</strong>, the difference between class and struct in Swift can vary depending on the specific use case. Here are some general considerations:</p><ol><li><strong>Memory allocation</strong>: As mentioned earlier, a struct is a value type, which means that when you create an instance of it, it&#39;s stored directly in memory. In contrast, a class is a reference type, which means that when you create an instance of it, only a reference to that instance is stored in memory. This means that creating and copying a struct instance can be faster than creating and copying a class instance, especially for small data types.</li><li><strong>Reference counting</strong>: Because a class is a reference type, it requires reference counting to manage its memory. This means that each time a new reference to a class instance is created, the reference count is incremented, and each time a reference is destroyed, the reference count is decremented. If the reference count reaches zero, the instance is deallocated. This process can introduce some overhead, especially if you have a large number of class instances with many references.</li><li><strong>Inlining</strong>: The Swift compiler can optimize code by inlining functions and methods. Inlining can improve performance by reducing function call overhead. However, the compiler may be less likely to inline functions and methods that are defined in a class because they can be overridden by subclasses.</li></ol><p>Overall, the performance difference between class and struct may not be significant for many applications. However, if you have specific performance requirements or are working with large data sets, you may want to consider using a struct instead of a class.</p><p>Let’s get into an example:</p><pre>// Example 1: Class<br>class Person {<br>    var name: String<br>    var age: Int<br>    <br>    init(name: String, age: Int) {<br>        self.name = name<br>        self.age = age<br>    }<br>    <br>    func sayHello() {<br>        print(&quot;Hello, my name is \(name) and I&#39;m \(age) years old.&quot;)<br>    }<br>}<br><br>// Create an instance of the Person class<br>let john = Person(name: &quot;John&quot;, age: 30)<br><br>// Call the sayHello method<br>john.sayHello()<br><br>// Example 2: Struct<br>struct Point {<br>    var x: Double<br>    var y: Double<br>}<br><br>// Create an instance of the Point struct<br>var point = Point(x: 0.0, y: 0.0)<br><br>// Modify the x and y properties<br>point.x = 1.0<br>point.y = 2.0</pre><p>In Example 1, we define a class called Person with two properties (name and age) and a method (sayHello). We create an instance of the Person class using the init method, and then call the sayHello method on that instance. Notice that we can modify the properties of the Person instance using dot notation (e.g., john.name = &quot;Bob&quot;).</p><p>In Example 2, we define a struct called Point with two properties (x and y). We create an instance of the Point struct using the member-wise initializer, and then modify the x and y properties of that instance. Notice that we can also modify the properties of the Point instance using dot notation (e.g., point.x = 3.0).</p><p>Overall, the key differences between class and struct are their mutability, reference vs value semantics, and inheritance. In general, you should use a class when you need reference semantics or inheritance, and use a struct when you need value semantics and simple data modeling.</p><p>Thanks for your time reading this article.</p><p>Do checkout my LinkedIn profile: <a href="https://www.linkedin.com/in/rohit-sharma-7ab904187/">https://www.linkedin.com/in/rohit-sharma-7ab904187/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39c596155057" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit-Test: XCTUnwrap Unique way of Testing in iOS]]></title>
            <link>https://medium.com/@rohit236c/unit-test-xctunwrap-unique-way-of-testing-in-ios-6d0897ae0ef0?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d0897ae0ef0</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 06:00:38 GMT</pubDate>
            <atom:updated>2023-01-26T06:00:38.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdZB8hkVWdTv9YHQYH79YQ.png" /><figcaption>Unit-test</figcaption></figure><p>Do you know the method to unwrap an optional in XCTest? Initially, I used <strong>guard</strong> or <strong>if let</strong> to unwrap the optional and test if this value is present.</p><p>This is how I used to test for optionals before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*173j5ofY5sG6ayMGhJekYA.png" /></figure><p>Apple has provided an excellent Method for handling this and making code much cleaner. <strong>XCTUnwrap </strong>is a method unwrap the optionals and throws an error when you have a nil value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oMUJAcyKVUp22h_IBOjCQ.png" /><figcaption>XCTUnwrap: Unique way of unwrapping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u34WrRJ3oqeg78NXXSVVsw.png" /><figcaption>XCTUnwrap: Passing Test</figcaption></figure><p>This makes the code much cleaner and easier to understand. The code gets quite cluttered if the test case is very big and we use guard/if let for unwrapping. <strong>XCTUnwrap</strong> makes the test quite clean and readable and helps us to avoid force unwrapping.</p><p>Thanks for reading this article. Here’s the GitHub link: l<a href="https://github.com/rohshar6/Design-Patterns-in-Swift">ink</a>.</p><p>You can reach out to me on my <a href="https://www.linkedin.com/in/rohit-sharma-7ab904187/">LinkedIn</a> or <a href="https://twitter.com/Rohitsh31769664">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d0897ae0ef0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Principle in Swift (PART 1)]]></title>
            <link>https://medium.com/@rohit236c/design-principle-in-swift-part-1-a54a7e64b292?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54a7e64b292</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 18:15:37 GMT</pubDate>
            <atom:updated>2023-01-22T18:15:37.247Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Principle in Swift(PART 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*AOzeP3iVWba5jd5SSj963w.png" /><figcaption>SOLID Design Principle</figcaption></figure><p>Hi Everyone, I plan to start writing a series on Design Patterns and principles this week. I will try to publish a few articles on design patterns and principles in iOS which will help people in expanding their knowledge and learn how to write scalable and good-quality code.</p><p>In this article, I will refer to the basics of design <strong>SOLID Design Principle</strong> introduced by <a href="https://en.wikipedia.org/wiki/Robert_C._Martin">Robert C. Martin</a> (Uncle Bob).</p><h4>S — Single Responsibility Principle</h4><blockquote>A class should have one, and only one, reason to change.</blockquote><p><strong>Brief</strong>:</p><p>So, this principle says, one class should always have one reason to change. If a class is handling multiple responsibilities it violates the SRP.</p><p>Example:</p><p>Here, I have created a UserViewModel class that handles all the operations starting from fetching a user from a server and making a request.</p><p>Bad ❌:</p><pre>struct User {<br>    let id: UUID<br>    let email: String<br>}<br><br>class UserViewModel {<br>    // users cache<br>    private var users = [User]()<br><br>    // Fetching user from the server and parsing data<br>    public func fetchUser() {<br>        URLSession.shared.dataTask(with: URLRequest(url: URL(string: &quot;testUrl&quot;)!)) { [weak self] data, response, error in<br>            self?.handleData(data)<br>        }<br>    }<br>    <br>    private func handleData(_ data: Data?) {}<br>    <br>    // Returns the user after finding<br>    func getUser(_ id: UUID) -&gt; User? {<br>        return users.first { $0.id == id }<br>    }<br>    <br>    func createUser() {<br>        // create user obj and save to db<br>    }<br><br>    func deleteUser() {<br>        // delete user obj from db<br>    }<br><br>    func updateUser() {<br>        // update user in db<br>    }<br>}</pre><p>As you can see from the above example, UserViewModel is handling too much logic inside itself. It will have to change for various reasons, For Example:</p><ol><li>The endpoint server is changed and will now point to another URL.</li><li>What if we want to get users based on email Id and not UUID?</li><li>What if we want to save the User to some NO-SQL database?</li></ol><p>All these reasons can lead to changes to the <strong>UserViewModel</strong> class which violates <strong>SRP</strong>.</p><p>Solution:</p><p>Good ✅:</p><pre>struct Query {}<br><br>protocol UserRequestHandlerProtocol {<br>    func fetchUser()<br>}<br><br>protocol DataBaseHandlerProtocol {<br>    func createUser()<br>    func deleteUser()<br>    func updateUser()<br>    func getUser(_ query: Query) -&gt; User<br>}<br><br>class UserViewModel {<br>    private let userRequestHandler: UserRequestHandlerProtocol<br>    private let dbHandler: DataBaseHandlerProtocol<br><br>    init(userRequestHandler: UserRequestHandlerProtocol, dbHandler: DataBaseHandlerProtocol) {<br>        self.userRequestHandler = userRequestHandler<br>        self.dbHandler = dbHandler<br>    }<br><br>    // Delegates the task to userRequestHandler to process the request and fetchUser<br>    func fetchUser() {<br>        userRequestHandler.fetchUser()<br>    }<br>    <br>    // Delegates the task to dbHandler to get the user from the db<br>    func getUser(_ query: Query) -&gt; User {<br>        return dbHandler.getUser(query)<br>    }<br>    <br>    func createUser() {<br>        dbHandler.createUser()<br>    }<br><br>    func deleteUser() {<br>        dbHandler.deleteUser()<br>    }<br><br>    func updateUser() {<br>        dbHandler.updateUser()<br>    }<br>}</pre><p>What I did is break down the functionality into independent classes/protocols and UserViewModel doesn’t need to depend on the implementation details.</p><p>Tomorrow even if the endpoint changes, We don’t need to change anything in UserViewModel.</p><h4>O — Open/Closed Principle</h4><blockquote>Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</blockquote><p><strong>Brief:</strong></p><p>This principle means we can extend the class for adding new functionality to it without modifying the old functions, providing better stability and maintainability of the code-base.</p><p><strong>Code Snippet:</strong></p><p>Here, We are calculating the area of the rectangle.</p><pre>struct Rectangle {<br>    let length: Double<br>    let breadth: Double<br>}<br><br>class Area {<br>    func getArea(_ rectangle: Rectangle) -&gt; Double {<br>        return rectangle.length * rectangle.breadth<br>    }<br>}<br><br>let area = Area()<br>print(area.getArea(Rectangle(length: 10, breadth: 10)))</pre><p>Now, if we want to calculate the area of the square, we have to modify this class, let’s get into the code:</p><p>Bad ❌:</p><pre>struct Square {<br>    let side: Double<br>}<br><br><br>class Area {<br>    func getArea(_ square: Square) -&gt; Double {<br>        return square.side * square.side<br>    }<br>}</pre><p>This violates the open-closed principle as mentioned above since we had to modify the function definition for the new requirement.</p><p>Now, let’s try to follow the Open-closed principle and try to get to a solution:</p><p>Good ✅:</p><pre>/// We Created a interface/Protocol of the Area, that can be extended easily<br>/// and modified by each class separately. <br>/// This allows us to follow Open-closed Principle.<br>protocol Area {<br>    func getArea() -&gt; Double<br>}<br><br>struct Rectangle: Area {<br>    let length: Double<br>    let breadth: Double<br>    <br>    func getArea() -&gt; Double {<br>        return length * breadth<br>    }<br>}<br><br>struct Square: Area {<br>    let side: Double<br>    <br>    func getArea() -&gt; Double {<br>        return side * side<br>    }<br>}<br><br>let rectangleArea = Rectangle(length: 100, breadth: 80)<br>print(rectangleArea.getArea())<br>let squareArea = Square(side: 10)<br>print(squareArea.getArea())</pre><p>What we did is create a protocol area that can be easily Extended and used by every shape to calculate the area. This way, we don’t have to modify anything to the area protocol and we can easily calculate the area of any shape.</p><h4>L — Liskov Substitution Principle</h4><blockquote>Let Φ(x) be a property provable about objects x of type T. Then Φ(y) should be true for objects y of type S where S is a subtype of T.</blockquote><p><strong>Brief:</strong></p><p>What this principle states is: A superclass object should be replaceable by any of its subclass objects without breaking the functionality.</p><p>So, the expectation is that derived classes should never do less than their base class.</p><p><strong>Code Snippet:</strong></p><p>Bad Example ❌:</p><pre>class Shape {<br>    func getArea() -&gt; Double {<br>        return .zero<br>    }<br>}<br><br>class Square: Shape {<br>    override func getArea() -&gt; Double {<br>        fatalError(&quot;Can&#39;t find area.&quot;) // ❌ This won&#39;t allow us to use Square<br>                                       // as the Shape which breaks Liskov Principle.<br>    }<br>}<br><br>class Rectangle: Shape {} ✅</pre><p>Solution:</p><p>Good Example ✅:</p><pre>class Shape {<br>    func getArea() -&gt; Double {<br>        return .zero<br>    }<br>}<br><br>class Square: Shape {<br>    var side: Double = .zero<br>    override func getArea() -&gt; Double {<br>        return side * side ✅<br>    }<br>}<br><br>class Rectangle: Shape {} ✅</pre><h4>I — Interface Segregation Principle</h4><blockquote>Clients should not be forced to depend upon interfaces that they do not use.</blockquote><p><strong>Brief:</strong></p><p>Usually, we all try to keep interfaces as small as possible. But with a big code base, the interface tends to become big and noisy sometimes. We should avoid making classes use interfaces that bring side effects or noise. The below example shows how we shouldn’t use this:</p><p><strong>Code Snippet:</strong></p><p>Bad ❌:</p><pre>protocol Sound {<br>    func quack()<br>    func bark()<br>}<br><br>class Dog: Sound {<br>    func quack() {<br>        fatalError(&quot;Dog doesn&#39;t quack&quot;) // ❌ We shouldn&#39;t do this<br>    }<br>    <br>    func bark() {<br>        print(&quot;bark&quot;)<br>    }<br>}<br><br>class Duck: Sound {<br>    func quack() {<br>        print(&quot;quack&quot;)<br>    }<br>    <br>    func bark() {<br>        fatalError(&quot;Duck doesn&#39;t bark&quot;) // ❌ We shouldn&#39;t do this<br>    }<br>}</pre><p>Good ✅:</p><p>We created two interfaces independent for each animal sound and this will help in reducing unwanted implementation of methods.</p><pre>protocol DogSound {<br>    func bark()<br>}<br><br>protocol DuckSound {<br>    func quack()<br>}<br><br>class Dog: DogSound {<br>    func bark() {<br>        print(&quot;bark&quot;)<br>    }<br>}<br><br>class Duck: DuckSound {<br>    func quack() {<br>        print(&quot;quack&quot;)<br>    }<br>}</pre><h4>D — Dependency Inversion</h4><blockquote>High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.</blockquote><p><strong>Brief:</strong></p><p>If the code is following the Open-closed principle and the Liskov principle, it will also follow the Dependency inversion Principle. Let’s see a bad example first:</p><p><strong>Code Snippet:</strong></p><p>Bad ❌:</p><p>The issue with this approach is User is dependent upon the concrete instance of SqlDatabase, what if the user wants to use MongoDB or SqlLiteDB instance? This will break the Open-closed principle as well.</p><pre>class SqlDataBase {<br>    func create(_ values: Any) {}<br>    func delete(_ query: Any) {}<br>    func update(_ query: Any) {}<br>    func get() -&gt; Any? {}<br>}<br><br>struct UserData {<br>    var id: String = &quot;&quot;<br>    var email: String = &quot;&quot;<br>}<br><br>class User {<br>    let db: SqlDataBase<br>    init(datebase: SqlDataBase) {<br>        self.db = datebase<br>    }<br>    <br>    func getUser() {<br>        print(db.get())<br>    }<br>    <br>    func deleteUser() {<br>        let user = UserData(id: &quot;1&quot;, email: &quot;test@mail.com&quot;)<br>        print(db.create(user))<br>    }<br>}</pre><p>Good ✅:</p><p>Now, we have created an interface for the <strong>Database, </strong>which can easily help us to add new types of <strong>Database</strong> into our User class which will help in easily extending User. User doesn’t depend upon concrete class but rather on interfaces.</p><pre>struct UserData {<br>    var id: String = &quot;&quot;<br>    var email: String = &quot;&quot;<br>}<br><br>protocol DataBase {<br>    func create(_ values: Any)<br>    func delete(_ query: Any)<br>    func update(_ query: Any)<br>    func get() -&gt; Any?<br>}<br><br>class MongoDBInstance: DataBase {<br>    func create(_ values: Any) {}<br>    func delete(_ query: Any) {}<br>    func update(_ query: Any) {}<br>    func get() -&gt; Any? {<br>        return nil<br>    }<br>}<br><br>class SqlDBInstance: DataBase {<br>    func create(_ values: Any) {}<br>    func delete(_ query: Any) {}<br>    func update(_ query: Any) {}<br>    func get() -&gt; Any? {<br>        return nil<br>    }<br>}<br><br><br>class User {<br>    let db: DataBase<br>    init(datebase: DataBase) {<br>        self.db = datebase<br>    }<br>    <br>    func getUser() {<br>        print(db.get())<br>    }<br>    <br>    func deleteUser() {<br>        let user = UserData(id: &quot;1&quot;, email: &quot;test@mail.com&quot;)<br>        print(db.create(user))<br>    }<br>}</pre><p>That is all for SOLID Design Principle. If you have any feedback, do reach out to me on my <a href="https://www.linkedin.com/in/rohit-sharma-7ab904187/">LinkedIn</a>.</p><p>Thanks for reading this article. Here’s the GitHub link: l<a href="https://github.com/rohshar6/Design-Patterns-in-Swift">ink</a>.</p><p>You can reach out to me on my <a href="https://www.linkedin.com/in/rohit-sharma-7ab904187/">LinkedIn</a>.</p><p>References:</p><ol><li><a href="https://www.geeksforgeeks.org/open-closed-principle-in-java-with-examples/">https://www.geeksforgeeks.org/open-closed-principle-in-java-with-examples/</a></li><li><a href="https://stackify.com/solid-design-liskov-substitution-principle/">https://stackify.com/solid-design-liskov-substitution-principle/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54a7e64b292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Life Lessons of my Life]]></title>
            <link>https://medium.com/@rohit236c/top-10-life-lessons-of-my-life-3213c8eeed08?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/3213c8eeed08</guid>
            <category><![CDATA[lessons-learned]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[lifestyle]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 12:57:13 GMT</pubDate>
            <atom:updated>2022-12-18T12:58:59.736Z</atom:updated>
            <content:encoded><![CDATA[<p>I might not be that experienced in my life. However, just wanted to share my raw views on life and I hope these lessons will help someone in the future, or at least me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*t9g6g9VVwRnAaOq2pT3cMg.jpeg" /><figcaption>Life Lessons</figcaption></figure><h3>#1 Never Underestimate anyone in your life</h3><p>I have made this mistake many times in my life. You should never ever underestimate anyone in your life. People you might believe aren’t that great, may turn out to be the greatest of all. Always try to learn something new from everyone. Try to see the best in them.</p><h3><strong>#2 Be Kinds to others</strong></h3><p>People have a lot going on in their life. We never know what the other person is going through in their life. Try to be kind to them and always help each other.</p><h3>#3 Value your friends and family</h3><p>I have realized life isn’t all about money or luxuries. It’s about the relations that we have created in our lifelong journey and how much we cherish our own people.</p><h3>#4 Be A Good Listener</h3><p>For years, I have assumed I was a good listener, but now I believe I haven’t been listening to people properly. Listening doesn’t mean waiting for another person to complete their conversation and then you can start talking. It means you understand and be in the other person’s shoes on what they are actually trying to convey. This helps a lot to great bonds for the future.</p><h3><strong>#5 Never Stop Learning</strong></h3><p>Learning is a lifelong journey. With my little experience in life, I have seen people twice my age still learning and exploring, and doing great in life. It not only helps you gain great knowledge but also helps you be humble and kind.</p><h3>#6 Always have some goals in your life</h3><p>Having Goals and aspirations takes you miles away in life. Goals help you stay motivated in life and help you move forward in life.</p><h3>#7 Learn to slow down once in a while &amp; take a break</h3><p>Taking a break in life helps you to slow down and analyze your growth and your experience so far. It helps you to improve and focus on yourself again rather than just your work or your commitments. Taking a break clears the mind and helps us in long run.</p><h3>#8 Never Compare yourself to anyone</h3><p>Everyone is on their own journey in life. Some people become a millionaire at the age of 17, some get their first job offer at 30. We shouldn’t compare our life journey with anyone and keep exploring our path in our life.</p><h3>#9 Never judge anyone in your life</h3><p>Sometimes, we are quick to judge people because they might have been rude to us or they don’t behave the way we expect them to behave. They have their own story and their journey. We should always be empathetic towards others, keeping us open-minded always.</p><h3>#10 Be In the Present and Enjoy Every moment in Life</h3><p>We tend to live in either past or in the future. One thing I have learned is to be in present and enjoy every moment in life. It changes the way you perceive the world and helps you enjoy it to the fullest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3213c8eeed08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory Design Pattern In Swift]]></title>
            <link>https://medium.com/@rohit236c/factory-design-pattern-in-swift-36599fe4fce1?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/36599fe4fce1</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Wed, 01 Jun 2022 18:46:20 GMT</pubDate>
            <atom:updated>2022-06-01T18:46:20.050Z</atom:updated>
            <content:encoded><![CDATA[<p>Every programmer once in their lifetime must have come across this issue.</p><p>It’s really difficult to test your code when it is coupled very <strong>tightly</strong>. During my last 1.5 years as iOS/macOS developer, i came across these issues multiple times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7P1TV_2D176W65PzKjI8hA.jpeg" /><figcaption>Too Tired of coupled code</figcaption></figure><p>The main issue that i came across was when one <strong>ViewController</strong> is calling another <strong>ViewController</strong> which is also calling another <strong>ViewController</strong>, making my unit-test more of a <strong>UITest</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*3HaDQFqwdKvuOxhIXfjqAg.jpeg" /><figcaption>Irritated of Long Build Test times</figcaption></figure><p>This leads to long testing time and also, making test flaky or really making it difficult to test code. So, starting with my journey with design pattern, i learned about this amazing design pattern known as <strong>Factory Design Pattern</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChjIj8eWRDDxbe9i0iDtEA.png" /><figcaption>Factory design pattern</figcaption></figure><p>What is <strong>Factory Design Pattern ?</strong></p><p>A Factory Pattern or Factory Method Pattern says that just <strong>define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate.</strong> In other words, subclasses are responsible to create the instance of the class.</p><p>So, how does this pattern helps us?</p><p>I as a junior developer, never used to worry about <strong>initialisation</strong> of an object. I used to call the class <strong>constructor</strong>, keeping the object reference and <strong><em>boom</em></strong> my work is done😂. But now, comes the daunting part 😨, the testing of the <strong>ViewControllers</strong>.</p><p>To tackle the problem of initialisation, factory pattern comes into play. No more talk now, let’s jump right into code.</p><p>I’m going to take a small example mentioned in head first design pattern book. Let’s start!</p><p>So, we have a <strong>PizzaFactoryProtocol, </strong>this protocol contains a <strong>makePizzaViewController </strong>method, that returns us a pizzaViewController from a desired city. Right now, we have 2 (NewYork and Chicago).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vk9zN_B8buwhYcaljCoGPQ.png" /><figcaption>Design Diagram for abstract Factory</figcaption></figure><pre>/// This is an abstract factory that defines the interface that each concrete factory will implement.<br><strong>protocol</strong> PizzaFactoryProtocol: AnyObject {<br>     <strong>func</strong> makePizzaViewController() -&gt; NSViewController<br>}</pre><pre>/// Factory One: This will return NewYorkPizza<br><strong>class</strong> NewYorkPizzaFactory: PizzaFactoryProtocol {<br>      <strong>func</strong> makePizzaViewController() -&gt; NSViewController {<br>          <strong>return</strong> NewYorkPizzaViewController()<br>      }<br>}</pre><pre>/// Factory Two: This will return ChicagoChessPizza<br><strong>class</strong> ChicagoPizzaFactory: PizzaFactoryProtocol {<br>      <strong>func</strong> makePizzaViewController() -&gt; NSViewController {<br>          <strong>return</strong> ChicagoPizzaViewController()<br>      }<br>}</pre><p>The benefit of approach is,<strong> the creation of concrete objects inside your viewController has now been delegated to your factory</strong>. Using abstract factory, we will able to initialise different types of object.</p><pre><strong>class</strong> PizzaRestaurant  {<br>     <strong>private</strong> <strong>let</strong> pizzaFactory: PizzaFactoryProtocol<br>     <strong>init</strong>(pizzaFactory: PizzaFactoryProtocol) {<br>          <strong>self</strong>.pizzaFactory = pizzaFactory<br>     }</pre><pre><strong>   func</strong> orderPizza() {<br>     <strong>let</strong> pizzaViewController = <strong>pizzaFactory.makePizzaViewController()</strong><br>    // let&#39;s get something yummy<br>   }<br>}</pre><p>So, having protocol will help in injecting different type of pizza’s factory and creating different ViewController. This will also help in mocking of factories in unit-test cases which will help us to increase the code coverage and helps in writing good test cases.</p><pre><strong>class</strong> FakePizzaViewController: NSViewController {}</pre><pre><strong>class</strong> MockPizzaFactory: PizzaFactoryProtocol {<br>     <strong>func</strong> makePizzaViewController() -&gt; NSViewController {<br>          <strong>return</strong> FakePizzaViewController()<br>     }<br>}</pre><p>This way we can easily mockViewControllers without adding any concrete dependencies. Example, if show a <strong>Modal(NSApp.modal)</strong> in our UI, and we try to call the same method in our unit-test. It will block our whole unit-test and this might lead to regression/breaking of test. To tackle this, we can do something like this:</p><pre><strong>class</strong> ChicagoPizzaViewController: NSViewController {<br>     <strong>func</strong> showCostAlert() {<br>         NSApplication.runModal()<br>     }<br>}</pre><pre><strong>class</strong> FakePizzaViewController: ChicagoPizzaViewController {<br>     <strong>var</strong> didShowAlert = <strong>false<br>     <br>     func</strong> showAlert() {<br>         didShowAlert = <strong>true<br>     </strong>}<br>}</pre><p>This way, we never show any alert in our unit-test and also, make sure our correct function is getting called.</p><p>This pattern is one of the many ways to create the objects. As a beginner, i do believe it is much easier to understand and implement in the code-base.</p><p><strong>Conclusion</strong></p><p>This pattern has helped a lot of developers and has been used in multiple places. Special thanks to the authors of Head First Design Patterns for laying out such an easy and great examples for the design patterns. I will link the book url, if anyone wants to have a look. I hope you liked this article. Do reach out to me on LinkedIn or via mail.</p><p><a href="https://www.oreilly.com/library/view/head-first-design/9781492077992/">Head First Design pattern</a></p><p><a href="https://www.linkedin.com/in/rohit-sharma-7ab904187/">LinkedIn</a> , <a href="http://rohit236c@gmail.com/">Mail</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36599fe4fce1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Design Pattern in Swift]]></title>
            <link>https://medium.com/@rohit236c/singleton-design-pattern-in-swift-a5c537a7ea14?source=rss-e12301067d58------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c537a7ea14</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rohit Sharma]]></dc:creator>
            <pubDate>Mon, 16 May 2022 03:19:47 GMT</pubDate>
            <atom:updated>2022-05-16T03:19:47.001Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have worked with <strong>AppKit </strong>or <strong>UIKit</strong>, you must have came across <strong>Singleton design pattern</strong> many times.</p><p><em>Apple uses this design pattern at multiple places eg : </em><strong><em>DispatchQueue.main.async, UserDefaults.standard.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*OnVKn6_g5J_L8CinZbz0wA.jpeg" /><figcaption>Thinking 🤔</figcaption></figure><p>So, What does this <strong>singleton</strong> means ?</p><p>Singleton refers to the design pattern which doesn’t allow instantiation of class more than once. Let’s jump to the example to understand it better.</p><p><strong>Example One:</strong></p><pre><strong>class</strong> Calculator {</pre><pre><strong>    static</strong> <strong>let</strong> shared = Calculator()<br></pre><pre><strong>    func</strong> add(firstNumber: Int, secondNumber: Int) -&gt; Int {</pre><pre><strong>        return</strong> firstNumber + secondNumber</pre><pre>    }<br>}</pre><pre><strong>let</strong> result = Calculator.shared.add(firstNumber: 3, secondNumber: 5)</pre><pre>print(result)</pre><p>The keyword <strong>static let </strong>makes shared instance available to all classes and immutable. However, one thing that is missing is, we can still instantiate the class. So, how do we solve this ?</p><pre><strong>class</strong> Calculator {</pre><pre><strong>     static</strong> <strong>let</strong> shared = Calculator()<br></pre><pre><strong>     private</strong> <strong>init</strong>() {}</pre><pre><strong>     func</strong> add(firstNumber: Int, secondNumber: Int) -&gt; Int {</pre><pre><strong>         return</strong> firstNumber + secondNumber</pre><pre>     }</pre><pre>}</pre><p>By making initialiser <strong>private, </strong>we restrict instantiation of class and thus, other classes can only use the shared instance of this class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rc8FvolwIPZfI2DTfF9pCA.png" /><figcaption>Compiler issues on restriction of instantiation of Calculator</figcaption></figure><p><strong>When should we use this design Pattern ?</strong></p><p>This pattern is really powerful, however this should be handled with care and shouldn’t be used randomly.</p><p>Most use-cases, I have came across is related to networking or routing.</p><p>If you have ever worked with networking, you must have came across <strong>URLSession.shared </strong>which is also an example of singleton design pattern.</p><p>Whenever, we want to have common instance across all classes, we should use singleton design pattern.</p><h3><strong>Conclusion</strong></h3><p>This pattern is very easy to implement. However, this should be handled with care because the lifecycle of the class is difficult to manage. Try using this pattern only when it is required. Kudos to you, for reading this article.</p><p>This is my second article on medium. Hope you liked it. Thanks for reading❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c537a7ea14" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>