<?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 Karthik Shiva on Medium]]></title>
        <description><![CDATA[Stories by Karthik Shiva on Medium]]></description>
        <link>https://medium.com/@karthikshiva?source=rss-f7b9d03e641a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tqMAjxdaA4QNqmHxz16Dwg.jpeg</url>
            <title>Stories by Karthik Shiva on Medium</title>
            <link>https://medium.com/@karthikshiva?source=rss-f7b9d03e641a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:11:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karthikshiva/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[Writing Integration Tests for Your Network Layer Using URLProtocol]]></title>
            <link>https://medium.com/better-programming/writing-integration-tests-for-your-network-layer-using-urlprotocol-1de8d310193a?source=rss-f7b9d03e641a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1de8d310193a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Karthik Shiva]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 15:44:19 GMT</pubDate>
            <atom:updated>2022-03-22T15:44:19.746Z</atom:updated>
            <content:encoded><![CDATA[<h4>Harness the power of integration testing in your iOS apps</h4><figure><img alt="smartphone" src="https://cdn-images-1.medium.com/max/1024/0*L6GG3YJqbw_sW00q" /><figcaption>Photo by <a href="https://unsplash.com/@vojtechbruzek?utm_source=medium&amp;utm_medium=referral">Vojtech Bruzek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Is Integration Testing?</h3><p>This is where you run test cases when all your modules work together. In the real world, no module will ever function in isolation. There is always a flow of data between different modules. This is the reason bugs can occur even when all of your unit test cases pass. So, it is important to have integration tests in addition to unit tests.</p><h3>Why Integration Testing?</h3><p>Most of the apps out there communicate with some kind of backend. Particularly, the network layer is responsible for communicating with the backend and the data from this layer drives the application. Therefore, it is important that this layer functions properly, not only in isolation but also along with other modules.</p><h3>What Is the Core Idea?</h3><p>The core idea is to completely control the response (data), status code (HTTPURLResponse), and the error (error) that gets sent upwards from the network layer. By controlling these parameters, we can simulate different scenarios and check if our data parsing logic (decoding response), business layer logic (View model or Presenter) and all other modules behave as expected.</p><p>We can also examine the network requests made to our URLSession instance by our network layer and check if they are as expected.</p><p><strong><em>Disclaimer</em></strong><em>: I have intentionally avoided best practices to keep the code simple for this article.</em></p><h3>What Is URLProtocol?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0f564aff3cf1b9fbe40c64d66e38eb2/href">https://medium.com/media/a0f564aff3cf1b9fbe40c64d66e38eb2/href</a></iframe><p>Here we use a shared instance of the URLSession to make a network call. Usually, the system takes care of performing this network call and returns the result.</p><p>But the system also gives you a chance to perform the request yourself and return back the result. Using URLProtocol is the way to do it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/826ac4a7ca325ce04afd8888ecf4b2a3/href">https://medium.com/media/826ac4a7ca325ce04afd8888ecf4b2a3/href</a></iframe><p>Let’s get started:</p><ol><li>Create a URLProtocol subclass and implement the above given mandatory methods</li><li>Register your URLProtocol subclass with the system in your AppDelegate’s application (_:didFinishLaunchingWithOptions:) method.</li><li>Assign the type of your URLProtocol subclass to the protocolClasses property of URLSession. Do not create an instance of your subclass since this is taken care of by the system automatically.</li></ol><p>Now, whenever URLSession is requested to make a network request, it will first check with the objects in the protocolClasses array and ask if they want to handle the request by calling canInit(with: request) — &gt; Bool. By returning true from our subclass, we will get a chance to handle the request.</p><h3>Our Example App Structure</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14b8ce2c13a432e69355c9352bf4d00b/href">https://medium.com/media/14b8ce2c13a432e69355c9352bf4d00b/href</a></iframe><p>We have an app where a user can see a list of posts [String]. Let’s call it the user feed. We have three modules here:</p><h4>1. Network layer</h4><p>It uses the URLSession’s shared instance to make network requests and decodes the response using JSONDecoder.</p><h4>2. View Model</h4><p>It supports fetching and searching posts, using the network layer.</p><h4>3. View Controller</h4><p>It has an instance of the view model and conforms to the ViewModelDelegate protocol. It invokes the view model’s functions and receives a reply through delegate callbacks.</p><p>We can write unit test cases to verify every module’s behaviour in isolation, but what if they start behaving unexpectedly when they all start interacting with each other? This is why we will write a few integration tests to verify their behaviour.</p><p>Before we start writing our tests, let’s complete our URLSessionProxy, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77c587cac8f70b02d76a2a73e273d146/href">https://medium.com/media/77c587cac8f70b02d76a2a73e273d146/href</a></iframe><p>Don’t close the article 🤣. Let me break down what is going on:</p><h4>startLoading()</h4><p>This method is called by the system after we agree to handle an URL request by returning true inside func canInit(with request: URLRequest) -&gt; Bool. We are supposed to start processing the request and inform the client when done.</p><h4>RequestHandler</h4><p>We will use this model object to set the response, data, or error for requests.</p><h4>Static properties on URLSessionProxy</h4><p>We have a few static properties that can be used to configure our class. They need to be static since the system takes care of creating the actual instance and we will not have access to this instance.</p><ol><li>contactedURLs: [URL]</li></ol><p>This stores the list of URLs that are passed by the system. This array can be useful to examine the list of URLs that were accessed by our application.</p><p>2. shouldHandleRequest: ((URLRequest) -&gt; Bool) = { _ in true }</p><p>You can use this closure to decide whether you want to handle a particular request. This is invoked inside func canInit(with request: URLRequest) -&gt; Bool.</p><p>3. handleRequest: ((URLRequest) -&gt; RequestHandler)?</p><p>This is invoked inside func startLoading(). You can use this closure to decide how you want to respond to an URLRequest by returning an instance of RequestHandler.</p><p>We&#39;re now all set! Let’s start writing the tests.</p><h3>Test 1: User Feed API Call Is Fired on viewDidLoad()</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f72c7198390b92427e066e57b556942/href">https://medium.com/media/8f72c7198390b92427e066e57b556942/href</a></iframe><p>Expectation: URLSessionProxy’s contactedURLs array contains the user feed API Url.</p><p>We configure our URLSessionProxy to return a default instance of RequestHandler instance since we are not focused on that part in this test. Then, we invoke viewDidLoad() on the view model to kick off the process.</p><p>We wait until our expectation has been fulfilled and then take advantage of our contactedURL’s property on URLSessionProxy to check if our app contacted the user feed API as expected.</p><h3>Test 2: Users Can See Posts on Their Feed</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9cf4a4f2612190c155be9aa657b6111/href">https://medium.com/media/a9cf4a4f2612190c155be9aa657b6111/href</a></iframe><p>Expectation: On invoking viewDidLoad(), view model contains mock posts after it calls reloadPosts() on its delegate.</p><p>We set up the following:</p><ol><li>Create a view model delegate and fulfill an expectation on the delegate method call, so that we know that its time to check the view model for the mock posts [String]</li><li>Configure URLSessionProxy to return a mock response</li><li>Call viewDidLoad() on the view model to start the process</li></ol><p>When the expectation is fulfilled, we check if our view model contains our mock posts. This test will give us the confidence that both the network layer and view model are working together properly to display the posts to the user.</p><h3>Test 3: Searching Posts Work Properly for Users</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b98407e4930e1902f6efbdf50f0f137/href">https://medium.com/media/7b98407e4930e1902f6efbdf50f0f137/href</a></iframe><p>Expectation: Search API is called with the correct parameters</p><p>We configure our URLSessionProxy to capture the search URLRequest and save it to our local variable.</p><p>We then invoke the search method on our view model and then wait until our URLRequest is captured.</p><p>We then examine different parts of our URLRequest to check if all the parameters are as expected.</p><p>This is still scratching the surface with what you can do with URLSessionProxy. Hopefully, by now, you have formed an idea of how you can use this technique in your project.</p><p>The finished project is available <a href="https://github.com/KarthikShiva97/URLSessionProxy">here</a>. Feel free to explore! There is also an <a href="https://github.com/WeTransfer/Mocker">open source library</a> based on this technique.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1de8d310193a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/writing-integration-tests-for-your-network-layer-using-urlprotocol-1de8d310193a">Writing Integration Tests for Your Network Layer Using URLProtocol</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing Property Wrappers in Swift]]></title>
            <link>https://medium.com/better-programming/customizing-property-wrappers-in-swift-abe0952fc504?source=rss-f7b9d03e641a------2</link>
            <guid isPermaLink="false">https://medium.com/p/abe0952fc504</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Karthik Shiva]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 18:06:17 GMT</pubDate>
            <atom:updated>2022-02-14T18:06:17.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>And the first look at NotificationCenterPublisher property wrapper</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*thfVnc0jX3T0FrJB" /><figcaption>Photo by <a href="https://unsplash.com/@ilyapavlov?utm_source=medium&amp;utm_medium=referral">Ilya Pavlov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As the name suggests, a property wrapper is a layer that wraps around your usual property to provide additional functionality. This layer acts as a middle man between you and the actual property. So, whenever you want to set or get a value of a property, you have to communicate through the property wrapper. Now, you may ask “Why introduce a middle man in this interaction?”. Keep reading and you will find your answer.</p><p>Let’s say you are a developer on the Twitter application and you want to store a new tweet in a property. As you may know, a tweet is limited to only 280 characters. Ideally, you already have a UI that restricts the user from entering more than 280 characters.</p><p>But, that doesn’t mean that we have to limit this character check only to the UI. What if the UI breaks and suddenly people are posting essays on Twitter. You don’t want to be fired right? Let’s see how a property wrapper can save your job.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d81403f2d50fd1e430d6a8c5d1624c9/href">https://medium.com/media/2d81403f2d50fd1e430d6a8c5d1624c9/href</a></iframe><p>In the above example, we use a property called tweet to store our actual tweet. If you notice, just before our variable declaration, we have @RestrictedCharacterCount(maxCharacterCount: 33). That’s our property wrapper.</p><p>To use a property wrapper, start with the @ symbol followed by the property wrapper name. We also pass in 33 as our maxCharacterCount value since that will be the maximum number of characters that we will be storing for this example.</p><blockquote>From the output, you can observe that only the first 33 characters of our sentence that we tweeted, was actually stored on our property. The rest was ignored. If you remember, this is because we explicitly set the “maxCharacterCount” to 33 earlier. Now, you can set this number to 280 characters and keep your job<em> </em>at twitter<em>.</em></blockquote><blockquote>You might also have noticed that we acesss our property wrapper object using the $ (dollar) sign before our property name. That’s called as the projected value.</blockquote><p>Before we celebrate our win, let’s understand how this works underneath the hood.</p><p>To write a property wrapper,</p><ol><li>You can use either a struct or a class</li><li>Annotate your object with @propertyWrapper syntax.</li><li>Declare a property called wrappedValue. It has to be non-static. This is the actual property that we will be wrapping up. The data type of this property is up to you.</li><li>You can either give your wrappedValue, a default value, or let the user provide it. To do the latter, make sure to include wrappedValue as part of your object’s initializer.</li><li>Apart from receiving the value for your wrappedValue in your initializer, you can also specify other parameters that you feel are required for your property wrapper.</li><li>Now, like a middle man, whenever the property is “set” or “get”, you can freely change the value according to your logic. What you decide will become the final value that is stored or returned to the user.</li><li>The projected value is something which the user can access when they prefix the property name with a $ (dollar sign). What you return as the projected value is completely up to you.</li><li>For example, you might have a few methods or properties on your property wrapper to provide extra functionality to the user. To expose this, you can return the property wrapper itself as the projected value.</li></ol><p>Now that you have a basic understanding of how things work, let’s look at the implementation for our property wrapper @RestrictedCharacterCount from earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aba37644bc00e81abcb14f2d62480947/href">https://medium.com/media/aba37644bc00e81abcb14f2d62480947/href</a></iframe><blockquote>“Bro, why you gotta make things complex by making it generic”</blockquote><p>Bear with me for a few minutes. Let me break this down for you and you will realize how really powerful this is. So, here’s the core idea.</p><blockquote>Make a property wrapper that will take in a maximum character count as a parameter and whenever the character count of the data stored inside the property, goes beyond the maximum character count, truncate the extra characters, from the end. The property wrapper should also be compatible with a wide range of data types to allow for maximum flexibility</blockquote><p>Now, let&#39;s break down our property wrapper,</p><ol><li>To make it compatible with a wide range of data types, we make the data type of our wrappedValue generic and call it <strong>T</strong>.</li><li>We also make sure that T is something that conforms to the LosslessStringConvertible<em> </em>protocol. This allows for free conversion between T ←→ String.</li><li>Now, we convert our wrappedValue of data type T, to String to count the number of characters. If we exceed the maxCharacterCount, we trim the extra characters at the end. Finally, we convert this trimmed string back to its original data type T and store it inside the wrappedValue variable.</li><li>So, anytime the user sets a value for our property, we examine the data, count the characters, trim any extra characters and then finally store it.</li></ol><p>Here are some examples of why making it generic made it really powerful:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89dbb9ba2eaf8eeb00e21b1d8595baf1/href">https://medium.com/media/89dbb9ba2eaf8eeb00e21b1d8595baf1/href</a></iframe><p>Let me give you a few more examples to solidify your understanding.</p><p>@RestrictedRange is a property wrapper that helps you restrict the value of your property, to a specific range. Whenever any user tries to set a value that does not fall within the valid range, a closure is called to replace it with a valid value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a4ddc5ff9ab8432c9127850018192a/href">https://medium.com/media/b2a4ddc5ff9ab8432c9127850018192a/href</a></iframe><p>@NotificationCenterPublisher is a generic property wrapper that publishes every new value of the property using Notification Center.</p><p>You must pass the Notification name and can also, optionally set a closure called getUserInfo which will allow you to pass in the userInfo dictionary, just before the notification is posted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70cdbb85d24badbc15ed24a35dab7d66/href">https://medium.com/media/70cdbb85d24badbc15ed24a35dab7d66/href</a></iframe><blockquote>In summary, property wrappers help you manipulate the value of a property, everytime it is read or writtern by the user. This access logic once writtern in the form of a property wrapper, can be reused and applied to any property in your codebase.</blockquote><blockquote>You can optionally add a projectedValue to your propety wrapper, which can then be accessed through the fancy $ (dollar) syntax. This is useful for exposing any addtional functionality in your property wrapper.</blockquote><p>Property wrappers are a big part of the SwiftUI world and understanding them is crucial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abe0952fc504" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/customizing-property-wrappers-in-swift-abe0952fc504">Customizing Property Wrappers in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Opaque Types in Swift]]></title>
            <link>https://medium.com/better-programming/opaque-types-in-swift-e0ee8e2a98ba?source=rss-f7b9d03e641a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0ee8e2a98ba</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Karthik Shiva]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 05:17:32 GMT</pubDate>
            <atom:updated>2022-01-23T16:36:31.293Z</atom:updated>
            <content:encoded><![CDATA[<h4>With a spy mission example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Obbv95y3SkZJVAh6" /><figcaption>Photo by <a href="https://unsplash.com/@sergiunista?utm_source=medium&amp;utm_medium=referral">Sergiu Nista</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To understand opaque types, we are going to take up an example.</p><p>Imagine, you are the head of a secret service organisation and you want to send your spy to an enemy country. Here’s the code example to get started:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feb98ded1ffde3f50e7ce548e91d0184/href">https://medium.com/media/feb98ded1ffde3f50e7ce548e91d0184/href</a></iframe><p>When you send your spy, you don’t want your enemy country to know the real identity. You just want them to know that some person has become a new immigrant of their country.</p><p>To do that, we create a protocol named Person<strong> </strong>and we will now use this protocol to hide the real identity of the spy.</p><p>Now, the enemy country can no longer see the original type of the object that we are sending to them. So, we have now successfully hidden our spy.</p><p>Next, since our spy will be using a fake name when he is in the enemy country, we can no longer identify him using his name. So, we need some sort of ID that will stay the same irrespective of his current location.</p><p>The <a href="https://developer.apple.com/documentation/swift/identifiable">Identifiable</a> protocol is a good choice and it requires that we provide an id variable of some data type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4dbc6776891c6b97f35cdb5419fd86/href">https://medium.com/media/dd4dbc6776891c6b97f35cdb5419fd86/href</a></iframe><p>associatedtype ID means that the object that conforms to the protocol gets to decide the data type of the ID. It can be String, Int, Float etc.</p><p>We now update the Person protocol and our Spy object to conform to the Identifiable protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff3013e1118e46b8ce687043a1d55284/href">https://medium.com/media/ff3013e1118e46b8ce687043a1d55284/href</a></iframe><p>Unfortunately, we now have the dreaded error in our sendPersonToEnemyCountry() function:</p><pre>“Protocol <strong>Person</strong> can only be used as a generic constraint because it has Self or associated type requirements</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vi65mHFhd48N7B7guzo4g.png" /></figure><h3>What does that mean? Should we just cancel our Spy Mission?</h3><p>You don’t need to if you finish reading the rest of this post. Let’s see how we can save this mission.</p><p>First, let’s try to understand the problem here.</p><p>Swift is saying that we can no longer use Person protocol as the return type of our function because it <em>cannot figure out the data type</em> of our associated type “ID”. Since the associated type is essentially a generic parameter, it can belong to any data type.</p><p>Swift is a type safe language and complains when it cannot understand data types.</p><p>We could fix this issue by updating our sendPersonToEnemyCountry()<strong> </strong>function to return a data type of Spy but that would spoil our mission since our enemy country would see that we are sending them a Spy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc357422c065bda62084e5091b96b4aa/href">https://medium.com/media/cc357422c065bda62084e5091b96b4aa/href</a></iframe><p>So, what we need is a solution that can allow us to return our Spy hidden by person protocol from our sendPersonToEnemyCountry() function but at the same time overcome our previous error: <em>Protocol Person can only be used as a generic constraint because it has Self or associated type requirements</em><strong><em>.</em></strong></p><h4>Phantom Types to the rescue !!</h4><p>Now, let&#39;s update our function to use an opaque return type.</p><p>To write an opaque return type, start with the keyword some<strong><em> </em></strong>followed by your actual return type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/238a4f15f44d3acdc2cb65a51cf95c2c/href">https://medium.com/media/238a4f15f44d3acdc2cb65a51cf95c2c/href</a></iframe><p>This now compiles without any errors. We passed our mission and our spy has now infiltrated the enemy country. But, before we celebrate our win, let us try to understand how opaque types saved the day.</p><p>Our previous error was that Swift could not figure out the data type of our associated type ID. When we switched to an opaque return type, Swift started looking at our function declaration to find out what we are actually returning. In this case, we are returning a Spy object and it has an associated ID type of String. So, the error is now gone.</p><p>Even though Swift now knows exactly what we are actually returning from our function, the receiver (Enemy country) has no idea about the actual data type that gets sent (Spy) since it is still abstracted by the Person protocol.</p><p>There are still a few differences between a protocol and an opaque return type like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e6bef33a248d456fbb76e33d54b46fc/href">https://medium.com/media/5e6bef33a248d456fbb76e33d54b46fc/href</a></iframe><p>The above code results in an error. Swift is unhappy because now it does not know what data type will actually get returned from our sendPersonToEnemyCountry() function.</p><blockquote><em>Treat functions with opaque return types similar to how you would treat a function with a concrete return type. Always return a single data type from the function.</em></blockquote><p>In conclusion, an opaque return type helps us to keep the benefits of a protocol (abstraction) while allowing us to still use it as a return type, even if the protocol has Self or associated type requirements.</p><p>Thanks for reading!</p><pre><strong>Want to Connect?</strong></pre><pre>Contact me on <a href="https://www.linkedin.com/in/karthik-shiva-ab5904124/">LinkedIn</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0ee8e2a98ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/opaque-types-in-swift-e0ee8e2a98ba">Exploring Opaque Types in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phantom Types in Swift]]></title>
            <link>https://medium.com/@karthikshiva/phantom-types-in-swift-beee513e4ae0?source=rss-f7b9d03e641a------2</link>
            <guid isPermaLink="false">https://medium.com/p/beee513e4ae0</guid>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[phantom-types]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Karthik Shiva]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 14:23:41 GMT</pubDate>
            <atom:updated>2022-01-21T14:49:32.817Z</atom:updated>
            <content:encoded><![CDATA[<p>A Phantom type is just a generic type which is never used inside an object. So, why does it exist then? <strong>Type safety. </strong>Lets find out how.</p><p>In the below example, we have an user, product and a shopping cart. Both the user and the product have an <strong>id</strong> property of the same data type <strong>Int64</strong>. Even though they have the same data type, we can agree that they are two completely different things and are not comparable at all.</p><p><em>So what?</em> might be your question. Look at the following code snippet and try to find out the bug.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/254048a2b21e29860ea1a412a977c494/href">https://medium.com/media/254048a2b21e29860ea1a412a977c494/href</a></iframe><p>As you might have noticed, when we try to remove the product from the shopping cart we accidentally end up passing the <strong>user id </strong>instead of the <strong>product id</strong>. Since this is a <strong>logical error</strong>, <strong><em>Swift</em></strong> has no idea and cannot warn us.</p><p><em>But what if we can ask Swift to help us out in the above situation?</em> Follow along to learn how.</p><p>Here, we have created an <strong>Id</strong> wrapper object to hold our actual value. It also has a generic parameter <strong>PhantomType</strong> which not used inside the object. To help creating <strong>Id</strong> object easily, we have conformed to the <a href="https://developer.apple.com/documentation/swift/expressiblebyintegerliteral">ExpressiblebyIntegerliteral</a> protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75c3bd051676b6e0c2e98a9ca35b8a1d/href">https://medium.com/media/75c3bd051676b6e0c2e98a9ca35b8a1d/href</a></iframe><p>We now create 2 data types to represent <strong>user</strong> and <strong>product Ids</strong>. Enum is the best candiate here since we <strong>don’t want</strong> to <strong>instantiate</strong> them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87fbd3200d62b312880a455220f44c00/href">https://medium.com/media/87fbd3200d62b312880a455220f44c00/href</a></iframe><p>We also update our existing models to use our <strong>Id type. </strong>It uses the previously created enums to substitute for the <strong>Phantom Type</strong> <em>generic parameter</em> that is required by the <strong>Id</strong> object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c5c68ad04aecf5a7fe6fe6478476e93/href">https://medium.com/media/5c5c68ad04aecf5a7fe6fe6478476e93/href</a></iframe><p>Even though both of the above models internally use <strong>Int64</strong> to store their <strong>i<em>ds </em></strong>they are now <strong>considered</strong> to be <strong>different data types</strong> by <strong><em>Swift</em></strong> since they <strong>use</strong> <strong>different generic parameters.</strong></p><p>Let us now update our <strong>removeProduct </strong>function to use our new <strong>product id type.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cca45f1635f80800d70feb5e2b6ecf37/href">https://medium.com/media/cca45f1635f80800d70feb5e2b6ecf37/href</a></iframe><p>Revisiting our bug from earlier, you can now observe that it is now <strong>impossible</strong> to accidently pass <strong>user id</strong> or <strong>any other id</strong> for that matter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63eb463dac1dcaba9ece050216b8eb25/href">https://medium.com/media/63eb463dac1dcaba9ece050216b8eb25/href</a></iframe><p><strong><em>Swift</em></strong> will now <strong>complain</strong> and <strong>demand</strong> that you only pass a <strong>product id</strong>. We have now managed to <strong>convert</strong> what was orginally a <strong>run time bug </strong>to a <strong>compile time error</strong> by teaching Swift about our data types. <strong><em>Yaay! </em></strong>:grin:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beee513e4ae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>