<?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 Fernando Martín Ortiz on Medium]]></title>
        <description><![CDATA[Stories by Fernando Martín Ortiz on Medium]]></description>
        <link>https://medium.com/@fmo91?source=rss-acb23ab50f4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2lSD0Kstdj9_jMBHFI11Tw.jpeg</url>
            <title>Stories by Fernando Martín Ortiz on Medium</title>
            <link>https://medium.com/@fmo91?source=rss-acb23ab50f4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:20:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fmo91/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[Unidirectional Architectures and time traveling in Swift: I]]></title>
            <link>https://fmo91.medium.com/unidirectional-architectures-and-time-traveling-in-swift-i-55085d31eff2?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/55085d31eff2</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 12:03:17 GMT</pubDate>
            <atom:updated>2020-12-21T12:15:15.029Z</atom:updated>
            <content:encoded><![CDATA[<p>Time traveling in Swift is possible. This is a series that describe how Unidirectional architectures can be applied in Swift and how we can do very impressive things by enforcing them.</p><p>This is the first article in the series, but before deep diving into Swift specifics. I’d like to give you an introduction to the general concepts that make all of this possible.</p><h3>What is time traveling?</h3><p>Of course this is not my idea. Time Traveling has been discussed in the Javascript world <a href="https://www.youtube.com/watch?v=uvAXVMwHJXU&amp;ab_channel=ReactEurope">several times</a>. However, there are not so many examples of it in Swift.</p><p>When we talk about time traveling in the context of a Frontend application, <a href="https://youtu.be/8QNGrxOKVW8">this is what we have in mind</a>.</p><p>We can record user sessions, and then reproduce the actions, go back, go forward, and “travel” in time, because all the actions are reproducible.</p><h3>The main components</h3><p>A word in the previous description is important: <strong>Actions</strong>. An <strong>Action</strong> is an object that describes something that happened in the system.</p><p>Did the user change the text in a textfield? That is an <strong>Action</strong>.</p><p>Did the user tap the button to create a To Do? That is an <strong>Action</strong>.</p><p>Did the user complete a To Do? That is also an <strong>Action</strong>.</p><p>Given that, if we want to describe something that happened in the system, anything, we need to create an <strong>Action</strong> that describes the event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*PXp-hZ_HiVYsgCwnjMZ1ng.png" /></figure><p>—</p><p>In order to time travel, we need to be able to get a certain <strong>State</strong> for the system by applying the <strong>Action</strong> objects, sequentially. Nothing else can possibly affect or modify the <strong>State</strong>. If anything else was able to mutate the <strong>State</strong> other than an action, then we couldn’t reproduce old states accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*gwfG5iLPYMuPVbdoo50IQg.png" /></figure><p>In the diagram above, I illustrate how a sequence of actions resulted in a state with an empty <strong>text</strong> attribute and an array with a single <strong>todo</strong> object that is completed. If we removed the <strong>toggleTodo</strong> action, we could apply all the other actions and get a state which is in turn the previous state. <strong>It is an undo event.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*MIS3oXyhwxCZqiUqPjH_vg.png" /></figure><p>We can also store the deleted actions in a separate stack, so we can bring those back to the main actions stack and calculate the state again. <strong>It is a redo event.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*GT05PxyAlWo3YLLEldp0-w.png" /></figure><p>So, we apply a set of <strong>Action</strong> objects, and we get a resulting application <strong>State</strong>. So far, so good. But, we can think of actions as an <strong>enum</strong> with a number of cases with associated values, and the <strong>State</strong> of a struct or a class with all the values inside, and that’s ok. However, something is missing: how is state mutated? Where is that mutation described?</p><h3>The missing piece: The reducer</h3><p>A <strong>reducer</strong> is a pure function. That means that its output is only calculated based on its input. It is a function in the traditional mathematical sense of the concept. Each element in its domain has only one element in its image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*AH4kkdFjOgEfOke8VzZtgQ.png" /><figcaption>Image from “Math is fun”</figcaption></figure><p>The <strong>reducer</strong> is the only function which is allowed to perform mutations in the <strong>State</strong>. Ok, it doesn’t mutate the <strong>State</strong>. It actually produces new states based on the previous <strong>State</strong> and an <strong>Action</strong>. It does so because it should only depend on its input. If it mutated the current state, it would also depend in a variable from the outside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*-mMsBzvPKt4qvcWPfDifKg.png" /></figure><p>For each <strong>Action</strong> we get in the system, we send that action to the `reducer` along with the current <strong>State</strong>. The <strong>reducer</strong> returns the new <strong>State</strong>, so we store that value and we are prepared for the next <strong>Action</strong> that we will eventually get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*U3uixkqsW7nhXR0z-je2iw.png" /></figure><p>Due to the <strong>functional purity</strong> of the <strong>reducer</strong>, and given that all the events that could possibly mutate the <strong>State</strong> are expressed through an <strong>Action</strong>, each step is reproducible. We can travel in time by storing all the actions and calculate previous and next <strong>State</strong> values by applying all the <strong>Action</strong> values sequentially using the <strong>reducer</strong> function.</p><h3>f(State) = UI</h3><p>For all of this to work, we need to enforce <strong>functional purity</strong> in another transformation: <strong>the view should be a pure function of the application state</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*_zHUqkZmOAFIsql9CX15vg.png" /></figure><p>Changes in the application states will produce modifications in the View to happen. This may sound as a lot of work, but keep in mind to things:</p><p>1. The power of programming depends more on the things you can’t do than on the things you are able to do. Applying restrictions to the things you can do is a way of getting properties in your system that allow you to do this kind of things.<br>2. SwiftUI already does this for you for free. Views in SwiftUI are rendered depending only on the state you have on them and on your <strong>ObservableObjects</strong>. This is taking that approach one step forward, and centralizing all your state in a single, big State object that can be mutated only by a function called <strong>reducer</strong>.</p><h3>The store</h3><p>There is another component that hasn’t been discussed so far. The <strong>Store</strong> is an object, that can be implemented in SwiftUI as a <strong>ObservableObject</strong>, that holds our <strong>State</strong>, our <strong>reducer</strong>, and exposes a function called <strong>dispatch(action:)</strong>, which takes an <strong>Action</strong> and replaces the current <strong>State</strong> for the result of the <strong>reducer</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*dbbu3Lzf_qxvx0sO9A0Mig.png" /></figure><h3>To sum up</h3><p>As said, <strong>The power of programming depends more on the things you can’t do than on the things you are able to do.</strong> If you enforce functional purity in your application, and express all mutations through actions, the state then becomes reproducible, you can go back and forward as you want, you can record user sessions, and many many many other things we havent covered in this article.</p><p>In the next article, we will translate all of this in actual Swift/SwiftUI code, so you will get a more practical understanding on how all of this fits in a real app.</p><p>If you want to learn an iOS architecture that applies all of this and is production ready, I would <strong>HIGHLY</strong> recommend <a href="https://github.com/pointfreeco/swift-composable-architecture">The Composable Architecture</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55085d31eff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Dependency Injection using @propertyWrapper]]></title>
            <link>https://fmo91.medium.com/simple-dependency-injection-using-propertywrapper-5f40f8795d60?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f40f8795d60</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 04:07:35 GMT</pubDate>
            <atom:updated>2019-11-04T04:07:35.835Z</atom:updated>
            <content:encoded><![CDATA[<p>Notes: This has already been posted on my <a href="https://fmo91.github.io/0002-dependency-injection-using-property-wrappers/">personal blog</a>.</p><p><strong>TL;DR</strong> :: <a href="https://gist.github.com/fmo91/2d359f82569dda69002784a49486b3c8">Here</a> is the gist.</p><p>Dependency injection is critical to get a good-quality codebase. As misterious as it can sound, dependency injection is central in software architecture.</p><p>But, what is it exactly? Well, let’s explain it through an example. Let’s suppose we want to design a groceries store calculator. We want to sum all the products’ prices and then calculate the taxes to the sub-total. We’ll start with a module: <strong>ProductsCalculator</strong>, and a struct called <strong>Product</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5437ee5668a125d3fbd9b2b3b9c12cd/href">https://medium.com/media/d5437ee5668a125d3fbd9b2b3b9c12cd/href</a></iframe><p>This can work for a simple use case. But real world scenarios are hardly ever that simple. Out there, in the real world, we will find really strange logics that will change over time, and we need to be prepared for them. And our most important tool for this, is a good software architecture. To get a good architecture, we will need to decouple the code a bit by splitting it into modules. And a good option here is to create a <strong>TaxesCalculator</strong> object that can calculate the taxes to be applied. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/389f24c7db1e6d22b3206f5e3e12f4ab/href">https://medium.com/media/389f24c7db1e6d22b3206f5e3e12f4ab/href</a></iframe><p>This way, we could change the code in <strong>TaxesCalculator</strong> without modifying <strong>ProductsCalculator</strong>. However, we can improve this design a lot. In first place, a good practice is to code against an interface and never against a concrete implementation. To apply this gold principle here, we would need to do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c25c2198bafd55bddb36af07cb7d2fe6/href">https://medium.com/media/c25c2198bafd55bddb36af07cb7d2fe6/href</a></iframe><p>This way, we can vary the <strong>TaxesCalculatorType</strong> we are using without affecting the internal logic in <strong>ProductsCalculator</strong>. Each module knows only what is needs to know.</p><p>This code still has an important failure in its design… We are still instantiating the <strong>TaxesCalculatorType</strong> in the <strong>ProductsCalculator</strong> class, so it still has a strong dependency on the concrete implementation. And now is when <strong>Dependency Injection</strong> comes into the play.</p><p>We will need to <strong>inject</strong> the concrete <strong>TaxesCalculatorType</strong> object in the <strong>ProductsCalculator</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9a0bde7bf7549936c56b6a126065ed6/href">https://medium.com/media/a9a0bde7bf7549936c56b6a126065ed6/href</a></iframe><p>By injecting the <strong>TaxesCalculatorType</strong> in the constructor, we don’t have a dependency on the concrete implementation anymore.</p><p>To generalize, when you have two modules A and B, A has a dependency on B if it calls a method from B, or has a reference for B, or knows something about B. Then, we have two possiblities, A can either know exactly how to create B, and how to use it, or we can `inject` B into A. That’s what <strong>dependency injection</strong> (<strong>DI</strong>) is about: Don’t letting a module know all about its dependencies, but giving it its dependencies from the outside. That way, we can give it different objects depedending on the context.</p><h4>Different ways to inject a dependency.</h4><p>The four most common ways to inject a dependency are:</p><p>1. <strong>Using a method/property</strong>: We pass the concrete implementation by calling a method or setting a property in the class. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d15a3174f884cc0df5fbc79ca08c234/href">https://medium.com/media/0d15a3174f884cc0df5fbc79ca08c234/href</a></iframe><p>2. <strong>Injecting in the constructor</strong>: We inject the dependency using the constructor, as seen in the first example.<br>3. <strong>Using a DI Container</strong>: This is more popular on other stacks (like Java, for example). We use a class called <strong>Container</strong> to <strong>register</strong> the dependencies at the beginning of the program, and then from the rest of the code we ask the <strong>Container</strong> to <strong>resolve</strong> which class should we use there.</p><h4>Property Wrappers</h4><p>Enough with Dependency Injection. Let’s talk about the other important part of this article: <strong>Property Wrappers</strong>.</p><p><strong>Property Wrappers</strong> are a new addition in Swift 5. They let us “delegate” the access of a property to a struct that is annotated with <a href="http://twitter.com/propertyWrapper"><strong>@propertyWrapper</strong></a>. Let’s explain it with an example before jumping into dependency injection again: We want to have an array that is always sorted by a specific criteria.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc43b6042349bdbfac1a77e2951cd202/href">https://medium.com/media/cc43b6042349bdbfac1a77e2951cd202/href</a></iframe><p>So let’s see how we can use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/442a4d607bb86de2bbe404f42bdf325e/href">https://medium.com/media/442a4d607bb86de2bbe404f42bdf325e/href</a></iframe><p>Not that hard, huh? Another thing I haven’t said in the example is that all the properties that are annotated by a property wrapper need to be <strong>var</strong>. <strong>let</strong> isn’t allowed to be used with property wrappers.</p><h4>So, what?</h4><p>How are property wrappers related to Dependency Injection? They seem to be cool stuff but not related in any way so far. Yes, that can seem to be the case, but we can use property wrappers to inject dependencies from a DI Container.</p><p>Let’s see how this could work.</p><p>We will start by creating a NameContainer for the dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de40b54a53f04486203eb2f8d53c0117/href">https://medium.com/media/de40b54a53f04486203eb2f8d53c0117/href</a></iframe><p>We need two more functions in the container: <br>- <strong>register</strong>: Adds a new entry for the dependencies registry. Optionally namespaced.<br>- <strong>resolve</strong>: It will return the needed dependency for the requested type. It can also work for namespaced dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0f4371df98378d7fd516b9b408545ff/href">https://medium.com/media/d0f4371df98378d7fd516b9b408545ff/href</a></iframe><p>Finally we need a property wrapper that can inject a dependency from the container in a property from an unrelated class. This property wrapper needs an optional argument for the dependency key and another optional argument for the DI container (it will default to the `default` singleton container).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fe88655a2f8c08b690907e35742130c/href">https://medium.com/media/6fe88655a2f8c08b690907e35742130c/href</a></iframe><p>Simple, right?</p><p>Let’s see how we can use this utility:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72d8c6d0dd6c2ac1cc49a51e85aa68b3/href">https://medium.com/media/72d8c6d0dd6c2ac1cc49a51e85aa68b3/href</a></iframe><h4>Conclusion</h4><p>Dependency injection is a pattern that you will be using once and once again as a software designer. Normally, using just constructor-based DI will be enough. But having this simple alternative can be handy. Also, you have learnt one thing or two about property wrappers too.</p><p>Thank you!</p><h4>Final Code</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9d911cdd4db74a90c3df918a75db6e2/href">https://medium.com/media/a9d911cdd4db74a90c3df918a75db6e2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f40f8795d60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A single source of truth]]></title>
            <link>https://fmo91.medium.com/a-single-source-of-truth-4c9fade0e758?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c9fade0e758</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Mon, 04 Nov 2019 03:51:59 GMT</pubDate>
            <atom:updated>2019-11-04T03:52:46.139Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: This article has already been posted on </em><a href="https://fmo91.github.io/0001-single-source-of-truth/"><em>my personal blog</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86C0luHms5N6DntKOjkf_A.jpeg" /></figure><p>I’ve been an iOS developer for almost five years. And working as a software engineer, you may know, is something frustrating. <br>Sure, it’s fulfulling, it’s a creative activity, I know, but it’s also frustrating. One thing I realised with the time<br>is that your taste evolves faster than your ability.</p><p>In my first projects, I followed the only technique I knew: programming imperatively. And it worked. Screens appeared in my<br>app, with the controls I programmed, and I felt better at the time.</p><p>The main characteristic that differentiates a junior developer from a senior one is the <strong>understanding of tradeoffs</strong>. A senior developer can create code that is scalable over time, and does that when required. He almost always chooses the approach that is complex enough to get the work done, but creating the least amount of accidental complexity in the process.</p><p>This introduction may seem a bit longer than needed, but it’s important to take this into account, because there are a lot of tools to solve each problem, and this one is not an exception. Today, I’ll write about the most important issue a UI developer face every day in my opinion: <strong>State management</strong>.</p><h4>Our problem</h4><p>Let’s work with an example. We are working on a calculator that operates on two numbers. The requirements for our simple screen would be:</p><p>1. There must be two text fields, so the user can introduce the arguments.<br>2. There must be a third text field, in which the user can select the operation to be performed.<br>3. There must be a label where the result will appear.<br>4. There must be no button. The entire UI should be refreshed on any change that may occur.</p><h4>What I used to do</h4><p>So here is what I would have done when I started as a developer.</p><p>First, I would have created the outlets for the views (I’ll not specify how the storyboard is done, to be more concise):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa475b5597a53b32b1664323d3d2538e/href">https://medium.com/media/fa475b5597a53b32b1664323d3d2538e/href</a></iframe><p>Then, I’d have configured the event handlers for my views, and an enum that will be helpful for to describe the operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85f7ede7f3a363a03b3a4d9c1be5d48e/href">https://medium.com/media/85f7ede7f3a363a03b3a4d9c1be5d48e/href</a></iframe><p>And finally, a method that would have refreshed the views accordingly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2deb6bfd397f4659d9c4a0f0de32df32/href">https://medium.com/media/2deb6bfd397f4659d9c4a0f0de32df32/href</a></iframe><p>This approach works great for basic tasks. And I insist with this, because there is nothing wrong with it in my opinion. However, if we know that the screen will be more complicated, or if there are more requirements that we haven’t coded yet, we can make some changes to it.</p><h4>The rule</h4><p>I have a main rule when it comes to UI software development: <strong>There should be a single source of truth, so state is always consistent.</strong></p><p>State is a bomb of complexity, that will explode on your face if you aren’t careful enough. So, as state is a bomb, and we have to be careful of it, it would be better if we isolate it, so the rest of our code will be safe.</p><p>We can create a <strong>ViewModel</strong>. Or name it as you want. The purpose of a <strong>ViewModel</strong> is to store the state for our view, and encapsulate the logic of how to manipulate it. Our View won’t know how to operate on the operands anymore, nor know what is an operand, or which is the current operand. In our example, our view will:</p><p>1. Handle the user events, and notify the <strong>ViewModel</strong>.<br>2. Get data from the <strong>ViewModel</strong> and update accordingly whenever the data changes.</p><p>And the <strong>ViewModel</strong> will be responsible for:</p><p>1. Receive events from the view.<br>2. Expose data to the view and notify whenever the data changes.</p><p>This approach is a bit more complex, because we need to maintain two classes instead of one, but it has other benefits. We splitted the responsibilities, and we know that the <strong>ViewModel</strong> will <strong>always</strong> have the current state. There won’t be duplicated states, or inconsistent states on our view.</p><p>We’ll need a way to notify the view when the data changes in the <strong>ViewModel</strong>. We can use delegation, or configure a closure so we can execute it from the <strong>ViewModel</strong> when the data changes, but it’s better to use a specialized tool for this. Some people use <strong>RxSwift</strong>/<strong>RxCocoa</strong>, and I’m also a great enthusiast of these tools. However, Apple listened us and created a library that is included in the iOS SDK and does that for us: <strong>Combine</strong>. So we’ll use it on our example</p><p>In practice, this will be our <strong>ViewModel</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5477fe10b29f9eb4bdbd079b3c06f16e/href">https://medium.com/media/5477fe10b29f9eb4bdbd079b3c06f16e/href</a></iframe><p>So, what’s happening here? Let’s go through it:</p><ol><li>In <strong>Combine</strong>, <a href="http://twitter.com/Published"><strong>@Published</strong></a> variables are variables that are like any other variable, but they have a <strong>projectedValue</strong> (the <strong>$</strong> prefix) that returns us the <strong>Publisher</strong> associated to it. And by using a <strong>Published</strong> we can operate on the changes the value can have over time. In our <strong>ViewModel</strong> we have <strong>input</strong> variables (the ones that our View Controller sets), and <strong>output</strong> variables (the variables our View Controller listens to).</li><li>When we listen to a <strong>Publisher</strong>, that <strong>subscription</strong> needs to be managed in terms of memory usage. That’s what our array of AnyCancellables does. Apart from that, we can use this extension to make our code more elegant:<br><a href="https://gist.github.com/fmo91/91132290e687284468857589381eb8c6">https://gist.github.com/fmo91/91132290e687284468857589381eb8c6</a></li><li>These are the listeners we can configure so our code is reactive.<br> * Whenever the <strong>firstNumberText</strong> value changes, it’s converted into a <strong>Int</strong>, and finally it’s value is assigned to <strong>firstNumber</strong>. We do the same with <strong>secondNumberText</strong> and <strong>secondNumber</strong>.<br> * Something similar is used to transform <strong>operation</strong> to <strong>operationText</strong>.<br> * As we are making subscriptions, we need to manage the memory usage here appending them to our array of <strong>AnyCancellable</strong> objects.</li><li>This is basically what <strong>calculateResult</strong> did in our previous example. We execute this whenever <strong>firstNumber</strong>, <strong>secondNumber</strong>, or <strong>operation</strong> change. And finally we assign the value to <strong>result</strong>.</li></ol><p>On the other side, we need to update ViewController, the code is below, but the important thing to keep in mind here is that now our VIewController just updates values in the <strong>ViewModel</strong> and listens to changes on it. Nothing else.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52101091c3311c260e75b9f880f2bbae/href">https://medium.com/media/52101091c3311c260e75b9f880f2bbae/href</a></iframe><p>Much simpler.</p><h4>A bright future in the horizon</h4><p>As you can guess. the above code is elegant and scalable. But it still looks unnatural. These are not how UIKit was build to be used. UIKit is imperative. And even the documentation Apple gives to us encourages us to work imperatively. This is embedded in the DNA of the framework.</p><p>But something is changing. The reactive/declarative approach for UI development and state management has gained great adoption during the last five years or so, mainly since React gained popularity and became the default way to build UIs in the web.</p><p>Apple also listened to this revolution taking place, and came out with a new shiny framework named <strong>SwiftUI</strong>. In <strong>SwiftUI</strong> we declare our state, and the view that is build using that state. Whenever the state changes, the view is configured again. Sounds familiar? It’s exactly the principle our <strong>ViewModel</strong>-based solution was built based on.</p><p>Even when <strong>SwiftUI</strong> is in its infancy, it’s a great tool we should keep an eye on it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9fade0e758" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimal Networking layer from scratch in Swift 4]]></title>
            <link>https://medium.com/ios-os-x-development/minimal-networking-layer-from-scratch-in-swift-4-a151af786dc5?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a151af786dc5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Mon, 28 May 2018 17:57:38 GMT</pubDate>
            <atom:updated>2018-05-28T17:57:38.347Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to build a declarative Networking layer in 118 relying on Codable, protocol oriented programming and URLSession without compromising modularity.</h4><h3>Introduction</h3><p>Almost every iOS app has a networking layer in order to comunicate with a JSON Api.</p><p>There are some great libraries that we can use to write the code needed to work with that Api. But they either is bloated and has many methods that we will never use, or they are so lightweight that they don’t enforce a clear code structure.</p><p>If you aren’t willing to read the whole thing, I’ve packed the code in this article as a module and released it as a Cocoapod. Feel free to use it and contribute to the repo in case you need.</p><p><a href="https://github.com/fmo91/Conn">fmo91/Conn</a></p><h3>The Request process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*1C_G_vaot6aeiNRBZGZ-PA.png" /><figcaption>The request process simplified</figcaption></figure><p>This may be the silliest diagram I’ve ever done, but it has sense to start this explanation.</p><p>When describing a http request, we have to describe two parts.</p><ol><li><strong>The Request:</strong> What does the networking layer need to know in order to dispatch the request</li><li><strong>The Response:</strong> What does the networking layer need to know in order to parse the response to make it valuable for the rest of the app.</li></ol><p>In addition, there is another component that we will call “Dispatcher”, which is needed in order to dispatch the request to the server.</p><h3>The Request</h3><p>The first step to create a declarative layer is describing the concepts in terms of “what” instead of “how”.</p><p>So, what is a Request ? A request is an object that describes “what” is required to perform a http request. It includes:</p><ul><li>The url path of the resource that we are requiring.</li><li>The HTTP method (get, post, put, patch, delete, etc.)</li><li>The body parameters in case it is needed</li><li>The request headers</li></ul><p>In swift, this can be declared as a struct</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9c9d6a03d4b58876500ac8963adc3d4/href">https://medium.com/media/f9c9d6a03d4b58876500ac8963adc3d4/href</a></iframe><h3>The Response</h3><p>When the request is resolved and the JSON is returned from the API, we need to parse it to actual models that make sense in the context of our app.</p><p>To accomplish that, we can take advantage of a recent feature of Swift: The Codable protocol.</p><p>For instance, a User model can be described as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd06f50f02018f6523e5cf601c5efb73/href">https://medium.com/media/fd06f50f02018f6523e5cf601c5efb73/href</a></iframe><h3>Wrapping it up</h3><p>In order to join Request and Response in something that acts as a glue, we are going to use protocol oriented programming.</p><p>We can define a protocol called RequestType that associates a Request with the matching response type (implementing Codable )</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/264c42bdf9f84c29689701af299a5550/href">https://medium.com/media/264c42bdf9f84c29689701af299a5550/href</a></iframe><h3>The Dispatcher</h3><p>Ok, so we have a RequestType that joins the request data and the shape of the response of a certain request. We just need something that actually dispatches the request using the request data and parses the returning json to convert it to the models. That “thing” is called a Dispatcher .</p><p>Lets take a look at the protocol describing the requirements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1642b0161558de3bd4486c64b8cfe411/href">https://medium.com/media/1642b0161558de3bd4486c64b8cfe411/href</a></iframe><p>The dispatcher can be implemented in very different ways. To make it lightweight, we are going to use the native UrlSession . The code would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0de1244357d84a2d38db9c1bcc019e/href">https://medium.com/media/5b0de1244357d84a2d38db9c1bcc019e/href</a></iframe><p>To use the dispatcher to dispatch the request, we are going to extend the RequestType protocol to allow it to actually execute the requests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f77fc04400b88bffac760b4623bdf96/href">https://medium.com/media/2f77fc04400b88bffac760b4623bdf96/href</a></iframe><p>Please note that the dispatcher is interchangeable, so you can use whatever you want in its place, as long as it conforms to NetworkDispatcher protocol.</p><h3>Example Usage</h3><p>Three simple steps:</p><ol><li>Write a struct/class that conforms to Codable .</li><li>Write a struct/class/enum that conforms to RequestType .</li><li>Execute it!</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6af27b5ce22088506803eab2acbd5d38/href">https://medium.com/media/6af27b5ce22088506803eab2acbd5d38/href</a></iframe><h3>Conclusion</h3><p>I have been using this pattern for a long time in production environments, and I personally love it due to its natural simplicity. It just feels like the natual way of describing network layers.</p><p>I would really like if you try the library and make me know what you think about it.</p><p><a href="https://github.com/fmo91/Conn">fmo91/Conn</a></p><p>Feel free to ask whatever you need</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a151af786dc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/minimal-networking-layer-from-scratch-in-swift-4-a151af786dc5">Minimal Networking layer from scratch in Swift 4</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service-oriented AppDelegate]]></title>
            <link>https://medium.com/ios-os-x-development/pluggableapplicationdelegate-e50b2c5d97dd?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50b2c5d97dd</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[clean]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Mon, 27 Feb 2017 01:57:08 GMT</pubDate>
            <atom:updated>2017-02-27T19:04:52.093Z</atom:updated>
            <content:encoded><![CDATA[<h4>AppDelegate is typically a huge class. It knows too much about your application and it progressively becomes a mess. Here, I will show you how to decouple it from its sub-functionalities by creating a clean plugin-based architecture.</h4><p>We are facing the problem in an incorrect way. Think about how you are managing your AppDelegate. I bet you that it’s huge, or at least you are using some workaround but you are not proud about how you are coding it.</p><p>The problem with AppDelegate is that it knows too much about your app. It knows your dependencies, how to initialize them, how to parse your push notifications, and many more things.</p><h3>TL;DR</h3><p>You can create ApplicationServices, those are objects that shares the AppDelegate life cycle and performs actions on its steps. Your AppDelegate then becomes observable and your services are its observers. This approach allows you to decouple AppDelegate from its services and create Single-responsibility objects.</p><p>Of course, it turns into a lot of boilerplate, so I have created a Cocoapod to face this problem. It is called PluggableAppDelegate and you can find it <a href="https://github.com/fmo91/PluggableApplicationDelegate">here</a>: <a href="https://github.com/fmo91/PluggableApplicationDelegate">https://github.com/fmo91/PluggableApplicationDelegate</a></p><p>You only have to create services and register them on AppDelegate. The result is the smallest and cleanest AppDelegate you have ever seen.</p><h3>Typical AppDelegate</h3><p>Typically, AppDelegate has a lot of responsibilities.</p><ol><li>Initialize EVERY dependency of your application.</li><li>Setup global UIAppearance values.</li><li>Handle push notifications.</li><li>Register to push notifications.</li></ol><p>And many more.</p><p>The problem here is that your AppDelegate knows exactly how every Component works and how to instantiate them. It also knows how your app should look like. And it knows the format of your push notifications. In result, it grows A LOT more than you may expect.</p><h3>A different approach</h3><p>Imagine that you have your dependencies encapsulated in their own components, called ApplicationService.</p><p>Every ApplicationService is a sub-AppDelegate. It shares its life cycle and performs actions in the events it requires.</p><p>Your AppDelegate becomes an observable source of events, as it only notifies its services that something happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*Cy1ZwjspjqL1Z4meMQPPOA.png" /><figcaption>Services-oriented AppDelegate</figcaption></figure><h3>Application Services</h3><p>Application Services are objects that share the AppDelegate life cycle. ApplicationService is just a tagging protocol. If you are using <a href="https://github.com/fmo91/PluggableApplicationDelegate">PluggableApplicationDelegate</a>, It looks like this:</p><pre>public protocol ApplicationService: UIApplicationDelegate {}</pre><p>As you can see, it’s only UIApplicationDelegate, but with a more expressive name.</p><p>When you implement it, it’s like implementing an AppDelegate, but the key difference here is that you are coding a single responsibility component.</p><p>Here is an example implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32abde39796480157e2e6f3c04d127a7/href">https://medium.com/media/32abde39796480157e2e6f3c04d127a7/href</a></iframe><h3>The new AppDelegate</h3><p>Now, your AppDelegate becomes a lot smaller, as it only has to inherit from PluggableApplicationDelegate and register its services.</p><p>Check this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2766b77ff92f44357fa2d7c25dd9903b/href">https://medium.com/media/2766b77ff92f44357fa2d7c25dd9903b/href</a></iframe><p>PluggableApplicationDelegate is just boilerplate. It only notifies its services that something has happened. You can check its code here: <a href="https://github.com/fmo91/PluggableApplicationDelegate/blob/master/PluggableApplicationDelegate/Classes/ApplicationServicesManager.swift">https://github.com/fmo91/PluggableApplicationDelegate/blob/master/PluggableApplicationDelegate/Classes/ApplicationServicesManager.swift</a></p><p>As long as you are adding more and more dependencies and features to your app, your AppDelegate remains clean, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd45f018086de5f7c0613a44a3bd6708/href">https://medium.com/media/dd45f018086de5f7c0613a44a3bd6708/href</a></iframe><h3>Conclusion</h3><p>That’s all. It’s a very simple approach that allows you to decouple your AppDelegate, preventing it to become a mess.</p><p>Don’t forget to see my github repository here: <a href="https://github.com/fmo91/PluggableApplicationDelegate">https://github.com/fmo91/PluggableApplicationDelegate</a></p><p>I hope this will help you as much as me. I really want to have some feedback about this. Please, leave your comments bellow 👇🏼</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50b2c5d97dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/pluggableapplicationdelegate-e50b2c5d97dd">Service-oriented AppDelegate</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Little Snippets #1: Group By in Swift 3]]></title>
            <link>https://medium.com/ios-os-x-development/little-snippet-group-by-in-swift-3-5be0a06307db?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be0a06307db</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Thu, 23 Feb 2017 05:03:49 GMT</pubDate>
            <atom:updated>2017-02-23T17:17:39.716Z</atom:updated>
            <content:encoded><![CDATA[<h4>A short implementation of the classic ‘group by’ function in Swift 3 as an Array extension.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*armBBh0jRHvfQ0fY6hsrqw.png" /></figure><p>Given an array of elements, and a <strong>criteria </strong>function, grouped(by:) transforms that array into a dictionary with the keys that the criteria function returns.</p><p>The criteria function takes an Element and returns its classification. For example, if you want to separate even numbers from odd ones, your criteria closure will return “even”, or “odd”.</p><p>I often use this for separating elements by creation date.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/397412d9c9fa0d09c2b9d5197399da60/href">https://medium.com/media/397412d9c9fa0d09c2b9d5197399da60/href</a></iframe><p>I hope this will help you. If you know a better way of doing this, please let me know below, in the comments! Thanks! 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be0a06307db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/little-snippet-group-by-in-swift-3-5be0a06307db">Little Snippets #1: Group By in Swift 3</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecting an Analytics layer]]></title>
            <link>https://medium.com/ios-os-x-development/architecting-an-analytics-layer-7cdacb5f74af?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cdacb5f74af</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mixpanel]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Thu, 23 Feb 2017 04:17:03 GMT</pubDate>
            <atom:updated>2017-02-23T16:11:45.295Z</atom:updated>
            <content:encoded><![CDATA[<h4>A better way of integrating Analytics SDK combining the Observer and the Adapter patterns.</h4><p>Suppose that you want to integrate <a href="https://developers.google.com/analytics/devguides/collection/ios/v3/?hl=en-419">Google Analytics SDK</a>. You start by following the guide, tracking the events that you want to measure. Everything is going well, because it just works, right?</p><p>But things get worse when you have to implement <a href="https://mixpanel.com/">Mixpanel Analytics</a>. You have to track some events using Google Analytics, and some other using Mixpanel. After that, you are requested to integrate <a href="https://developer.yahoo.com/analytics/">Flurry</a>, to track other events. Everything become a mess, and you have analytics code everywhere. Your code is not maintainable anymore.</p><p>You might be thinking “Hey! Wait a second… Why in the Earth would you add more than one Analytics provider to a single project? 😶” Well, I really don’t know. But I have been asked to do that a couple times before and I had to face this problem. The point here is: <strong>Reduce coupling between your external dependencies and your code</strong>. Even if you don’t have to add more than one analytics provider, it’s always a best practice to not depend on a particular implementation. Keep this in mind.</p><h3>TL;DR</h3><p>Here is the diagram for the pattern I always use to add Analytics services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*aCd7OZKnwbv2a9BGSt1kaQ.jpeg" /></figure><p><strong>Key points:</strong></p><ol><li>Although analytics SDKs have different interfaces, they have similar functionalities. So, we have to use an Adapter for each one to make them implement the same interface.</li><li>Analytics Services (the adapters) subscribe to a list of events that they are interested to be notified when fired. Each service could subscribe to a different list of events. This is important, in order to get flexibility.</li><li>There is a class, called AnalyticsManager, that is the only class you know from the application, and you notify it when an event is fired in the app.</li><li>Whenever an event is fired in the app, the AnalyticsManager notifies Analytics Services that were subscripted to that event. (Observer pattern)</li><li>You can extend this pattern if you need to add more functionalities to the adapters.</li></ol><h3>The two main parts in Analytics SDKs</h3><p>Every analytics SDK has at least two important steps in its usage:</p><ol><li>Initialize the SDK in AppDelegate</li><li>Track events in your app.</li></ol><p>It seems like a perfect fit for a protocol!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56893f4b991884a60d3235118270fc40/href">https://medium.com/media/56893f4b991884a60d3235118270fc40/href</a></iframe><p>Every Analytics SDK you integrate in your app should implement AnalyticsService protocol.</p><h3>What is an Event anyway?</h3><p>Events are anything that you would like to measure in your app. If you are wondering what events you would be tracking I really recommend you <a href="https://www.quicksprout.com/the-definitive-guide-to-growth-hacking/">this guide</a>, it’s <strong>REALLY</strong> worth reading. The most natural way to implement Events is with an enum:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44c2295439d244ba3be48ad6197bb6e7/href">https://medium.com/media/44c2295439d244ba3be48ad6197bb6e7/href</a></iframe><h3>Sample analytics service</h3><p>Here is an analytics service example, wrapping Mixpanel SDK:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5b4310ee64a837102ac30dbe8cab05e/href">https://medium.com/media/e5b4310ee64a837102ac30dbe8cab05e/href</a></iframe><h3>The core</h3><p>As I said before, from your app, you don’t know which SDKs you are really using. From the app, you only want to know two things from your analytics layer:</p><ol><li>The list of Events</li><li>The AnalyticsManager</li></ol><p>The AnalyticsManager class is often implemented as a Singleton, but it’s up to you. If you really dislike Singletons, you are free to inject it as a dependency. But if you ask me, it’s kind of over engineering. It isn’t a bad thing that your code has a dependency to your AnalyticsManager. It’s way better than depending on the concrete SDKs.</p><p>The analytics services can subscribe to AnalyticsManager specifying a list of events to which them will be observing.</p><p>Here is a sample implementation of AnalyticsManager:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de7798d91aa6dedfbb8934f163dd593c/href">https://medium.com/media/de7798d91aa6dedfbb8934f163dd593c/href</a></iframe><h3>Usage</h3><p>As I’ve said before, there are two main functionalities in Analytics SDKs. Initialization and tracking.</p><h4>Initialization</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08ad8d142f07801b08984ecfdf7d3465/href">https://medium.com/media/08ad8d142f07801b08984ecfdf7d3465/href</a></iframe><h4>Tracking</h4><p>As simple as this:</p><pre>AnalyticsManager.instance.track(event: Event.loginWithEmail)</pre><p>That’s all. 🎉</p><h3>Conclusion</h3><p>Depending on an implementation is always a bad thing. It’s always better to code against an interface, keeping flexibility and reducing coupling. Whenever you want to change the Analytics SDK that you are using, if you have followed this pattern, It would be really easy!</p><p>This pattern can be extended. If you want to add more functionalities to Analytics services, you can extend the protocol, and the AnalyticsManager class. But the çore idea would be the same.</p><p>If you know a better way of doing this, just let me know, below in the comments 👇🏼</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cdacb5f74af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/architecting-an-analytics-layer-7cdacb5f74af">Architecting an Analytics layer</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A better, exhaustive switch in UITableView protocols]]></title>
            <link>https://medium.com/ios-os-x-development/a-better-exhaustive-switch-in-uitableview-protocols-c770200c9ffa?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c770200c9ffa</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Tue, 14 Feb 2017 20:21:28 GMT</pubDate>
            <atom:updated>2017-02-14T20:21:28.617Z</atom:updated>
            <content:encoded><![CDATA[<h4>I have written a lot of not-good-looking code inside UITableViewDelegate and UITableViewDataSource. Here is a very handful trick I’ve figured out a few months ago that has worked like a charm since then.</h4><h3>The common way</h3><p>UITableView protocols are often written using expressions like these:</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>    switch indexPath.section {<br>        case 0: // Dequeue a cell for section 0<br>        case 1: // Dequeue a cell for section 1<br>        // And so on...<br>        default: fatalError(&quot;Unhandled section \(indexPath.section)&quot;)<br>    }<br>}</pre><p>I’m probably exaggerating here. I know there are some workarounds, but I bet you aren’t proud of what you are doing in these kind of situations.</p><h3>The better solution</h3><p>I prefer creating a protocol extension called ReusableViewEnum with two methods, one for obtaining all cases inside an enum implementing it and a build method that I use to obtaining a case with a section value without receiving an optional value.</p><p>Here goes the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e3c1bdc93c646043f3c80ac3549ad1/href">https://medium.com/media/d4e3c1bdc93c646043f3c80ac3549ad1/href</a></iframe><p>I hope this will help you as much as me. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c770200c9ffa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/a-better-exhaustive-switch-in-uitableview-protocols-c770200c9ffa">A better, exhaustive switch in UITableView protocols</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be Literal!]]></title>
            <link>https://medium.com/ios-os-x-development/be-literal-76e9b4389eda?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e9b4389eda</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Mon, 13 Feb 2017 18:27:32 GMT</pubDate>
            <atom:updated>2017-02-13T19:50:57.732Z</atom:updated>
            <content:encoded><![CDATA[<h4>Swift supports color literals and image literals. A brief explanation on these concepts and some usage examples.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*CPywF3oZ3yK4jK2tTVhE0A.png" /></figure><h3>Literal Colors</h3><p>We used to write UIColors like this:</p><pre>let color = UIColor(<br>    red     : 100.0/255.0,<br>    green   : 100.0/255.0, <br>    blue    : 100.0/255.0,<br>    alpha   : 1.0<br>)</pre><p>Too verbose…</p><p>Now, it’s possible to do the same in a much more visual way:</p><p>Is as easy as writting ColorLiteral and selecting the first hint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*DwIArsjRIaYJyGpDpSWIvw.png" /><figcaption>Choose Color Literal</figcaption></figure><p>Then, Xcode will open a handy color picker:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*kZWs4jrCapcp2Q2pSCFD1w.png" /><figcaption>Color picker</figcaption></figure><p>The generated color is an UIColor, with all its attributes and methods.</p><p>So you can do things like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*F7ZvUSegRzKUyqJAVk29-A.png" /></figure><p>Whenever you want to select another color, just double-click inside any of those rects and the color picker will open again.</p><h3>Literal Images</h3><p>Literal images are similar to Literal Colors. You probably already noticed that if you start typing the name of an image asset, Xcode will autocomplete (when autocomplete is working 🤔) with the asset you are looking for.</p><p>That result asset is actually an UIImage. It’s a <strong>literal </strong>UIImage.</p><p>If you do the same as with Color Literals, Xcode will open a image picker with which you can select an asset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*88csyU4vzrRTDp2gtshuLQ.png" /></figure><p>This is how the image picker looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*krVA4AnXQ3lfjEo1X0emAw.png" /><figcaption>The image picker for an image literal</figcaption></figure><p>And you can treat the generated images as any other UIImage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*t24NxT1tyvLDrM5nqO33sQ.png" /></figure><p>It’s worth noting that the generated image is not optional, which is really cool.</p><h3>Conclusion</h3><p>Color and image literals are really great. It reduces verbosity in the code and are much more visual.</p><p>I would really like to see this in other classes likeUIFont in the future!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e9b4389eda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/be-literal-76e9b4389eda">Be Literal!</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Isolating tasks in Swift, or how to create a testable networking layer.]]></title>
            <link>https://medium.com/ios-os-x-development/isolating-tasks-in-swift-or-how-to-create-a-testable-networking-layer-d0380e69f7e3?source=rss-acb23ab50f4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0380e69f7e3</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Fernando Martín Ortiz]]></dc:creator>
            <pubDate>Sun, 12 Feb 2017 07:04:02 GMT</pubDate>
            <atom:updated>2017-02-12T17:26:04.532Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a lot of shiny iOS architectures that are getting more and more hype in the last few years. As they are all valid and have good and bad parts, they all address the same thing: <strong>separate the business logic from the presentation.</strong> Today, I’m going to write about a simple concept that is applicable to your next project’s architecture, whichever architecture you are planning to use.</p><h3>A pretty common networking layer</h3><p>To explain my point, I will first talk a bit about how network layers are often implemented.</p><p>I have seen a lot of different network layers. In most of them, there is a <em>NetworkManager, ConnectionManager</em>, or something like those. There is a single class that contains every single API call in the app. While that’s valid and works fine, it fails in a core concept in software design: <strong>Single Responsibility.</strong></p><p>A ConnectionManager contains too many responsibilities to be considered a good practice. Moreover, it is often implemented as a singleton. And I don’t say singletons are necessarily bad, but they can’t be injected as dependencies, and can’t be easily mocked when testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*kkRj4SghWRhOllOOSLCifw.png" /><figcaption>Networking Layer is commonly implemented as a singleton</figcaption></figure><p>This is a very frequent practice. I’ve also seen this in MVVM, or MVP architectures.</p><h3>A different approach</h3><p>A data access layer can be implemented in a different way. Let describe the process in networking fetching:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*bmzfuTiur3j6Dvx0I41zpg.png" /><figcaption>Steps involved in a network call</figcaption></figure><p>Put in this way, a network call implies, at least, three steps:</p><ol><li><strong>Create a request</strong>: this means setting the URL, method, parameters (either in URL path or http body) and HTTP headers.</li><li><strong>Dispatch request</strong>: This is a very, very important step. The request that was created and configured in the previous step must be dispatched using URLSession, or a layer over that (for example, Alamofire).</li><li><strong>Get and parse response</strong>: It’s important that this step should be implemented separated from the previous two. This is where you should validate JSON or XML response and parse that into a valid Entity (or Model if you prefer to say).</li></ol><p>If you really want your architecture to be clean and testable, those three steps should be implemented in different objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*CvyRWIqxdOCZzBCDhdZ7MA.png" /><figcaption>Network layer should be implemented using, at least, three different components.</figcaption></figure><p>Those objects are the following:</p><ol><li><strong>Request</strong>: A Request object has everything needed for configuring a network request. It is a struct, or class that is responsible for configuring a single network request. And this is <strong>very</strong> important: <strong>One network request, one </strong>Request<strong> object.</strong></li><li><strong>NetworkDispatcher</strong>: A NetworkDispatcher is an object that is responsible of getting a Request and return a Response. It should be implemented as a protocol. You should code against that protocol and not against a concrete class (or struct), and it should never, ever, be implemented as a singleton. If you do that, this NetworkDispatcher can be replaced for a MockNetworkDispatcher that doesn’t actually make any network request, and instead getting the response from a JSON file, leading to a naturally testable architecture.</li><li><strong>NetworkTask</strong>: A NetworkTask is a subclass of the generic class Task. A task, as I will explain better in a moment, is a generic class that is responsible of getting an Input type and returning a Output type, either in a synchronous, or asynchronous way. You can implement a Task using <a href="https://github.com/ReactiveX/RxSwift">RxSwift</a>, <a href="https://github.com/ReactiveCocoa/ReactiveCocoa">ReactiveCocoa</a>, <a href="https://github.com/malcommac/Hydra">Hydra</a>, <a href="https://github.com/fmo91/microfutures">Microfutures</a>, <a href="https://github.com/fmo91/fotask">FOTask</a>, or simply using closures. It’s up to you. The important part here is the concept, not the implementation details.</li></ol><h3>Implementing a Request</h3><p>A Request is an object that is responsible of configuring everything that may be necessary to create a URLRequest.</p><p>An example of a network request may be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1149c16d8063875cb44ca26e67da4138/href">https://medium.com/media/1149c16d8063875cb44ca26e67da4138/href</a></iframe><p>As simple as it is. The important part here is that every Request is implemented as a separate object. Of course, this can be also implemented as an enum, like <a href="https://github.com/Moya/Moya">Moya</a> promotes, it depends on what you like more. I personally prefer using a more object oriented style and implementing a BaseRequest class, and subclasses like AuthenticatedRequest and more specific requests like GetAllUsersRequest or LoginRequest.</p><h3>Implementing a NetworkDispatcher</h3><p>The NetworkDispatcher is the component that is responsible of dispatching network requests.</p><p>Note: hereinafter, I will be using RxSwift in my examples, but you are free to implement them the way you prefer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295f4744fb911ed1ff766f4a29d592ec/href">https://medium.com/media/295f4744fb911ed1ff766f4a29d592ec/href</a></iframe><p>A NetworkDispatcher has a single responsibility: dispatching Request objects and returning responses.</p><p>The cool thing about using a protocol instead of a specific implementation here is that a protocol based implementation is easily interchangeable. You can have a MockNetworkDispatcher, which doesn’t actually perform any “network” operation, and instead returns a response from a JSON file, making testing much easier.</p><h3>Isolating Tasks</h3><p>Tasks are simple objects that are responsible of performing a single logic operation. It may be getting users from the backend, logging in or registering a user, for example. Tasks can be synchronous or asynchronous, but that should be transparent from the client side. I like using the convenient abstraction that is RxSwift’s Observable but a Promise, Signal, Future or a simple callback can be enough.</p><p>A simple implementation of Task can be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dec14e2d983040eef0ea64c38a4669ab/href">https://medium.com/media/dec14e2d983040eef0ea64c38a4669ab/href</a></iframe><p>I use an object oriented style, but you are free to do some cool stuff here like associated types and type erasure, that may work well too. I prefer using an object oriented style because it seems less <em>hacky </em>and it’s simpler to implement.</p><p>Every Task needs two generic parameters: a Input type, and an Output one. A Task performs an operation that includes receiving an Input object and returning an Output, maybe using an abstraction over it, like Observable.</p><p>We need to specialize Task to perform networking operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e89848f1cc9e5b1a76291e0a9be04ae/href">https://medium.com/media/6e89848f1cc9e5b1a76291e0a9be04ae/href</a></iframe><p>As you can see, a NetworkTask needs two generic types, an Input and an Output, it’s worth noting that the Input must be a Request object. A NetworkTask should be only instantiated with a NetworkDispatcher so you can easily pass a MockNetworkDispatcher when you want to test.</p><h3>Reviewing architecture</h3><p>Implementing business logic in this way helps to reduce coupling without introducing complexity and increasing testability.</p><p>This idea can be shown in a diagram as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*M2g3fJunwZVU9zR-s3ar1A.png" /><figcaption>Task based network layer</figcaption></figure><h3>Conclusion</h3><p>Isolating business logic operations in separated objects is a good practice, as it allows creating a more testable architecture. It reduces complexity and is totally independent of which architecture you are using. This can be used behind a ViewModel, Presenter, Interactor, Store, or whatever you are using to separate business logic from presentation logic.</p><p>I hope this will help you as much as me. If you have a doubt or know a better way to do this, please, leave your comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0380e69f7e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/isolating-tasks-in-swift-or-how-to-create-a-testable-networking-layer-d0380e69f7e3">Isolating tasks in Swift, or how to create a testable networking layer.</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>