<?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 Luis Piura on Medium]]></title>
        <description><![CDATA[Stories by Luis Piura on Medium]]></description>
        <link>https://medium.com/@luis-piura?source=rss-832430df706b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5R9KXBtgJwczqWvupfic0Q.jpeg</url>
            <title>Stories by Luis Piura on Medium</title>
            <link>https://medium.com/@luis-piura?source=rss-832430df706b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:59:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luis-piura/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Power Of Generics Part 2]]></title>
            <link>https://medium.com/geekculture/the-power-of-generics-part-2-56627d543c58?source=rss-832430df706b------2</link>
            <guid isPermaLink="false">https://medium.com/p/56627d543c58</guid>
            <category><![CDATA[generic-programming]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Luis Piura]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 02:18:25 GMT</pubDate>
            <atom:updated>2021-08-04T06:28:03.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*__CtBYIu0hNocdYI1iFNKQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@markusspiske?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Markus Spiske</a> from <a href="https://www.pexels.com/photo/creative-internet-designer-abstract-6212801/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong>Learning outcomes</strong></p><ol><li>Learn how and when to use protocols with associated types.</li><li>Learn how and when to use generic where clauses.</li></ol><p>In the <a href="https://medium.com/geekculture/the-power-of-generics-ba37053a95d9">previous generics post</a> we covered the main topics of Generics: Type Parameters, Generic Functions, Generic Types and Type Constraints. Now it’s time to take this to the next level 🚀. In this post we’ll cover:</p><ol><li>Associated Types: To add type parameters in our protocols.</li><li>Generic Where Clauses: To add additional conditions in our type parameters.</li></ol><h3>Associated Types</h3><p>An associated type is the way to add type parameters as part of our protocols. We can use these type parameters as properties types or as return/parameters types in our protocol functions. Another important thing is that these associated types can have constraints as well, meaning that the protocol implementation must respect any of these type constraints. Associated types allow us to have protocols with generic functions and generic properties, Why? Because the protocol implementation will be <strong>responsible</strong> for assigning an actual type to each associated type in the protocol it implements.</p><p>Let’s start with a small example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52796b843e71b8367a27e1876c1fc8f6/href">https://medium.com/media/52796b843e71b8367a27e1876c1fc8f6/href</a></iframe><p>In the previous example we created a protocol called MyProtocol and we added an associated type called MyAssociatedType. Adding associated types to a protocol is easy, we must only write the keyword associatedtype followed by our associated type name. Another important thing in our protocol is that it has a function that receives a parameter of type MyAssociatedType and returns a value of type MyAssociatedType as well. Do we now which type MyAssociatedType is? No we don’t, because this is a concern of any MyProtocol implementation. The only thing we know so far is that all the implementations must have a function with a parameter of type MyAssociatedType and this function must also return a value of type MyAssociatedType. The implementations must also follow the type constraint in our associated type: MyAssociatedType: Equatable.</p><p>Now let’s take a look at the implementations of MyProtocol, this is where things start to get more interesting. In the MyProtocolImplementation class we are telling the compiler that our associated type will be the of type EquatableEnum. How? You may ask, from the moment we implemented myFunction and we used EquatableEnum as the parameter and return types we are telling the compiler to useEquatableEnum as the associated type in this implementation. This is an implicit way and we are taking advantage of the Swift compiler type inference. We could perfectly do it in an explicit way adding a typealias as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4706b081914e8c4188d047474c9f5bc/href">https://medium.com/media/c4706b081914e8c4188d047474c9f5bc/href</a></iframe><p>Now let’s take a look to the second implementation of MyProtocol. In the first implementation we wanted to work with enums by receiving and returning an EquatableEnum. In the AnotherImplementation class, we wanted to work with a struct by receiving and returning an EquatableStruct. The same applies here, from the moment we used EquatableStruct as the parameter and return types of myFunction, we are telling the compiler that EquatableStruct will be our associated type in this implementation. As you can see thanks to the associated types we have two very diverse implementations of MyProtocol, one that works with enums and another that works with structs.</p><p>If by any reason we decided to change the return type of myFunction in any of the implementations we will get a compiler error telling us that our implementation does not conform the protocol. Why? Because both, the return and the parameter type of myFunction must be the same, we would have the same error if we only change the parameter type. If we also decide to use a type that does not conform to the Equatable protocol as parameter/return type of myFunction we will get the same error.</p><p>We are free to decide which types to use as associated types, as long as we respect any present type constraint and the functions/properties types.</p><h4>Protocols that depend on Generic Types</h4><p>So far we have covered the first scenario to use associated types in a protocol. But there’s another one, imagine that we have a protocol with either a function that receives/returns a Generic Type or a property that is a Generic Type.</p><p>Let’s see an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0402b19b85a251bdfe2f0c479cb67e98/href">https://medium.com/media/0402b19b85a251bdfe2f0c479cb67e98/href</a></iframe><p>In the previous example you can see we declared a struct called MyModel. This struct is a Generic Type that receives a type parameter called Type. Type is constrained to be an Equatable implementation. We also declared the AnotherProtocol protocol, this protocol has a function that receives a parameter of type MyModel. We just mentioned that MyModel is a Generic Type meaning that we must pass a type parameter to every MyModel declaration. To do that we had to define an associated type and we passed it to the parameter declaration. The only way to interact with Generics in a protocol is through associated types because protocols don’t allow generic parameters. Your first thought may be to pass a type parameter to the protocol as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d61734d291c79b9fbc816cb4fa962d/href">https://medium.com/media/64d61734d291c79b9fbc816cb4fa962d/href</a></iframe><p>This code will throw the next compiler error:</p><pre>Protocols do not allow generic parameters; use associated types instead</pre><p>Now you know another useful way to use associated types in a protocol. To summarize associated types will be useful in two scenarios:</p><ol><li>Have flexible implementations of a protocol by having generic parameters and return types.</li><li>To declare protocols that depend on Generic Types.</li></ol><h4>Using protocols with associated types implementations as properties types</h4><p>Let’s imagine we want to declare a class that has a property of type AnotherProtocol which is the protocol we defined in the previous example, keep in mind that this protocol has an associated type.</p><p>We couldn’t do something like this:</p><pre>let myConstant: AnotherProtocol</pre><p>The compiler will throw the next error:</p><pre>Protocol &#39;AnotherProtocol&#39; can only be used as a generic constraint because it has Self or associated type requirements.</pre><p>The only way our class can have a property of type AnotherProtocol is by creating a Generic Type that receives a type parameter constrained to be an implementation of AnotherProtocol. Let’s see an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb2b93c0203bcf32d38e2d906d11d86c/href">https://medium.com/media/bb2b93c0203bcf32d38e2d906d11d86c/href</a></iframe><p>In the previous example we created the MyClass generic type. This generic type receives theType type parameter which is constrained to implement the AnotherProtocol protocol. Then we declared a private constant of type Type, that way we’ll have access to the AnotherProtocol implementation and call any method it may have.</p><p>Now imagine that we want to create a new protocol that has a property of type AnotherProtocol. Protocols can’t have type parameters so we couldn’t do what we did in the previous example. To do this we must add an associated type and constrain it to be an implementation of AnotherProtocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e9fae67f107055e8a91115c190c83bd/href">https://medium.com/media/7e9fae67f107055e8a91115c190c83bd/href</a></iframe><h3>Generic Where Clauses</h3><p>Besides type constraints we have generic where clauses to add extra conditions to our type parameters. Generic clauses are helpful to:</p><ol><li>Compare type parameters in a generic class or function,</li><li>Compare the associated types of a type parameter with other type parameters in a generic class or function, and</li><li>Ensure that the associated types conform to certain protocols or are equal to specific types such as Int or Bool.</li></ol><p>Let’s imagine that we want to add a generic function in our class. This generic function receives a parameter of type T, T is a type parameter constrained to be an implementation of a protocol with an associated type. We want our function to work only with the protocol implementations that have an Equatable associated type. Sounds like a lot of code right? This is easy to do.</p><p>Let’s start by creating our class with the generic function and our protocol with the associated type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6757a2e3fa8d412a5cfa640cb23d62d9/href">https://medium.com/media/6757a2e3fa8d412a5cfa640cb23d62d9/href</a></iframe><p>This is all we have to do! Let’s take a look at myFunction. As you can see it receives a parameter of type T which is a type parameter constrained to be an implementation of MyProtocol. MyProtocol has an associated type and we mentioned we only want our function to work with those implementations of MyProtocol with an Equatable associated type. To add the Equatable verification we must use a where clause.</p><p>Now let’s imagine that we want to define a generic class that receives two type parameters, Type1 and Type2. Type1 must be constrained to be a MyProtocol implementation, Type2 doesn’t have any type constraint. Our generic class will have two properties: myProtocolImplementation of type Type1 and anotherProperty of type Type2. We want to create a function that compares the myProtocolImplementation stored property called myProperty of type AssociatedType with anotherProperty of type Type2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53fbc712d4dc5f23e5c619f369634cd3/href">https://medium.com/media/53fbc712d4dc5f23e5c619f369634cd3/href</a></iframe><p>There it is! As you can see we add extra conditions to our type parameters with the generic where clause. First of all we have a property called myProtocolImplementation of type Type1 and anotherProperty of type Type2. Now we want to compare myProperty contained in the MyProtocol implementation with anotherProperty and return a boolean but, How could we compare them if we don’t know which type they are? How could we compare them if we don’t know if they are Equatable? Well we can add conditions with a generic where clause to ensure this will work. The first condition helps us to ensure that both Type1.AssociatedType and Type2 are the same types. The second one on the other hand ensures that Type2 is Equatable and since Type1 is equal to Type2 we are sure that both of them are Equatable.</p><p>In this example we have more than one condition in our where clause, if we have more than one condition we must separate them by a comma as follows: where Type1.AssociatedType == Type2, Type2: Equatable</p><h4>Extensions and generic where clauses</h4><p>Sometimes we may want to add an extension to a specific type but only under certain conditions. For doing this we could use generic where clauses too.</p><p>Let’s imagine that we want to add an extension to an array but only to the [Int] arrays, this extension will have a function called sum to return the total sum of the elements in the array. Let’s start by saying that arrays in Swift are generic types that receive an Element type parameter. Now we have more context let’s create our extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e30f037795ce0c1caff2507e1073a338/href">https://medium.com/media/e30f037795ce0c1caff2507e1073a338/href</a></iframe><p>In the previous example as you can see, we are conditioning this extension only to work with those arrays whose Element is equal to Int.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56627d543c58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/the-power-of-generics-part-2-56627d543c58">The Power Of Generics Part 2</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power Of Generics]]></title>
            <link>https://medium.com/geekculture/the-power-of-generics-ba37053a95d9?source=rss-832430df706b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba37053a95d9</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[generics-swift]]></category>
            <dc:creator><![CDATA[Luis Piura]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 18:00:29 GMT</pubDate>
            <atom:updated>2021-03-09T19:00:22.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*__CtBYIu0hNocdYI1iFNKQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@markusspiske?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Markus Spiske</a> from <a href="https://www.pexels.com/photo/black-and-white-printed-textile-1936299/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong>Learning outcomes:</strong></p><ol><li>Understand what are Generic Functions and Generic Types</li><li>Understand what are Type Constraints</li><li>Use generic functions to write cleaner code</li></ol><h4>Introduction</h4><p>Generics is one of the most powerful tools in Swift. It enables us to write clean, flexible, and reusable code to avoid duplications. Great, isn’t it? Now the question is: How does this tool help me to write cleaner and flexible code? The answer is not that simple, but I promise you will be using generics with confidence after reading this article. Let’s start by saying that generics covers topics like:</p><ol><li>Generic Functions</li><li>Generic Types</li><li>Type Constraints</li><li>Associated Types</li><li>Generic Where Clauses</li></ol><p>In this article, we’ll only cover the first three items above. These three items are the core of Generics.</p><p>Now let’s dive in!</p><h4>Generic Functions</h4><p>These are functions capable of receiving any parameter type. Their return type is flexible as well. I know that this sounds nonsense in the beginning because once we write a function, it will only be allowed to receive or return certain types, and that’s true for sure, but we can also rewrite our function to become a Generic Function.</p><p>Let’s see an example. Imagine that we want to create a function that receives an item and inserts it in an array. We don’t know how to use generics so far, so let’s write a non-generic version of the function before, using an Int item and an Int array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346ffbc6f8daa165b35254d26b16a521/href">https://medium.com/media/346ffbc6f8daa165b35254d26b16a521/href</a></iframe><p>There it is! As you can see we wrote our function to receive only an Int array and an Int item. We declared our array param as an inout parameter because we don’t want to return anything yet. Now what happens, if during our development process, we find out that we require the same functionality for a String item and a String array instead? We could think of creating another inserItem function changing the types. That’s what Generics helps us to avoid, repeat the same source code with different types.</p><p>Let’s rewrite our insertItem function as a generic function. To do that let’s take another look to the non-generic version. As you can see the only requirement is that both item and array type must be the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8035a1ff875c462a9793e5b34f467345/href">https://medium.com/media/8035a1ff875c462a9793e5b34f467345/href</a></iframe><p>There we have our generic version! But let’s take a closer look to see what’s going on.</p><p>As you can see, we changed the types for both item and array to T. T is a commonly used type on Swift… wait, it doesn’t even exist on Swift. That must throw a compiler error, you may say, but it doesn’t. Why? Because we defined T as a Placeholder Type Name. We did that right after the function name, putting T between angle brackets(&lt;T&gt;). When the compiler looks this it says: “I know that this type doesn’t exist because it’s a placeholder type name. I will replace it with any other type sent by the developer on each call to this function.”</p><p>Now we can call our function either with an Int, String, or Double. Each call will replace the placeholder type name with the specified type.</p><pre><strong>var</strong> intArray = [2, 3]<br>insertItem(item: 2, in: &amp;intArray)</pre><pre><strong>var</strong> stringArray = [&quot;a string&quot;, &quot;another string&quot;]<br>insertItem(item: &quot;2&quot;, in: &amp;stringArray)</pre><p>In the previous example, the first call to insertItem replaced T with Int later; in the second call, it replaced T with String.</p><p>Something to keep in mind is that we can add as many placeholder type names as we want but, we must be careful because we need to use all of them or, the compiler will throw an error such as:</p><blockquote>Generic parameter ‘X’ is not used in function signature</blockquote><p>To add more placeholder type names, we separate them by commas as follows:</p><pre><strong>func</strong> functionName&lt;T, U, X&gt;() {}</pre><p>We have covered the use of placeholder type names in parameters so far, but as you remember, we already mentioned that we could also use them as return types. Let’s see an example. Imagine that we are working on our app’s API module and we want to decode the user fetched data in a User instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f8cb9bec14a696ae3e8239c83ef70d6/href">https://medium.com/media/5f8cb9bec14a696ae3e8239c83ef70d6/href</a></iframe><p>It works as expected, but suddenly we realized that the same decoding must be done for every fetched data in the app, meaning that we will have to create a decodeMessage function for our Message class.</p><p>Wouldn’t it be better to have a function capable of return any type? Yes, it would. We will create a placeholder type name for this and, then we will use it as the function’s return type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dad325384d915c48acf137baa0dd9d52/href">https://medium.com/media/dad325384d915c48acf137baa0dd9d52/href</a></iframe><p>Spoiler alert: our decode function throws a compiler error, but we will fix it a few lines later 🙂.</p><p>Done! As you can see, we created a new placeholder, D and, we replaced the User usages with it. Now instead of adding a function to decode each one of our types, we could call our decode function as follows:</p><pre><strong>let</strong> user: User? = decode(data: Data())<br><strong>let</strong> message: Message? = decode(data: Data())</pre><p>When the compiler reaches these lines it says: “The developer is calling a function with a generic return type, and I have to assign its return to a User/Message variable. I’ll replace the placeholder D with User/Message type”.</p><h4>Type Constraints</h4><p>Type constraints help us to add some restrictions to our placeholder type names. For example, inherit from a certain class or conform to a certain protocol.</p><p>As you remember, we mentioned before that our decode function threw a compiler error, that error is:</p><blockquote>Instance method ‘decode(_:from:)’ requires that ‘D’ conform to ‘Decodable’</blockquote><p>We added the line JSONDecoder().decode(D.self, from: data) in our decode function. That means that we are trying to decode some data into an instance of type D. Remember that we are only allowed to decode data into types that conform to the Decodable protocol. The compiler doesn’t know everything about our D placeholder type name; therefore, it isn’t sure if it can use D to decode data and, that’s why it throws the error.</p><p>To fix this issue, we must tell the compiler that D conform to the Decodable protocol. We do this by adding a type constraint to D. To add type constraints we put a colon after our placeholder type name and then, we add a class to inherit from or a protocol to conform.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65e937620eabdc75b03c45adde43844e/href">https://medium.com/media/65e937620eabdc75b03c45adde43844e/href</a></iframe><p>Boom! The error was solved! When we added &lt;D: Decodable&gt;, we constrained D to be Decodable. Now the compiler knows that it can decode data into D and, we can only assign the decode returned result to a type that conforms to the Decodable protocol. If we try to assign decode returned result to a type that doesn’t conform to the Decodable protocol, we will receive an error like this:</p><blockquote>Function ‘decode(data:)’ requires that ‘YourType’ conform to ‘Decodable’</blockquote><p>If we want to add more type constraints, we separate them by &amp;. For example: &lt;D: Decodable &amp; Equatable&gt;, meaning that the function’s return type must be Decodable <strong>and</strong> Equatable.</p><h4>Generic Types</h4><p>Generic Types are classes, structs, or enums that can work with any type. To declare generic types, we write our type name, then we put our placeholder type name between angle brackets.</p><p>Let’s see an example. Imagine that we want to encapsulate our decode function into a class. As you remember, we must have the same decode functionality for all our fetched data so, Do we create an UserDataMapper and a MessageDataMapper? We could but, we are going to use a generic type instead. Why? Because the functionality will be the same for all our fetched data regardless of the type we decode. We will create a single DataMapper instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e554c6b1b71d9513dc2d23e09efcd8ab/href">https://medium.com/media/e554c6b1b71d9513dc2d23e09efcd8ab/href</a></iframe><p>Awesome! Now we have a generic type to decode all our app’s data. Notice that now the placeholder type name is declared at a class level, meaning that it will be accessible for any other functions that we may want to add in the future. We added the same type constraint as well (Type constraints apply here as well 🚀).</p><p>How can we use our new generic type? Even though the result is the same, we access the functionality differently. Generic types require us to pass them the type(s) to be stored during the instantiation.</p><pre><strong>let</strong> dataMapper = DataMapper&lt;User&gt;()<br><strong>let</strong> user = dataMapper.decode(data: Data(json.utf8))</pre><p>Done! When we created the dataMapper object, we passed the User type(&lt;User&gt;). Now the compiler understands that this object will always replace its placeholder type name with User instances, meaning that it isn’t necessary to specify the user constant type. Additionally, we can only instantiate DataMapper with decodable types because of the type constraint.</p><p>Here we could have as many placeholders as we want as well. We must pass them each time we instantiate an object as follows:</p><pre><strong>let </strong>myObject = GenericType&lt;StoredType, AnotherStoredType&gt;()</pre><p>In the previous example, we created an instance of GenericType. We are passing two types to be stored. These types could be a class, a struct, or any other type, that fulfills the type constraints if there are any.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba37053a95d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/the-power-of-generics-ba37053a95d9">The Power Of Generics</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Asynchronous Tasks]]></title>
            <link>https://medium.com/geekculture/testing-asynchronous-tasks-ebd0dbc310ec?source=rss-832430df706b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd0dbc310ec</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Luis Piura]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 18:39:09 GMT</pubDate>
            <atom:updated>2021-03-24T23:32:21.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*u_4SyP1Fo45N40DNYlbacA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@startup-stock-photos?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Startup Stock Photos</a> from <a href="https://www.pexels.com/photo/man-wearing-black-and-white-stripe-shirt-looking-at-white-printer-papers-on-the-wall-212286/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong>Learning outcomes</strong></p><ol><li>Learn how to use XCTestExpectation clas</li><li>Take advantage of XCTestExpectation class to clean up the source code of your tests</li></ol><h4>XCTestExpectation class</h4><p>When test driving or writing tests for some tasks we usually have our given, our when, and finally our then. This is easy to picture when we create tests for synchronous tasks. What happens when we have to test driving tasks that don’t behave the same way? If a task is asynchronous, How do we get the results to make our assertions in our test? The answer is fairly simple, Apple provides us with XCTestExpectation class. According to Apple documentation, this class represents:</p><blockquote>An expected outcome in an asynchronous test.</blockquote><p>In simpler words, this class will help us to know if an asynchronous task did complete or <strong>fulfill. </strong>Expectations fulfill when:</p><ol><li>They receive a notification,</li><li>They receive an object that is successfully evaluated with a predicate,</li><li>They observe a value until it matches an expected value, or;</li><li>When as a developer you explicitly fulfill them(The ones we’ll cover in this tutorial 🙂).</li></ol><p>The XCTestCase class provides us with the expectation method to create XCTestExpectation objects. Let’s see an example:</p><pre><strong>func</strong> test_asyncFunction_didFulfill() {<br>   // Given<br>   //Any initialization</pre><pre>   //When<br>   <strong>let</strong> exp = expectation(description: &quot;Wait for asycn function to complete&quot;)</pre><pre>   //Then<br>   //Any assertion<br>}</pre><p>In the example above we create an expectation that must be explicitly fulfilled. Why? Because we only passed the description parameter. The expectation method is overloaded to cover the four ways to fulfill an expectation we’ve seen before.</p><p>Now you may be wondering, What does explicitly fulfill mean? This means that you call the fulfill method when your async task is completed. You do this to let your test know that an async task has already completed its execution.</p><pre>exp.fulfill()</pre><p>You may also be wondering: Hmm I’m calling an async task from a synchronous function, what happens if my async task takes a while? Can my test function end before my async task? If I don’t get the async task result on time, How can I do some assertions? This problem is solved with the wait method provided by the XCTestCase class as well. This method will receive an array of expectations and a timeout in seconds, meaning that your test function will be waiting until the expectations you passed are fulfilled. We define our timeout value based on the task we will perform. Maybe 3–5 seconds would fit for async tasks that require network operations such as an URL request.</p><pre><strong>func</strong> test_asyncFunction_didFulfill() {<br>   <strong>let</strong> exp1 = <br>      expectation(description: &quot;Wait for async function to complete&quot;)<br>   <strong>let</strong> exp2 = <br>      expectation(description: &quot;Wait for another async function to complete&quot;)</pre><pre>   //Async actions call</pre><pre>   // Our function is on hold and waiting for the expectations to be   fulfilled when it reaches this line<br>   <strong>wait</strong>(for: [exp1, exp2], timeout: 2.0)</pre><pre>   //Once our expectations are fulfilled our function continues its execution to this block</pre><pre>}</pre><p>If by any reason the expectations we declared in the previous example didn’t fulfill our test would fail and we’d receive the next message:</p><blockquote>Asynchronous wait failed: Exceeded timeout of 2 seconds, with unfulfilled expectations: “Wait for async function to complete”, “Wait for another async function to complete”.</blockquote><p>Another important thing about the wait method, is that it doesn’t matter in which order the expectations are fulfilled. If your test requires the expectation to fulfill in a certain order you could use the next method overload:</p><pre>func <strong>wait</strong>(for expectations: [<a href="https://developer.apple.com/documentation/xctest/xctestexpectation">XCTestExpectation</a>], <br>  timeout seconds: <a href="https://developer.apple.com/documentation/foundation/timeinterval">TimeInterval</a>, <br>enforceOrder enforceOrderOfFulfillment: <a href="https://developer.apple.com/documentation/swift/bool">Bool</a>)</pre><h4>The Authenticator class example</h4><p>The Authenticator class will help us to understand better the dynamics described before. Our class is very simple an it only has one signIn method. The signIn method will execute an async task and it has one sad path and one happy path meaning that we will write a test for each one of them.</p><pre><strong>class</strong> Authenticator {</pre><pre><strong>   enum</strong> Result: Equatable {<br>      <strong>case</strong> success<br>      <strong>case</strong> fail(Error)<br>   }</pre><pre><strong>   enum</strong> Error: Swift.Error {<br>      <strong>case</strong> imcompleteData<br>   }</pre><pre><strong>   func</strong> signIn(email: String, password: String, completion: <strong>@escaping</strong> (Result) -&gt; Void) {</pre><pre><strong>      guard</strong> !email.isEmpty, !password.isEmpty <strong>else</strong> {<br>         completion(.fail(.imcompleteData))<br>         <strong>return<br>      </strong>}</pre><pre>      completion(.success)<br>   }</pre><pre>}</pre><p>Let’s start with the sad path test, signIn method delivers an incompleteData error if either the email or the password are empty.</p><pre><strong>func</strong> test_signIn_withEmptyEmailOrPasswordDeliversIncompleteDataError() {</pre><pre>   //Given<br>   <strong>let</strong> sut = Authenticator()<br>   <strong>let</strong> email = &quot;&quot;<br>   <strong>let</strong> password = &quot;&quot;</pre><pre>   //When<br>   authenticator.signIn(email: email, <br>                        password: password) { result <strong>in<br>   </strong>}</pre><pre>}</pre><p>In the previous example, we have our given and our when so far but we are still missing a few things. Our signIn function is asynchronous meaning that we require to add an expectation and wait for this expectation to fulfill. Now the questions are:</p><ol><li>Where do we fulfill our expectation? and</li><li>Where do we wait for our expectations to complete?</li></ol><p>We know that the singIn function completes when the closure we passed as a parameter is executed, therefore, the closure is the place from where we will fulfill our expectation.</p><p>We will wait for our expectations to fulfill right after the asynchronous function invocation by calling the wait method. The wait method “freezes “ our source code until the expectations you passed as a parameter fulfill. If we call this method before our async function we will receive a timeout error in our test.</p><pre><strong>func</strong> test_signIn_withEmptyEmailOrPasswordDeliversIncompleteDataError() {</pre><pre>   <em>//Given</em><br>   <strong>let</strong> sut = Authenticator()<br>   <strong>let</strong> email = &quot;&quot;<br>   <strong>let</strong> password = &quot;&quot;</pre><pre>  <em> //When<br>   //Expectation declaration</em><br>   <strong>let</strong> exp = <br>      expectation(description: &quot;Wait for async signIn to complete&quot;)<br>   authenticator.signIn(email: email, <br>                        password: password) { result <strong>in<br>      </strong><em>//Fulfill expectation from signIn completion block</em><strong><br>      </strong>exp.fulfill()<br>   }</pre><pre>   <em>//Freeze the function execution until we fulfill our expectation<br>   //This could take a second or less</em><strong><em><br>   </em></strong>wait(for: [exp], timeout: 1.0)<br>}</pre><p>Great! We have a passing test and we ensure that we won’t get any timeout error because we are fulfilling our expectation. We are still missing our assertions to ensure we have a valid test. We will add out assertions in the singIn completion block (That will work… for now 🙂).</p><pre><strong>func</strong> test_signIn_withEmptyEmailOrPasswordDeliversIncompleteDataError() {</pre><pre>   <em>//Given</em><br>   <strong>let</strong> sut = Authenticator()<br>   <strong>let</strong> email = &quot;&quot;<br>   <strong>let</strong> password = &quot;&quot;</pre><pre>   <em>//When</em><br>   <strong>let</strong> exp = <br>      expectation(description: &quot;Wait for async signIn to complete&quot;)<br>   authenticator.signIn(email: email, <br>                        password: password) { result <strong>in<br>      </strong><em>//Then</em><br>      XCTAssertEqual(result, .fail(.imcompleteData))</pre><pre>      exp.fulfill()<br>   }</pre><pre>   wait(for: [exp], timeout: 1.0)<br>}</pre><p>Great! We cover the sad path with this test. Now let’s add a test to cover the happy path.</p><pre><strong>func</strong> test_signIn_withEmailAndPasswordAuthenticatesTheUser() {<br>   <strong>//Given<br>   let</strong> sut = Authenticator()<br>   <strong>let</strong> email = &quot;my-email@my-domain.com&quot;<br>   <strong>let</strong> password = &quot;my-password&quot;</pre><pre><strong>   //When<br>   let</strong> exp = <br>      expectation(description: &quot;Wait for async signIn to complete&quot;)<br>   authenticator.signIn(email: email, <br>                        password: password) { result <strong>in<br>      </strong>//Then<br>      XCTAssertEqual(result, .success)</pre><pre>      exp.fulfill()<br>   }</pre><pre>   wait(for: [exp], timeout: 1.0)<br>}</pre><p>Great now we have passing tests for both paths! But it seems to me that we are repeating ourselves and that we could improve both tests. As you can see both test functions are:</p><ol><li>Declaring an expectation,</li><li>Calling the signIn method,</li><li>Waiting for the expectations to fulfill, and finally,</li><li>Do some assertions.</li></ol><p>This means that we could extract all of those tasks in a separate function. Our function will receive our SUT(System under test) which in this case is an Authenticator instance, the email, the password, and finally the expected result. Due to we will do some assertions in this function we must pass the file and line as well for XCode to show us the correct line that may fail.</p><pre><strong>func</strong> test_signIn_withEmailAndPasswordAuthenticatesTheUser() {<br>   <strong>let</strong> email = &quot;my-email@my-domain.com&quot;<br>   <strong>let</strong> password = &quot;my-password&quot;</pre><pre>   expect(Authenticator(), <br>          email: email, <br>          password: password,   <br>          toCompleteWith: .success)<br>}</pre><pre><strong>func</strong> test_signIn_withEmptyEmailOrPasswordDeliversIncompleteDataError() {<br>   <strong>let</strong> email = &quot;&quot;<br>   <strong>let</strong> password = &quot;&quot;</pre><pre>   expect(Authenticator(), <br>          email: email, <br>          password: password, <br>          toCompleteWith: .fail(.imcompleteData))<br>}</pre><pre>// MARK:<strong> - Helper</strong></pre><pre><strong>private</strong> <strong>func</strong> expect(<strong>_</strong> sut: Authenticator, <br>                    email: String, <br>                    password: String, <br>                    toCompleteWith expectedResult: Authenticator.Result, <br>                    file: StaticString = <strong>#filePath</strong>, <br>                    line: UInt = <strong>#line</strong>) {</pre><pre><strong>   let</strong> exp = <br>      expectation(description: &quot;Wait for async signIn to complete&quot;)<br>   sut.signIn(email: email, password: password) { receivedResult <strong>in<br>      </strong>XCTAssertEqual(expectedResult, <br>                     receivedResult, <br>                     &quot;Expecting \(expectedResult) got \(receivedResult) instead&quot;, <br>                     file: file, <br>                     line: line)</pre><pre>      exp.fulfill()<br>   }</pre><pre>   wait(for: [exp], timeout: 1.0)<br>}</pre><p>Now our tests are cleaner and it’s easier to understand what they are doing!</p><p>There’s also another approach that we can follow. Imagine that we want to do the assertions from the test functions instead. We could create a helper method to return the signIn result. This sounds like an impossible task, isn’t it? Call an asynchronous function and then return its value. Do you remember we mentioned that calling the wait method would freeze your code? Well, that’s what will help us to get the signIn result and return it.</p><pre><strong>func</strong> test_signIn_withEmailAndPasswordAuthenticatesTheUser() {<br>   <strong>let</strong> email = &quot;my-email@my-domain.com&quot;<br>   <strong>let</strong> password = &quot;my-password&quot;</pre><pre><strong>   let</strong> receivedResult = <br>      resultFor(Authenticator(), email: email, password: password)</pre><pre>   XCTAssertEqual(receivedResult, .success)<br>}</pre><pre><strong>func</strong> test_signIn_withEmptyEmailOrPasswordDeliversIncompleteDataError() {<br>   <strong>let</strong> email = &quot;&quot;<br>   <strong>let</strong> password = &quot;&quot;</pre><pre><strong>   let</strong> receivedResult = <br>      resultFor(Authenticator(), email: email, password: password)</pre><pre>   XCTAssertEqual(receivedResult, .fail(.imcompleteData))<br>}</pre><pre>// MARK:<strong> - Helper</strong></pre><pre><strong>private</strong> <strong>func</strong> resultFor(<strong>_</strong> sut: Authenticator,<br>                       email: String,<br>                       password: String) -&gt; Authenticator.Result? {</pre><pre><strong>   let</strong> exp = <br>      expectation(description: &quot;Wait for async signIn to complete&quot;)</pre><pre><strong>   var</strong> result: Authenticator.Result?<br>   sut.signIn(email: email, password: password) { receivedResult <strong>in<br>      </strong>result = receivedResult<br>      exp.fulfill()<br>   }</pre><pre>   wait(for: [exp], timeout: 1.0)</pre><pre><strong>   return</strong> result</pre><pre>}</pre><p>We still have passing tests for both paths! As you can see the resultFor function calls the singIn function and then waits for the expectation to fulfill. Once the expectation fulfills the function can continue its execution to the return result line.</p><p>Both approaches are valid to use and help us to keep our test source code cleaner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd0dbc310ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/testing-asynchronous-tasks-ebd0dbc310ec">Testing Asynchronous Tasks</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Source Cleanup Using Pattern Matching]]></title>
            <link>https://medium.com/swlh/source-cleanup-using-pattern-matching-21961c690eda?source=rss-832430df706b------2</link>
            <guid isPermaLink="false">https://medium.com/p/21961c690eda</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Luis Piura]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 02:04:16 GMT</pubDate>
            <atom:updated>2021-02-03T22:30:05.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hT_2P5fZDpl17gmkM9SKQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@markusspiske?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Markus Spiske</a> from <a href="https://www.pexels.com/photo/matrix-background-1089438/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong>Learning outcomes</strong></p><ol><li>Learn about Swift available patterns</li><li>Learn how we can use pattern matching to clean up our source code</li></ol><h4><strong>Available patterns in Swift</strong></h4><p>The term may sound complex to you if you have worked with Swift before, and either you don’t know what patterns are or which available patterns exist in Swift. The good news is that you’ve been working with patterns and you don’t know that(yet 🙂).</p><p>Do these tasks sound familiar to you?</p><ol><li>Declare a variable/constant (<strong>Identifier pattern</strong>)</li><li>Use a wildcard to ignore an expression’s returned value (<strong>Wildcard Pattern</strong>)</li><li>Declare a tuple (<strong>Tuple Pattern</strong>)</li><li>Verify an enum value on a switch statement (<strong>Enumeration Case Pattern</strong>)</li><li>Cast a value or verify a value type using as and is operators (<strong>Type Casting Pattern</strong>)</li><li>Decompose the elements of tuple (<strong>Value-Binding Pattern</strong>)</li><li>Use .some in a switch case label to verify that an optional value was unwrapped (<strong>Optional Pattern</strong>)</li><li>Check the value of an expression in a switch case label (<strong>Expression Pattern</strong>)</li></ol><p>If at least one of the previous tasks sounds familiar to you, then good news! You’ve been working with Swift patterns.</p><p>According to Swift book:</p><blockquote>A <em>pattern</em> represents the structure of a single value or a composite value.</blockquote><p>Swift book also says that there are two kinds of patterns:</p><ol><li>Patterns that match any kind of value</li><li>Patterns that may fail to match a value</li></ol><blockquote>In Swift, there are two basic kinds of patterns: those that successfully match any kind of value, and those that may fail to match a specified value at runtime.</blockquote><h4>Patterns that match any kind of value</h4><p>We can group four Swift patterns here:</p><ol><li><strong>Wildcard Pattern:</strong> Matches and ignores any value</li><li><strong>Identifier Pattern</strong>: Matches any value and binds the matched value in a variable or constant(I would say this is the one we use the most because we are always declaring variables and constants 🙂)</li><li><strong>Value-Binding Pattern</strong>: Binds any matched value into a variable or constant(We usually use this to decompose tuple values).</li><li><strong>Tuple Pattern</strong>: Zero or more patterns separated by a comma and enclosed in parenthesis.</li></ol><p>Let’s see an example using these four patterns:</p><pre><strong>var</strong> (_, y) = (2, 2)</pre><p>In the previous example, we are decomposing and binding the values of a tuple(Tuple Pattern) that represents a cartesian point. That means we bound the coordinates in an x and y variables(Value-Binding), this allows us to access those bound values. Another important thing in the example is the use of _ to match and ignore the x coordinate. So, with this we could match any type of value regardless if it’s an integer, a string, or a float(Wildcard Pattern). The tuple containing the x and y was also bound in a var (Identifier Pattern).</p><p>Something to keep in mind is that we can add some type annotations to these patterns to constraint them to certain types. For example:</p><pre><strong>let</strong> (x, y) : (Int, Int) = (3,4)</pre><p>Now we can only bind integer values both in x and y.</p><h4>Patterns that may fail to match a value</h4><p>These patterns may fail because the runtime value we are matching against to may not be the one specified by the pattern.</p><ol><li><strong>Enumeration Case Pattern</strong>: Matches only if the enum case is the same you are checking on a swift case label, if, guard or while statements.</li><li><strong>Optional Pattern</strong>:<strong> </strong>Matches only if the value you are passing to .some in a switch case label was successfully unwrapped.</li><li><strong>Type-Casting Patterns</strong>: Matches if either the value has the same type you are casting to or the value has the same type you are verifying with the is operator.</li><li><strong>Expression Pattern</strong>: Matches only if the expression returns the value or values(a tuple) you are checking in the switch case label.</li></ol><p>Let’s see an example using these patterns.</p><p>Imagine that we have an enum that represents some of the possible HTTP responses(see Figure 1), there are three possible response cases:</p><ol><li>Successful response -&gt; Includes a code and also some data. The data could be any Decodable.</li><li>Failure, includes a code only.</li><li>Server error, includes a code only.</li></ol><p>Figure 1</p><pre><strong>enum</strong> HTTPResponse {<br>   <strong>case</strong> success(Int?, Decodable)<br>   <strong>case</strong> failure(Int?)<br>   <strong>case</strong> serverError(Int?)<br>}</pre><p>Following the same example imagine that we are required to create a function that verifies if an HTTP response can be processed as a fetch user data response.</p><p>To know if it’s possible to process a HTTP response as a fetch user data response, it must match the next criteria:</p><ol><li>The response must be successful(.success)</li><li>The response code is not nil.</li><li>The response decodable data can be cast to an UserData instance(see Figure 2).</li></ol><p>Figure 2</p><pre><strong>struct</strong> UserData: Decodable {<br>   <strong>let</strong> id: UUID</pre><pre><strong>   init</strong>(id: UUID) {<br>      <strong>self</strong>.id = id<br>   }<br>}</pre><p>Let’s get started. Our function will receive an HTTPResponse enum as a parameter. The first step is to verify that the response parameter matches the .success case, meaning that we will use Enumeration Case pattern.</p><pre><strong>func</strong> isResponseValid(response: HTTPResponse) -&gt; Bool {<br>   <strong>switch</strong> response {<br>   <strong>case</strong> .success:<br>      <strong>return</strong> <strong>true<br>   default</strong>:<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><p>The next step is to ensure that the response code is not nil. Meaning we need to access the code of the HTTPResponse which is the Int? associated value. But how do we do this? To do this, we will add the let keyword before the .success on the case label.</p><pre><strong>func</strong> isResponseValid(response: HTTPResponse) -&gt; Bool {<br>   <strong>switch</strong> response {<br>   <strong>case</strong> <strong>let</strong> .success(code, <strong>_</strong>):<br>      <strong>return</strong> <strong>true<br>   default</strong>:<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><p>Notice that there’s no need to add the let keyword before code to access it as we usually do when we access enums associated values. Adding the let keyword before the pattern allows us to bind variables in the sub-patterns we may have. Another important thing is that currently, we are using the wildcard pattern to avoid compiler warnings related to the enum’s decodable associated value. As I mentioned before, the Wildcard pattern will match anything so… we will remove the wildcard later.</p><p>Now let’s ensure that code is not nil using the Optional pattern matching. We have two ways to do that, we can either wrap code in .some or we can add the ? operator after code. For the case, we will use the second option.</p><pre><strong>func</strong> isResponseValid(response: HTTPResponse) -&gt; Bool {<br>   <strong>switch</strong> response {<br>   <strong>case</strong> <strong>let</strong> .success(code?, <strong>_</strong>):<br>      <strong>return</strong> <strong>true<br>   default</strong>:<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><p>The only pending step is to verify that theDecodable associated value is an UserData instance. How do we do this? With the Type-Casting pattern. Here we can use either as or is operators. Let’s use the is operator.</p><pre><strong>func</strong> isResponseValid(response: HTTPResponse) -&gt; Bool {<br>   <strong>switch</strong> response {<br>   <strong>case</strong> <strong>let</strong> .success(code?, <strong>is</strong> UserData):<br>      <strong>return</strong> <strong>true<br>   default</strong>:<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><p>You may wonder, when do we choose as or is operator? The answer is fairly simple. We could use is when we want to verify the type only(that’s exactly what our isResponseValid should do). The as operator on the other hand, is a casting operator and is better to use it when we want to use its returned result.</p><p>For example, imagine that our UserData struct had a name property and we want to verify that the name property is not empty. We could add user <strong>as</strong> UserData instead and use the user constant to check the name.</p><p>In this final step we want to add to this function an extra validation to the response code, so our function will only return true if the response code is 200.</p><pre><strong>func</strong> isResponseValid(response: HTTPResponse) -&gt; Bool {<br>   <strong>switch</strong> response {<br>   <strong>case</strong> <strong>let</strong> .success(code?, <strong>is</strong> UserData):<br>      <strong>return</strong> code == 200<br>   <strong>default</strong>:<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><p>We can take this function to a next level. As you can see right now, we are only matching the .success case. We could simplify this by replacing the switch statement with an if case let statement.</p><pre><strong>func</strong> isResponseValid(response: HTTPResponse) -&gt; Bool {<br>   <strong>if</strong> <strong>case</strong> <strong>let</strong> .success(code?, <strong>is</strong> UserData) = response {<br>      <strong>return</strong> code == 200<br>   } <strong>else</strong> {<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><p>Now our function looks cleaner! As you can see the if case let statement is verifying if the response parameter matches the pattern and we also keep doing the same bindings we were doing before.</p><h4>Use pattern matching to clean up our source code</h4><p>As you saw in the previous example, the isResponseValid is really easy to read and is doing validations that would look less clean if we’ve used another approach.</p><p>We’ll rewrite the isResponseValid function using a different approach:</p><pre><strong>func</strong> isResponseValid(response: HTTPResponse) -&gt; Bool {<br>   <strong>switch</strong> response {<br>   <strong>case</strong> .success(<strong>let</strong> code, <strong>let</strong> data):<br>      <strong>guard</strong> <strong>let</strong> code = code, <strong>let</strong> <strong>_</strong> = data <strong>as</strong>? UserData <strong>else</strong> {<br>         <strong>return</strong> <strong>false<br>      </strong>}</pre><pre><strong>      return</strong> code == 200<br>   <strong>default</strong>:<br>      <strong>return</strong> <strong>false<br>   </strong>}<br>}</pre><p>This code does exactly the same as the one we implemented using pattern matching but in this one, I removed all the sub-patterns(Optional and Casting patterns). I had to implement two guard let statements, one to verify that code is not nil and the other one to verify that the Decodable associated value is an UserData instance.</p><p>Pattern matching is a powerful tool for us to make our source code more readable and cleaner. It will result challenging in the beginning, however, we will be writing cleaner code and getting advantage of using it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21961c690eda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/source-cleanup-using-pattern-matching-21961c690eda">Source Cleanup Using Pattern Matching</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find potential memory leaks with automated tests]]></title>
            <link>https://levelup.gitconnected.com/find-potential-memory-leaks-with-automated-tests-7b8d78a5274f?source=rss-832430df706b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8d78a5274f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Luis Piura]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 14:42:25 GMT</pubDate>
            <atom:updated>2021-02-19T14:16:31.806Z</atom:updated>
            <content:encoded><![CDATA[<h4>Memory handling and types of references</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yo2nG22qI8-u3PdFCD46Ww.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jorgedevs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jorge Ramirez</a> on <a href="https://unsplash.com/s/photos/ram-memory?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Working in our iOS apps can be very challenging in terms of memory handling, this means we need to be very careful with the object instances allocated in memory and guarantee their correct deallocation.</p><p>As you may know instances are deallocated from memory by the <strong>ARC</strong> or <strong>Automatic Reference Counting </strong>and there are two types of references on iOS: Strong and Weak.</p><p>Strong references are the default type of reference, let’s see a simple object declaration. Imagine that we have a class called Person and we declare an object as follows:</p><pre><strong>var</strong> person = Person()</pre><p>In the previous declaration we are creating a strong reference to a Person object. Each time we a create strong reference we increase the <em>object retain count</em> by 1. What does that mean? Why is this useful? It’s useful because the ARC won’t remove an object from memory until its retain count is equal to 0.</p><p>Weak references on the other hand don’t increase the object retain count. Let’s see an example:</p><pre><strong>var</strong> person = Person()<br><strong>weak</strong> <strong>var</strong> anotherPerson: Person? = person</pre><p>In the previous example we created a <strong>weak</strong> reference to the same person object and now we have the person strong reference and the anotherPerson weak reference. This means that even when we have two references to the same person object its retain count remains in 1 because one of them is a weak reference. Other important aspect of weak references is that they are optionals because we may access them in a time where they are already deallocated from memory.</p><h3>Find retain cycles and memory leaks with testing</h3><p>A retain cycle occurs when two objects have strong reference to each other. The result is that both objects retain themselves in memory because their retain count will never be 0. As developers we need to break this cycles so that the ARC will be able to free the space in memory occupied by those objects.</p><p>Imagine that we have two objects one of type HTTPClient which is a collaborator of an UserProfileLoader object.</p><pre><strong>class</strong> UserProfileLoader {</pre><pre><strong>   private</strong> <strong>let</strong> client: HTTPClient<br>   <strong>private</strong> <strong>let</strong> url: URL</pre><pre><strong>   init</strong>(url: URL, client: HTTPClient) {<br>      <strong>self</strong>.url = url<br>      <strong>self</strong>.client = client<br>   }</pre><pre><strong>   enum</strong> Error: Swift.Error {<br>      <strong>case</strong> invalidProfileData<br>      <strong>case</strong> connectivity<br>   }</pre><pre><strong>   enum</strong> Result: Equatable {<br>      <strong>case</strong> success(UserProfile)<br>      <strong>case</strong> failure(Error)<br>   }</pre><pre><strong>   func</strong> loadProfile(completion: <strong>@escaping</strong> (Result) -&gt; Void) {<br>      client.get(from: url) { data <strong>in<br>         let</strong> result = <strong>self</strong>.map(data: data)<br>         completion(result)<br>      }<br>   }</pre><pre><strong>   func</strong> map(data: HTTPClientResult) -&gt; Result {<br>      <strong>return</strong> .success(UserProfile(id: &quot;an-user-id&quot;))<br>   }</pre><pre>}</pre><pre><strong>enum</strong> HTTPClientResult {<br>   <strong>case</strong> success(Data)<br>   <strong>case</strong> failure(Error)<br>}</pre><pre><strong>protocol</strong> HTTPClient {</pre><pre><strong>   func</strong> get(from url: URL, <br>            completion: <strong>@escaping</strong> (HTTPClientResult) -&gt; Void)</pre><pre>}</pre><pre><strong>class</strong> HTTPClientSpy: HTTPClient {</pre><pre><strong>   var</strong> completion: ((HTTPClientResult) -&gt; Void)? = <strong>nil</strong></pre><pre><strong>   func</strong> get(from url: URL, <br>            completion: <strong>@escaping</strong> (HTTPClientResult) -&gt; Void) {<br>       <br>       <strong>self</strong>.completion = completion<br>   }</pre><pre>}</pre><pre><strong>struct</strong> UserProfile: Equatable {<br>   <strong>var</strong> id: String<br>}</pre><p>In the previous example our UserProfileLoader has a method called loadProfile that invokes the get method in the composed client of type HTTPClient. As you can see the implementation of get in our HTTPClientSpy stores a closure in a property called completion, this makes our closure accesible from our testings.</p><p>The above implementation contains a retain cycle for sure, but why and where? is not that obvious at a first glance isn’t it?, let’s take another look. The UserProfileLoader has a strong reference to the HTTPClient object, where? on the client property, the HTTPClient implementation on the other hand has a strong reference to the UserProfileLoader as well, where? there isn’t any UserProfileLoader stored in our HTTPClientSpy you may say, but there’s one for sure. Let’s take another look to our get method, this method is storing the received closure in the completion property, this closure has a strong reference to our UserProfileLoader object, where? in the map method invocation. As you can see we added a strong reference with the explicit use of self.</p><p>These kinds of mistakes are usually found in a lot of codebases, sometimes they are not that obvious and we are not exempt of falling into them. We can reduce that chances by using automated tests, but how? We must be sure that <strong>SUT</strong> or <strong>System Under Test</strong> and its collaborators are properly deallocated.</p><p>Let’s start by writing out first test, this test will cover the successful path. In this example our SUT will be our UserProfileLoader instance.</p><pre><strong>func</strong> test_load_withSuccesfulClientResponseDeliversSuccesLoadingResult() {</pre><pre><strong>   let</strong> url = URL(string: &quot;https://a-url.com&quot;)!<br>   <strong>let</strong> client = HTTPClientSpy()<strong><br>   let</strong> sut = UserProfileLoader(url: url, client: client)</pre><pre>}</pre><p>We have our givens, now we have to store our loading result in some place to make some assertions, as you remember the loadProfile method will complete with a closure of type <strong>(Result) -&gt; Void</strong>. Let’s store that result in our test.</p><pre><strong>func</strong> test_load_withSuccesfulClientResponseDeliversSuccesLoadingResult() {</pre><pre><strong>   let</strong> url = URL(string: &quot;https://a-url.com&quot;)!<br>   <strong>let</strong> client = HTTPClientSpy()<strong><br>   let</strong> sut = UserProfileLoader(url: url, client: client)</pre><pre><strong>   var</strong> capturedResults = [UserProfileLoader.Result]()<br>   sut.loadProfile { capturedResults.append($0) }</pre><pre>}</pre><p>In our previous test the load closure will never be executed, why? Because our loadProfile is calling the implementation of get, do you remember what does the implementation of get do? In our HTTPClientSpy instance the get method stores the received closure in a property. We must call that stored completion block in the test to get the result.</p><pre><strong>func</strong> test_load_withSuccesfulClientResponseDeliversSuccesLoadingResult() {</pre><pre><strong>   let</strong> url = URL(string: &quot;https://a-url.com&quot;)!<br>   <strong>let</strong> client = HTTPClientSpy()<strong><br>   let</strong> sut = UserProfileLoader(url: url, client: client)</pre><pre><strong>   var</strong> capturedResults = [UserProfileLoader.Result]()<br>   sut.loadProfile { capturedResults.append($0) }</pre><pre>   client.completion?(.success(Data()))</pre><pre>}</pre><p>Now we can start to make some assertions with the capturedResultsarray. Our loadProfile method will always complete with a successful result containing and instance of UserProfile. That’s what we must expect in our test then.</p><pre><strong>class</strong> MemoryLeaksTests: XCTestCase {</pre><pre><strong>   func</strong> test_load_withSuccesfulCallDeliversSuccesLoadingResult() {</pre><pre><strong>      let</strong> url = URL(string: &quot;https://a-url.com&quot;)!<br>      <strong>let</strong> client = HTTPClientSpy()<strong><br>      let</strong> sut = UserProfileLoader(url: url, client: client)</pre><pre><strong>      let</strong> expectedResult: UserProfileLoader.Result =<br>          .success(UserProfile(id: &quot;an-user-id&quot;))</pre><pre><strong>      var</strong> capturedResults = [UserProfileLoader.Result]()<br>      sut.loadProfile { capturedResults.append($0) }<br>      client.completion?(.success(Data()))</pre><pre>      XCTAssertEqual(capturedResults, [expectedResult])</pre><pre>   }</pre><pre>}</pre><p>Great! We have a passing test! Does that test ensures the correct deallocation of our SUT and its collaborators? Not yet. Let’s add some assertions to be sure that our test are deallocated from memory.</p><p>Our MemoryLeaksTests class extends from the XCTestCase class, the XCTestCase class provides us with a method called <a href="https://developer.apple.com/documentation/xctest/xctestcase/2887226-addteardownblock">addTearDownBlock</a>, this method receives a block of type <strong>() -&gt; Void</strong> that will be executed each time a test function ends. We could add a tear down block right after the creation of our SUT and its collaborators.</p><pre><strong>class</strong> MemoryLeaksTests: XCTestCase {</pre><pre><strong>   func</strong> test_load_withSuccesfulCallDeliversSuccesLoadingResult() {</pre><pre><strong>      let</strong> url = URL(string: &quot;https://a-url.com&quot;)!<br>      <strong>let</strong> client = HTTPClientSpy()<strong><br>      let</strong> sut = UserProfileLoader(url: url, client: client)</pre><pre>      addTeardownBlock { [<strong>weak</strong> sut, <strong>weak</strong> client] <strong>in<br>         </strong>XCTAssertNil(client, &quot;Instance has not been deallocated&quot;)<br>         XCTAssertNil(sut, &quot;Instance has not been deallocated&quot;)<br>      }</pre><pre><strong>      let</strong> expectedResult: UserProfileLoader.Result =<br>          .success(UserProfile(id: &quot;an-user-id&quot;))</pre><pre><strong>      var</strong> capturedResults = [UserProfileLoader.Result]()<br>      sut.loadProfile { capturedResults.append($0) }<br>      client.completion?(.success(Data()))</pre><pre>      XCTAssertEqual(capturedResults, [expectedResult])</pre><pre>   }</pre><pre>}</pre><p>Now we have our blocks in place. Notice that in our blocks we added weak references to the sut and client instances to avoid increasing their retain counts even more. Now our green test is not green anymore because the teardown blocks assertions are failing.</p><p>To remove the retain cycle we could avoid the explicit use of self in our loadProfile method. We have some options:</p><ol><li>Use a <strong>weak</strong> reference in our closure and add guard let block to unwrap the result;</li><li>Turn our map method into a static method; or</li><li>Move the map method to a mapper class static method</li></ol><p>For this example I’ll use the second option just to break the retain cycle and to have a passing test.</p><pre><strong>func</strong> loadProfile(completion: <strong>@escaping</strong> (Result) -&gt; Void) {<br>   client.get(from: url) { data <strong>in<br>      </strong>completion(UserProfileLoader.map(data: data))<br>   }<br>}</pre><pre><strong>static</strong> <strong>func</strong> map(data: HTTPClientResult) -&gt; Result {<br>   <strong>return</strong> .success(UserProfile(id: &quot;an-user-id&quot;))<br>}</pre><p>Now our test is passing but… it looks a little bit messy so let’s refactor our test to clean it a little bit. Imagine that we want to add more test functions(trust me we’ll want it 🙂), we would be creating our SUT and its collaborators and also adding the tear down blocks for each one of them, meaning that we would be repeating ourselves.</p><p>To refactor this test we will create some factory methods. The first one will be our makeSUT method, this method will return the SUT and its collaborators.</p><pre><strong>class</strong> MemoryLeaksTests: XCTestCase {</pre><pre><strong>   func</strong> test_load_withSuccesfulCallDeliversSuccesLoadingResult() {</pre><pre>      <strong>let</strong> (sut, client) = <br>          makeSUT(url: URL(string: &quot;https://a-url.com&quot;)!)<br>      <strong>let</strong> expectedResult: UserProfileLoader.Result =<br>          .success(UserProfile(id: &quot;an-user-id&quot;))</pre><pre>      <strong>var</strong> capturedResults = [UserProfileLoader.Result]()<br>      sut.loadProfile { capturedResults.append($0) }<br>      client.completion?(.success(Data()))</pre><pre>      XCTAssertEqual(capturedResults, [expectedResult])<br>   }</pre><pre>   // MARK:<strong> - Helpers</strong></pre><pre><strong>   func</strong> makeSUT(url: URL,<br>                file: StaticString = <strong>#filePath</strong>,<br>                line: UInt = <strong>#line</strong>) -&gt; (sut: UserProfileLoader, client: HTTPClientSpy) {</pre><pre><strong>      let</strong> client = HTTPClientSpy()<br>      <strong>let</strong> sut = UserProfileLoader(url: url, client: client)<br>      addTeardownBlock { [<strong>weak</strong> sut, <strong>weak</strong> client] <strong>in<br>         </strong>XCTAssertNil(client, <br>                      &quot;Instance has not been deallocated&quot;, <br>                      file: file, <br>                      line: line)<br>         XCTAssertNil(sut, <br>                      &quot;Instance has not been deallocated&quot;, <br>                      file: file, <br>                      line: line)<br>      }</pre><pre><strong>      return</strong> (sut, client)</pre><pre>   }</pre><pre>}</pre><p>Now we have a cleaner test! Our test is more readable and we have another great advantage! Which one apart from cleaner test? you may say, If you take a look to the makeSUT factory method, this method is adding our tear down blocks, that means that every test that creates the SUT using this method will be automatically validating that the SUT and its collaborators are correctly deallocated from memory once the test is completed. If the SUT and its collaborators were not deallocated from memory the test will show the error on the makeSUT call because we are passing the file and line parameters to the XCTAssertNil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*OAiMyVvA0WIRf21eIpalVw.png" /></figure><p>Following this approach will give us the confidence to refactor and validating that we are doing a correct memory management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8d78a5274f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/find-potential-memory-leaks-with-automated-tests-7b8d78a5274f">Find potential memory leaks with automated tests</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>