<?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 Ritesh Gupta on Medium]]></title>
        <description><![CDATA[Stories by Ritesh Gupta on Medium]]></description>
        <link>https://medium.com/@_riteshhh?source=rss-c224d46d0025------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wEjR5i9Zw34hXeFgEpXIcA.png</url>
            <title>Stories by Ritesh Gupta on Medium</title>
            <link>https://medium.com/@_riteshhh?source=rss-c224d46d0025------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 12:12:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_riteshhh/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[Declarative Networking with Combine]]></title>
            <link>https://medium.com/@_riteshhh/declarative-networking-with-combine-67d0aa8004f3?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/67d0aa8004f3</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 08:33:07 GMT</pubDate>
            <atom:updated>2019-12-17T08:33:07.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdtnsLpaovt5j2sfduMWzQ.png" /></figure><blockquote><a href="https://riteshhh.com/combine/declarative-networking-with-combine/"><strong>Originally posted on my personal blog at riteshhh.com 🙇 🙈</strong></a></blockquote><p>In this post, we will explore how we can form a declarative networking layer using Combine for iOS applications. The idea here is not to re-create URLSession.DataTaskPublisher operator but rather to understand and take advantage of the existing declarative nature of Combine (and its operators) to manage success and error values declaratively. I know I have already over used the term declarative, so please bear with me 😅</p><p>The Combine framework has a built-in operator named DataTaskPublisheralong with a convenience method on URLSession which can be used to hit a network request i.e. func dataTaskPublisher(for request: URLRequest) -&gt; URLSession.DataTaskPublisher .</p><p>Though before we go ahead and parse server’s response we need to validate it so that we can segregate the error values from the success values. Once we have established this clear separation between the two paths, we can then parse them correctly and pass on the values in their respective streams. Also, the Combine framework doesn’t know how to understand custom error cases that a server might throw (4xx/5xx) or some hidden key/value pair in headers. So we need to handle two things to move forward,</p><ol><li>How to add validation rules to segregate success and error values?</li><li>How to map the server’s error response to a custom type and forward its value via error stream only?</li></ol><h4><a href="https://riteshhh.com/combine/declarative-networking-with-combine/">This is just an excerpt from the original article posted on my personal blog at riteshhh.com</a> <em>🙇‍♂️ </em>🙈</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67d0aa8004f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom binding operator in Combine]]></title>
            <link>https://medium.com/@_riteshhh/custom-binding-operator-in-combine-c7bf4f482734?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7bf4f482734</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 23:58:38 GMT</pubDate>
            <atom:updated>2019-08-20T23:58:38.341Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>For the last couple of years I have been using ReactiveSwift to use reactive paradigms in my apps. And I couldn&#39;t be happier when Apple announced Combine, the new shiny reactive framework. Though when I jumped into it, it didn&#39;t feel like home right away. The two frameworks felt a bit different even though they both follow the same principles of reactive stream.</blockquote><blockquote>One of the missing pieces is the binding operator &lt;~ which I think everyone in the ReactiveSwift community is fond of. So, I thought let&#39;s try to recreate it using Combine as it shouldn&#39;t be too hard.</blockquote><blockquote><a href="http://riteshhh.com/combine/custom-binding-operator-in-combine/">This is just an excerpt from the original article posted on my personal blog</a> 🙇‍♂️</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7bf4f482734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Child View Controllers, Part 1]]></title>
            <link>https://medium.com/swift-sundae/child-view-controllers-part-1-631ef6764b7c?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/631ef6764b7c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Sun, 24 Mar 2019 13:18:03 GMT</pubDate>
            <atom:updated>2019-03-24T13:29:20.924Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>If we are trying to refactor a massive view controller, probably embedding child view controllers is one of the ways to go about it. With this post, I&#39;m starting a series where I&#39;ll experiment with this concept and share my findings with everyone. I&#39;ll be making a movie app as a demo project to go with these posts. Every post will tackle only one problem which can be solved via child view controllers.</blockquote><h3>Part 1: AppStarterViewController</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*IyYu5Pg99JAP11Ba1X4Lug.png" /></figure><blockquote><em>This is just an excerpt from the original article posted on my </em><a href="http://riteshhh.com/child-view-controllers-part-1/"><em>personal blog</em></a><em> 🙇‍♂️</em></blockquote><blockquote><a href="http://riteshhh.com/child-view-controllers-part-1/"><em>http://riteshhh.com/child-view-controllers-part-1/</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631ef6764b7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-sundae/child-view-controllers-part-1-631ef6764b7c">Child View Controllers, Part 1</a> was originally published in <a href="https://medium.com/swift-sundae">Swift Sundae 🍨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive <~ Closure]]></title>
            <link>https://medium.com/swift-sundae/reactive-closure-530eba812768?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/530eba812768</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 19:40:54 GMT</pubDate>
            <atom:updated>2017-11-28T04:59:49.967Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article is about how to adapt a closure based api to have a reactive layer on top of it, without modifying any underlying logic!</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxTiTnpZBALuuuwyzw4%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxTiTnpZBALuuuwyzw4%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxTiTnpZBALuuuwyzw4%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c4fb9dd8ba05722d906739c644878a3/href">https://medium.com/media/9c4fb9dd8ba05722d906739c644878a3/href</a></iframe><h3>Motivation</h3><p>In the last one year, I have played a lot with <a href="https://github.com/ReactiveCocoa/ReactiveSwift">ReactiveSwift</a> and since then I haven’t looked back to non-reactive style of programming. Reactive programming completely re-wires your brain and gradually it changes the approach of solving a problem. Since I like <a href="https://github.com/riteshhgupta?tab=repositories">OSS</a> a lot, these days I’m trying to adapt my existing swift libraries to have a reactive layer as well. Though one can argue that why not re-write them completely using reactive approach. Well adding just a top layer give user the freedom to choose between reactive &amp; non-reactive versions of the same library. This is advantageous because we don’t want someone to not use our libraries just because they don’t want ReactiveCocoa since it’s a relatively bigger dependency (you can checkout <a href="https://github.com/RuiAAPeres/Receiver">Receiver</a> if you are looking for a reactive µ-framework)</p><h3>Closure based api</h3><p>Let’s say we are using a framework, DataProvider, which takes care of populating UITableView &amp; UICollectionView. After removing the low level details of the class, it looks like something below,</p><pre>class DataProvider {<br>    ...	<br>    var <strong>sections: ([Section] -&gt; Void)</strong><br>    ...<br>}</pre><p>As you can see, we have a closure named sections which we want to invoke or observe to make relevant updates in a table/collection. The objective here is to add a reactive layer along with this closure api. Since the framework, let’s say, is not maintained by us and we don&#39;t want to modify their underlying logic so let&#39;s try to figure out how to go about it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26gYPjuK6O0H63GyQ%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26gYPjuK6O0H63GyQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26gYPjuK6O0H63GyQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccb3a11921a321aa68ada7529043805b/href">https://medium.com/media/ccb3a11921a321aa68ada7529043805b/href</a></iframe><h3>ReactiveSwift</h3><h4>1. ReactiveExtensionsProvider</h4><p>If you are familiar with ReactiveSwift, there’s a protocol ReactiveExtensionsProvider which marks the foundation of adding a separate layer of reactive apis. This separate layer is provided by a property .reactive. Below you can checkout the extension in more detail,</p><pre>public struct <strong>Reactive&lt;Base&gt;</strong> { ... }</pre><pre>extension <strong>ReactiveExtensionsProvider</strong> {</pre><pre>    public var <strong>reactive: Reactive&lt;Self&gt;<br>    ...<br></strong>}</pre><p>Since <a href="https://github.com/ReactiveCocoa/ReactiveCocoa">ReactiveCocoa</a> (UIKit + ReactiveSwift) makes NSObject conform to ReactiveExtensionsProvider thus every subclass of NSObject (which is practically the entire UIKit) gets a property –– .reactive. Let&#39;s see some UIKit reactive &amp; non-reactive counterparts,</p><pre>...<br>view.<strong>alpha</strong> // non-reactive<br>view.<strong>reactive.alpha</strong> //reactive</pre><pre>view.<strong>isHidden</strong><br>view.<strong>reactive.isHidden</strong><br>...</pre><p>Similarly if we want to add a reactive layer on top of the DataProvider, we can simply conform DataProvider to ReactiveExtensionsProvider,</p><pre>extension<strong> DataProvider: ReactiveExtensionsProvider </strong>{}</pre><p>Since ReactiveExtensionsProvider is an empty protocol so we don&#39;t need to provide anything. But what we get in return is .reactive property on an instance of DataProvider. Now that we have a separate layer for reactive apis, so let&#39;s see how to make a couple of such apis. Since they are reactive apis so it&#39;s not as straight forward as adding properties directly to DataProvider. There are few steps involved which we will understand below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o85xLbmtO1CTYvwDC%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o85xLbmtO1CTYvwDC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o85xLbmtO1CTYvwDC%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c7138808f10c5e76ec7504bb8dc3eb/href">https://medium.com/media/12c7138808f10c5e76ec7504bb8dc3eb/href</a></iframe><h4>2. BindingTarget</h4><p>UIView has properties like –– view.isHidden, view.alpha etc. We already know that isHidden is of type Bool and alpha is of type CGFloat. Now if we checkout the types of their reative counterparts like view.reactive.isHidden, we can find out that it&#39;s BindingTarget&lt;Bool&gt; rather than simply Bool. Similarly view.reactive.alpha is of type BindingTarget&lt;CGFloat&gt;. So if we want a property which we want to bind, we need an instance of BindingTarget of that corresponding property. Let&#39;s try to add a corresponding reactive property for sections in DataProvider so that we can do something like dataprovider.reactive.sections which will have type BindingTarget&lt;[Section]&gt;,</p><pre>extension<strong> Reactive </strong>where<strong> Base: DataProvider</strong> {<br>	<br>    var sections: <strong>BindingTarget&lt;[Section]&gt;</strong> {<br>	return <strong>makeBindingTarget</strong> { (dataProvider, newSections) in <br>	    dataProvider.sections(newSections) <br>	}<br>    }<br>}</pre><p>Now let’s breakdown the extension so we can understand the inner bits,</p><ul><li>extension Reactive where Base: DataProvider –– Base is the custom class in which we want to add a reactive layer (DataProvider in our case).</li><li>var sections: BindingTarget&lt;[Section]&gt; –– We have already discussed it above i.e. if we have a closure api dependent on [Section] then we would want it’s reactive counterpart of type BindingTarget&lt;[Section]&gt;.</li><li>makeBindingTarget { (dataProvider, newSections) in } –– It’s an in-built function inside ReactiveSwift framework which returns an instance of BindingTarget. It has a closure based initialiser which takes two arguments as part of a tuple i.e. an instance of the Base class (DataProvider) and the input ([Section]).</li><li>dataProvider.sections(newSections) –– This is the internal underlying logic which we want to use when we get new values of sections so that we can trigger the table/collection to update.</li></ul><p>Thus after making the above changes, the new reactive api looks something like below,</p><pre>let dataProvider = DataProvider()</pre><pre>// reactive<br><strong>dataProvider.reactive.sections &lt;~ ... </strong>// acts like a target</pre><pre>// non reactive<br>dataProvider.sections(...)</pre><h4>3. BindingSource (Signal)</h4><p>Just now we saw how we can reactively get the sections which allows us to bind it with other functions. Now what if we want to observe the sections reactively as well. To achieve it, there&#39;s another protocol –– BindingSource which simply means it can act like source of values which we can listen or bind forward. We already have a class Signal comforming to BindingSource, as part of ReactiveSwift framework, to make our job easier. Let&#39;s see some UIKit examples to understand the flow,</p><pre>textField.<strong>reactive.continuousTextValues</strong> // Signal&lt;String?&gt;<br>button.<strong>reactive.controlEvents</strong> // Signal&lt;UIControlEvents&gt;</pre><p>We can see a similar pattern here as well i.e. how to migrate a type to it’s reactive counterpart — we simply need a Signal of that type. In our case it&#39;s array of section i.e. Signal&lt;[Section]&gt;. Let&#39;s again extend Reactive to add a new property called sectionsSignal</p><pre>extension<strong> Reactive </strong>where<strong> Base: DataProvider</strong> {<br>	<br>    var sectionsSignal: <strong>Signal&lt;[Section]&gt;</strong> {<br>	return Signal { observer, _ in<br>		base.sections = { sections in <br>			<strong>observer.send(value: sections) </strong><br>		}<br>	}<br>    }<br>}</pre><p>Let’s again deconstruct the extension without repeating the parts we have already discussed,</p><ul><li>return Signal { observer, _ in } –– Signal intializer gives us two arguments, observer &amp; lifetime where observer is the instance of the class which is listening to the values emitted by this Signal (for simplicity let&#39;s not talk about lifetime).</li><li>base.onNext –– base is the instance of the custom class which we want to extend to have a reactive layer. In this case it&#39;s DataProvider, that&#39;s why we can access sections property which is nothing but a closure.</li><li>observer.send(value: sections) –– whenever someone calls base.sections(), sectionsSignal will emit a new value of sections by calling the method observer.send().</li></ul><p>Thus after making the above changes, the new reactive api looks something like below,</p><pre>// acts like a source of values<br>... &lt;~ dataProvider.reactive<strong>.sectionsSignal</strong></pre><h3>Conclusion</h3><p>Thus without modifying any underlying logic of DataProvider or creating a new class, we are able to extend it to make it plugeable with other reactive apis. The protocols or classes used above are –– <strong>ReactiveExtensionsProvider</strong>, <strong>BindingTarget</strong>, <strong>Reactive</strong> &amp; <strong>Signal</strong> (<strong>BindingSource</strong>) Let&#39;s the compare the final api,</p><pre>extension<strong> DataProvider: ReactiveExtensionsProvider {}</strong></pre><pre>extension<strong> Reactive </strong>where<strong> Base: DataProvider</strong> {<br> <br>    var sections: <strong>BindingTarget&lt;[Section]&gt;</strong> {<br>       return <strong>makeBindingTarget</strong> { (dataProvider, newSections) in <br>         dataProvider.sections(newSections) <br>       }<br>    }<br> <br>    var sectionsSignal: <strong>Signal&lt;[Section]&gt;</strong> {<br>      return <strong>Signal</strong> { observer, _ in<br>          base.sections = { sections in <br>            <strong>observer.send(value: sections) </strong><br>          }<br>      }<br>    }<br>}</pre><pre>let dataProvider = DataProvider()</pre><pre>// reactive<br><strong>dataProvider.reactive.sections</strong> &lt;~ ... // used as a target<br>... &lt;~ <strong>dataProvider.reactive.sectionsSignal</strong> // used as a source</pre><pre>// non-reactive<br>dataProvider.sections(...)<br>dataProvider.sections = { sections in ... }</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl41m3OEwcrljYekBa%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl41m3OEwcrljYekBa%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl41m3OEwcrljYekBa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a2c1b1e035b069512eb025bae7444dc/href">https://medium.com/media/8a2c1b1e035b069512eb025bae7444dc/href</a></iframe><p>There are few terms/concepts which I have deliberately left out so that it doesn’t mix with the objective of the article. Feel free to ask about them in the comments or add your thoughts on how to make it better! Thanks again for reading 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=530eba812768" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-sundae/reactive-closure-530eba812768">Reactive &lt;~ Closure</a> was originally published in <a href="https://medium.com/swift-sundae">Swift Sundae 🍨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift snippet #14 — UIAlertControllerStyle]]></title>
            <link>https://medium.com/swift-snippets/swift-snippet-14-uialertcontrollerstyle-fedd6f3c4fb7?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/fedd6f3c4fb7</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Thu, 09 Nov 2017 14:06:02 GMT</pubDate>
            <atom:updated>2017-11-09T14:11:31.105Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Thursday, 9th November, 2017</em></p><h3>About</h3><p>My <a href="https://medium.com/swift-snippets/swift-snippet-13-extension-oriented-api-69bb5cf80c8c"><strong>last snippet</strong></a> was about how we can transform Apple’s Foundation/UIKit apis using extension to remove some of the boilerplate code. Today we will explore how we can reduce code to construct a UIAlertController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqvhxzI9-CEoPIYS8am5GA.png" /></figure><blockquote>You can find its <a href="https://gist.github.com/riteshhgupta/ce957c5ecfb01d5f47827496cf1d7e4d">Gist here!</a></blockquote><h3>UIAlertControllerStyle</h3><p>The first extension is on UIAlertControllerStyle which returns an instance of UIAlertController of a specific style i.e. –– alert or actionSheet. So now I can do something like this,</p><pre>let alertController = UIAlertControllerStyle<br>  .alert<br>  .controller(title:, message:, actions:)</pre><p>So instead of passing a style type inside the constructor of UIAlertController, I can now ask for a controller of a particular style <em>(if you have read my earlier snippets or blog posts, you probably know by now that I like extension oriented apis –– looks cleaner and simple to read).</em></p><h3>String</h3><p>Now any alert will also have some actions associated to it. Thus the next extension is on String since every action will some have title and it returns an instance of UIAlertAction,</p><pre>let dismissAction = &quot;Dismiss&quot;.alertAction()</pre><pre>let retryAction = &quot;Retry&quot;.alertAction { _ in /* retry logic */ }</pre><p>So instead of passing a title into the constructor of UIAlertAction, I can now ask of an alertAction on a String.</p><blockquote>That’s it, now let’s look at the entire api,</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPAipmEz4gSnfrU3S7EYdQ.png" /></figure><p>Without creating extra classes, we have been able to write such a short api to construct any kind of UIAlertController. You can also make an actionSheet using the same api 🚀.</p><p>PS –– I have used String for simplicity but if you don’t like it then you can also create an Enum just for the different actions and extend it to have similar behaviour!</p><p><em>If you are wondering about the inception of </em><a href="https://medium.com/@_riteshhh/swift-snippets-1e9a9779e024#.jvuv3zjxr"><strong><em>Swift-Snippets</em></strong></a><em> or want to checkout more such snippets, you can find them </em><a href="https://medium.com/@_riteshhh/swift-snippets-1e9a9779e024#.jvuv3zjxr"><em>here</em></a><em> </em>😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fedd6f3c4fb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-snippets/swift-snippet-14-uialertcontrollerstyle-fedd6f3c4fb7">Swift snippet #14 — UIAlertControllerStyle</a> was originally published in <a href="https://medium.com/swift-snippets">Swift Snippets 🚀</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM, you had one job to do!?]]></title>
            <link>https://medium.com/swift-sundae/mvvm-you-had-one-job-to-do-b33dfe055570?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/b33dfe055570</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Tue, 07 Nov 2017 11:03:06 GMT</pubDate>
            <atom:updated>2017-11-08T04:11:24.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-fzPw611Yw4oDTLnbShCg.jpeg" /></figure><h4>Idea 💡</h4><p>In the last couple of years, <strong>MVVM</strong> has gained some reputation in the iOS community. Almost every other conference has atleast one talk on it. Almost every other blog post is talking about design patterns specially MVVM (like this one :p). All of this indicates that it must be very good at what it does. So let’s try to understand what it actually does 🤔.</p><h4>Motivation 💪</h4><p>When we make an iOS (or you can say in general any mobile/web) app, every screen has more than one UI component like UIView, UITextField, UILabel, UIImageView.. etc. These components need to fill themselves with a lot of business logic. Hence there is a big opportunity of tight coupling between the two. Now the coupling is bad because it,</p><ul><li>increases the cost of making UI modifications</li><li>difficulty of unit testing such code</li></ul><p>Thus to decouple them, we often try to use some design patterns to add some <strong>abstraction</strong> &amp; <strong>modularity</strong>. One of such patterns is MVVM, introduced by Microsoft, which stands for ofcourse — <strong>Model-View-ViewModel</strong>. I won’t delve into the finer details of MVVM since you must be tired of reading it again &amp; again. Instead I’ll talk about what it has to offer and where else can we apply it. If you are hearing MVVM for the first time then there are some really good documentation by Microsoft which you can <a href="https://msdn.microsoft.com/en-in/library/hh848246.aspx">checkout here</a> or there are plenty of good posts by the community as well.</p><h4>What it does? 🤔</h4><p>MVVM has one &amp; only one job — it simply separates the presentation logic from an UI. Let’s talk about this presentation logic. Every UI needs to display some data in one form or the other. Now a data can’t be directly shown because it’s saved in a raw format. So we need to apply some decorative methods on it to make it usable for the UI. So far so good but nobody talks about where is this data coming from. It could come from a persistence layer or may be an api call or may be both. So who is exactly resposible for getting this data. Since ViewModel is &quot;ONLY&quot; resposible for decorating the data so may be we could put our data fetching logic also in it like some core-data helpers or may be some api logic.. aaand we are back to where we started from, it starts to sound like a controller. It&#39;s time we take a step back and leave the view-model only with presentation logic.</p><h4>Moment of truth! 😲</h4><p>Since, while we study MVVM (or such design patterns), this grey area (i.e. who gets the data) is not very well defined so we end up putting this logic inside view-model or controller. Thus giving rise to <strong>massive-controllers</strong> or these days <strong>massive-viewmodels</strong>. But nobody said that you can’t abstract data fetching just like you just abstracted presentation logic. So what we should also learn from MVVM is we should abtract out different resposibilities and put them in a different class. It’s just MVVM doesn’t talk about data fetching but we could use the idea that led to MVVM i.e. it’s good to have single responsibility per class. We can achieve this in many ways, though right now I’ll only discuss using two simple ways — concrete classes &amp; protocols.</p><h4>Example 🛠️</h4><p>In the first example we will see how can inject Datasource into UserListViewModel so that we can abstract out the logic of fetching data into a separate class and make the view-model only consume it,</p><pre>struct <strong>User</strong> {<br>	<br>	let name: String<br>}<br><br>// to fetch data from persistence/api<br>struct <strong>Datasource</strong>&lt;T&gt; {<br><br>	func items() -&gt; [T] {<br>		return []<br>	}<br>}<br><br>struct <strong>UserListViewModel</strong> {<br><br>	// decorated data with business logic<br>	let <strong>users</strong>: [User]<br><br>	init(datasource : Datasource&lt;User&gt;) {<br>		// business logic<br>		<strong>users</strong> = datasource<br>			.items()<br>			.map { &quot;\($0.name.uppercased())&quot; }<br>			.map { &quot;Hey \($0)&quot; }<br>	}<br>}</pre><p>We can achive similar result using protocol as well thus making UserListViewModel act like a datasource but without having the actuall logic inside it,</p><p><em>Update: Recently I got to know that the following approach actually has a name –– </em><strong><em>Dependency injection with Cake Pattern </em></strong>(<em>small world </em>😅)</p><pre>struct <strong>User</strong> {<br>	<br>	let name: String<br>}<br><br>// to fetch data from persistence/api<br>protocol <strong>Datasource</strong> {<br>	<br>	associatedtype Model<br>}<br><br>extension <strong>Datasource</strong> {<br>	<br>	func items() -&gt; [Model] {<br>		return []<br>	}<br>}<br><br><br>struct <strong>UserListViewModel</strong>: Datasource {<br><br>	typealias Model = User<br><br>	// decorated data with business logic<br>	let <strong>users</strong>: [User]<br><br>	init() {<br>		// business logic<br>		<strong>users</strong> = items()<br>			.map { &quot;\($0.name.uppercased())&quot; }<br>			.map { &quot;Hey \($0)&quot; }<br>	}<br>}</pre><h4>What did we learn!? 🤓</h4><p>MVVM is just not about separating presentation logic but also about abstraction in general (just like other patterns as well). Let’s not bloat view-models or view-controllers with too many responsiblities. Don’t try to fit your logic flow into popular design patterns. Rather simply try to find out different ways to just abstract functionalities and try to reuse them, it’s more than enough 🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b33dfe055570" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-sundae/mvvm-you-had-one-job-to-do-b33dfe055570">MVVM, you had one job to do!?</a> was originally published in <a href="https://medium.com/swift-sundae">Swift Sundae 🍨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusable View Class using Protocol & MVVM]]></title>
            <link>https://medium.com/swift-sundae/reusable-view-class-using-protocol-mvvm-5b2e9ff8937a?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b2e9ff8937a</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Mon, 30 Oct 2017 11:38:08 GMT</pubDate>
            <atom:updated>2017-10-30T11:57:57.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reusable View Layout using Protocol &amp; MVVM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYLUsvBiRYQM9zTHj3sKXA.jpeg" /></figure><h4>Idea 💡</h4><p>The reason I have titled it “Reusable View Layout..” rather than simply “Reusable View..” because I’m NOT referring to object level reusability of views here. Rather I’ll be discussing about how we can reuse a view layout with the help of a <strong>protocol</strong> &amp; <strong>MVVM</strong>. In the process I’ll share how we can outline a view’s interface, <em>basically different configuration states</em>, with a <strong>protocol</strong> which will enable us to inject different <strong>view-models</strong> into a view. In other words, the idea here is to design data agnostic modelling of a view layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*30g9kzCvtwKbIwfwfrFdvQ.gif" /></figure><h4>MVVM</h4><p>Before we move further, let’s get few things straight about <strong>MVVM</strong>. It’s one of most confusing design patterns out there so just want to make sure we are on the same page. It’s a design pattern where we make a view dependent on an intermediate model object called view-model. This view-model, gets some data (doesn&#39;t matter from network or persistence layer) and apply some decorative methods which is finally consumed by a view. E.g. if we have a profile view class –– <strong>ProfileView</strong>, we can create it’s view-model <strong>ProfileViewModel</strong> to configure it and save it&#39;s state.</p><pre>class ProfileView: UIView {<br><br>	var nameLabel: UILabel!<br><br>	func configure(with model: ProfileViewModel) {<br>		nameLabel.text = model.nameTitle<br>	}<br>}<br><br>struct ProfileViewModel {<br><br>	var nameTitle: String { return &quot;Profile Title&quot; }<br>} </pre><h4>Binding</h4><p>As we can see <strong>ProfileView</strong> gets coupled with <strong>ProfileViewModel</strong> for any kind of configuration which happens when you use <strong>MVVM</strong>. This works well if your view, in the entire lifetime, will only have one kind of view-model. Now let&#39;s say we want to reuse <strong>ProfileView</strong> class which should be capable of showing both an <strong>Owner</strong> profile &amp; a <strong>Guest</strong> profile.</p><h4>Enum</h4><p>To support this, we can convert <strong>ProfileViewModel</strong> into an enum where owner &amp; guest will be different cases.</p><pre>enum ProfileViewModel {<br><br>	case owner<br>	case guest<br><br>	var nameTitle: String {<br>		switch self {<br>			case .owner: return &quot;Hi, Owner&quot;<br>			case .guest: return &quot;Hi, Guest&quot;<br>		}<br>	}<br>}</pre><p>This solution doesn’t look bad at once but if we keep on adding more cases, it will eventually become a God class. To avoid this we can modify the way we think about MVVM. Instead of making our view directly dependent on a view-model, I propose to make an <strong>interface</strong> of a view which could include all the configurable properties. Thus we need something which a view could understand without actually knowing anything about it’s incoming view-models.</p><h4>Protocol</h4><p>To achieve that “<em>something</em>”, we can use a <strong>protocol</strong>. A view could have an interface which could be outlined using a protocol. This interface could have all the configurable states of it’s view. Finally we can have different view-models conforming to it. This approach makes the view totally oblivious of the kinds of view-models it could be expecting. E.g,</p><pre>class ProfileView: UIView {<br><br>	...<br><br>	func configure(with interface: ProfileViewInterface) {<br>		nameLabel.text = interface.nameTitle<br>	}<br>}<br><br>protocol ProfileViewInterface {<br><br>	var nameTitle: String { get }<br>}</pre><p>Thus now <strong>ProfileView</strong> is only aware of the fact that some object will configure it and it will be conforming to <strong>ProfileViewInterface</strong>. Doing so we have separated the layer between view and it&#39;s view-models. View is oblivious of it&#39;s view-models but view-models know which view they need to configure. This provides a scalable solution since different classes can now conform to <strong>ProfileViewInterface</strong> so that they can act like view-models for their view. E.g,</p><pre>class OwnerViewModel: ProfileViewInterface {<br><br>		var nameTitle: String { return &quot;Owner Title&quot; }<br>}<br><br>class GuestViewModel: ProfileViewInterface {<br><br>		var nameTitle: String { return &quot;Guest Title&quot; }<br>}<br><br>class AdminViewModel: ProfileViewInterface {<br><br>		var nameTitle: String { return &quot;Admin Title&quot; }<br>}<br><br>let view = ProfileView()<br><br>let ownerModel = OwnerViewModel()<br>let guestModel = GuestViewModel()<br>let adminModel = AdminViewModel()</pre><pre>view.configure(...)</pre><pre>// here we can pass any of the three above view-models since they all conform to ProfileViewInterface</pre><p>So tomorrow if you intend to add another kind of profile view then simply make a new view-model class conforming to <strong>ProfileViewInterface</strong> and inject it to <strong>ProfileView</strong>’s configure method 🚀.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b2e9ff8937a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-sundae/reusable-view-class-using-protocol-mvvm-5b2e9ff8937a">Reusable View Class using Protocol &amp; MVVM</a> was originally published in <a href="https://medium.com/swift-sundae">Swift Sundae 🍨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift snippet #13 — Extension Oriented API]]></title>
            <link>https://medium.com/swift-snippets/swift-snippet-13-extension-oriented-api-69bb5cf80c8c?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/69bb5cf80c8c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Tue, 03 Oct 2017 07:59:15 GMT</pubDate>
            <atom:updated>2017-10-03T10:21:50.639Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Tuesday, 3rd October, 2017</em></p><blockquote>I posted my last swift snippet way back in March, so roughly it’s been 6 months now. I wanted to be more active, but a lot has happened since then. Now I’m rekindling this series of snippets and hopefully will continue posting for a longer time 🚀.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*5cayiNuu7p5FL648fazb-A.png" /></figure><blockquote>You can find its <a href="https://gist.github.com/riteshhgupta/0bce24a1ce8a9b93f857fc8cf0e41ba3">Gist here!</a></blockquote><h3>About</h3><p>With this post, I would like to highlight the power &amp; relevance of creating Extensions. In my recent app, I had to use FileManager api and it’s really easy to use them btw. But after using it at couple of places, I was calling the same functions again, FileManager.default.contents(atPath: path) or FileManager.default.someFunc(). I felt it could be refactored and thus got the idea of converting the same api into more extension-oriented rather than function-oriented where you have to pass the argument.</p><p>If you observe the api — FileManager.default.<strong>contents</strong>(atPath: path), it takes exactly one argument i.e. path and thus we can make an extension on this argument (URL in general) to achieve the same result. In this case, it adds two benefits. It makes the new api,</p><ul><li><strong>inline</strong> (you can get the same result by using dot notation)</li><li><strong>shorter</strong> (makes it easier to read)</li></ul><h3>Usage</h3><p>Let’s say we want to read the contents of a json file name &quot;model_user&quot;. With the above extensions, now you can achieve something like this,</p><pre>let userData = &quot;model_user&quot;.fileURL.fileContent</pre><ul><li>fileURL gets the correct url of the file from the document&#39;s directory, eliminating the need to figure out how to get the document directory&#39;s url.</li><li>fileURL internally uses fileName which make sure that we have a centralised variable to do any processing on the file name so that the chances of getting it wrong reduces.</li><li>fileContent uses the FileManager api to get the required data</li></ul><p>Thus the final api is dependent on smaller pieces of logic which are abstracted in the extension. If you want, you can make the api even shorter by using the below extension,</p><pre>extension String {<br><br>	var fileContent: Data? {<br>		return fileURL.fileContent<br>	}<br>}<br><br>let userData = &quot;model_user&quot;.fileContent</pre><blockquote>Though I’m not saying shorter is better, it’s a matter of how much further you should/could go (clarity is more important than brevity) 🚀</blockquote><p><em>If you are wondering about the inception of </em><a href="https://medium.com/@_riteshhh/swift-snippets-1e9a9779e024#.jvuv3zjxr"><strong><em>Swift-Snippets</em></strong></a><em> or want to checkout more such snippets, you can find them </em><a href="https://medium.com/@_riteshhh/swift-snippets-1e9a9779e024#.jvuv3zjxr"><em>here</em></a><em> </em>😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69bb5cf80c8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-snippets/swift-snippet-13-extension-oriented-api-69bb5cf80c8c">Swift snippet #13 — Extension Oriented API</a> was originally published in <a href="https://medium.com/swift-snippets">Swift Snippets 🚀</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extend Swift Associated Types in Protocol to compose behaviour!]]></title>
            <link>https://medium.com/swift-sundae/extend-swift-associated-types-in-protocol-to-compose-behaviour-6753fd74669a?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/6753fd74669a</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Sun, 16 Jul 2017 20:01:20 GMT</pubDate>
            <atom:updated>2017-07-17T11:22:49.086Z</atom:updated>
            <content:encoded><![CDATA[<p>Associated Type is a great way to add generic constraint in a Swift protocol. If you are new to generic constraint or associated types, you should checkout <a href="https://www.natashatherobot.com/swift-what-are-protocols-with-associated-types/">these</a> <a href="https://www.natashatherobot.com/swift-protocols-with-associated-types/">wonderful</a> <a href="https://www.natashatherobot.com/swift-making-the-associated-type-parameter-readable-in-protocols/">articles</a> by <a href="https://medium.com/u/902a4d56b584">NatashaTheRobot</a>👌 This article aims to exlpain how we can extend behaviour of associatedTypes of a child protocol while inheriting from it’s base protocol 🙌.</p><p>Let’s take up a use case to understand what we are trying to achieve here. Every app has a UITableview or UICollectionView. To populate them, we either make an api request or hit the cache or sometimes do both. Recently I started working on multiples generic data-providers which could take care of all the above tasks. I know it sounds like too much work for protocols but hold on, you will discover later how I’ll extend associatedType to make specific data providers like CacheDataProvider &amp; APIDataProvider derived from a generic parent protocol DataProvider.</p><pre>protocol <strong>DataProvider </strong>{<br>  <br>  associatedtype <strong>Data<br>  </strong>var <strong>data</strong>: ([Data]) -&gt; Void { get set }<strong><br></strong>}<br></pre><pre>protocol <strong>CacheDataProvider: DataProvider </strong>{<br>  <br>  associatedtype <strong>Data</strong>:<strong> NSManagedObject<br></strong>}<br></pre><pre>protocol <strong>APIDataProvider: DataProvider </strong>{<br>  <br>  associatedtype <strong>Data</strong>:<strong> Parsable<br></strong>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yY7JbHJaXRJOQZE2MokIPQ.png" /></figure><p>DataProvider is the base protocol which has a generic constraint named Data which will be provided by the individual screen conforming it. Data defines the type of object that screen is dependent on like, list of users or list of magazines or list of movies etc.</p><p>CacheDataProvider is a child protocol, derived from DataProvider, which takes care of fetching cache data for a screen. In our case it should be a subclass of NSManagedObject. So what we have achieved here is that we have extended the meaning of Data from it’s parent protocol to something which makes more sense for cache related operations.</p><p>APIDataProvider is also a child protocol, derived from DataProvider which takes care of fetching new data from server. In our case it should be parsable, which converts a json into a concrete object. Here again we have extended the behaviour of Data to something which is more meaningful for fetching data via api.</p><p>This means that we can extend the meaning of Data as we like and it could differ for different child protocols. Now let’s see how they both provide the data in their own way,</p><pre>extension <strong>CacheDataProvider</strong> {<br>  <br>  func fetchCacheData() {<br>    ...<br>    <strong>Data.allObjects()<br></strong>    ...<br>  }<br>}</pre><pre><br>extension <strong>APIDataProvider</strong> {</pre><pre>  func fetchAPIData() {<br>    ...<br>    jsonList.map { <strong>Data.parse($0)</strong> }<strong><br></strong>    ...<br>  }<br>}</pre><p>As we can see, in case of CacheDataProvider we can call a function allObjects() since Data acts like a NSManagedObject &amp; allObjects() is a helper method on NSManagedObject to fetch all the cache objects.</p><p>In case of APIDataProvider we can call a function parse() which converts json into a concrete object since Data acts like Parsable which has a method to parse data.</p><p>Even though Data is not defined by DataProvider but as we have seen we can extend it’s meaning to anything we want as suited for the child protocol we create. If a screen only need cache then one can only conform to CacheDataProvider or if only need new data from api then APIDataProvider or if both are needed then one can conform to both the protocols to get cache first and then server data.</p><p>Thus associatedType is indeed a powerful way to extend functionality. I have used a similar approach along with ReactiveSwift to make different kinds of data providers including a paginated data provider which handles pagination for me 🚀 If you like the article, do share the kinds of associatedType you use in your projects in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6753fd74669a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-sundae/extend-swift-associated-types-in-protocol-to-compose-behaviour-6753fd74669a">Extend Swift Associated Types in Protocol to compose behaviour!</a> was originally published in <a href="https://medium.com/swift-sundae">Swift Sundae 🍨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift snippet #11 — RawRepresentable]]></title>
            <link>https://medium.com/swift-snippets/swift-snippet-11-rawrepresentable-2c5ed62f868c?source=rss-c224d46d0025------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c5ed62f868c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[snippet]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ritesh Gupta]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 18:13:12 GMT</pubDate>
            <atom:updated>2017-03-20T18:33:26.031Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Monday, 20th March, 2017</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*MSBP2XgSjT4IX4v6aHwLLw.png" /></figure><blockquote>You can find its <a href="https://gist.github.com/riteshhgupta/672a58b5187fbbd4681bb452becf5384">Gist here!</a></blockquote><p><em>The above snippet creates </em>items<em> &amp; </em>itemsCount<em> properties on every enum which has </em>RawValue<em> as </em>Int<em>.</em></p><pre>enum City: Int {<br> <br> case delhi<br> case bangalore<br> case mumbai<br>}</pre><p><em>With the help of above snippet, to get the entire the list of cases we can do </em>City.items<em> or </em>City.itemsCount<em> to get the count </em>🚀</p><p>Since the advent of Swift, we all have been using Enums a lot lately in our apps! And why not, they are super cool and so powerful. But they have this big limitation where we <strong><em>explicitly</em></strong> need to provide a computed var to list all the <strong><em>items</em></strong> or even <strong><em>items count, </em></strong>something<strong><em> </em></strong>like:</p><pre>extension City {<br>  <br>  static var items: [City] {<br>    return [.delhi, .bangalore, .mumbai]<br>  }<br>  static var itemsCount: int {<br>    return items.count<br>  }<br>}</pre><p>Nothing is wrong with the above code but its not awesome 😓 Everytime we add a new case, we have to update our items, failing of which could lead to bugs 🐛 No one likes them so how about we automate it to make it work out of the box &amp; thus the above snippet 😄</p><p>Big thanks to <a href="https://twitter.com/nnnnnnnn">Nate Cook</a> for making it even more <a href="https://twitter.com/nnnnnnnn/status/843177192246906880">awesome</a>!!!</p><h3>Nate Cook on Twitter</h3><p>@_riteshhh Great! 🎉 A hint: If you constrain your extension to where RawValue == Int, those don&#39;t need to be optional</p><p>It has two <strong>limitations</strong> though 🛠️:</p><ol><li><em>only applicable for enums having </em>RawValue<em> as </em>Int</li><li><em>not applicable for discontinuous cases nor the ones starting from a value other than </em>0</li></ol><p><em>If you are wondering about the inception of </em><a href="https://medium.com/@_riteshhh/swift-snippets-1e9a9779e024#.jvuv3zjxr"><strong><em>Swift-Snippets</em></strong></a><em> or want to checkout more such snippets, you can find them </em><a href="https://medium.com/@_riteshhh/swift-snippets-1e9a9779e024#.jvuv3zjxr"><em>here</em></a><em> </em>😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5ed62f868c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-snippets/swift-snippet-11-rawrepresentable-2c5ed62f868c">Swift snippet #11 — RawRepresentable</a> was originally published in <a href="https://medium.com/swift-snippets">Swift Snippets 🚀</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>