<?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 Lubaba Hasnain on Medium]]></title>
        <description><![CDATA[Stories by Lubaba Hasnain on Medium]]></description>
        <link>https://medium.com/@lubabahasnain93?source=rss-4e72c575efbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WnZB0W1pecsBl1laHmjnmw.jpeg</url>
            <title>Stories by Lubaba Hasnain on Medium</title>
            <link>https://medium.com/@lubabahasnain93?source=rss-4e72c575efbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:13:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lubabahasnain93/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[Design Patterns in Swift: Part II— Behavioral Design Pattern]]></title>
            <link>https://medium.com/@lubabahasnain93/design-patterns-in-swift-part-ii-behavioral-design-pattern-5e4e5f13ccf7?source=rss-4e72c575efbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4e5f13ccf7</guid>
            <category><![CDATA[swift-playgrounds]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Lubaba Hasnain]]></dc:creator>
            <pubDate>Tue, 01 Jan 2019 16:17:58 GMT</pubDate>
            <atom:updated>2019-01-01T16:36:58.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQtDo7cPJx1Jv_29Q8OYFg.jpeg" /></figure><p>In the first article of the series, I discussed about <a href="https://medium.com/@lubabahasnain93/design-patterns-in-swift-part-i-creational-design-pattern-18d4be82092f">Creational Design Patterns</a>. <br>Now I will describe another set of patterns called <strong>Behavioral Design Patterns.</strong></p><blockquote><strong>Behavioral Design Pattern</strong> deals with how objects interact. It describes how objects communicates with each other and how the steps of a task is broken among different objects so as to provide more flexibility and make the code more testable.</blockquote><p>Let us jump to these 10 behavioral design patterns:</p><h3><strong>1. Chain of Responsibility</strong></h3><p><strong>Chain of Responsibility</strong> is a behavioral design pattern that let us pass the requests among a chain of handlers where each handler decides either to process the request or to pass it along the chain.</p><p>There is an enum called <strong><em>Level</em></strong> to breakdown the Sports management into three levels: state, national &amp; international. First let us create a class called <strong><em>Sports</em></strong> which will just hold the current sports management level.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e684065df2d56df548cae8e1e404590/href">https://medium.com/media/5e684065df2d56df548cae8e1e404590/href</a></iframe><p>Then we have the protocol called <em>GameManagement</em> which can pass the responsibility along the handler chain. The classes <strong><em>StateSportsTeam</em></strong>, <strong><em>NationalSportsTeam</em></strong> &amp; <strong><em>InternationalSportsTeam</em></strong> implement this protocol. If the sports level does not belong to their management, they pass the responsibility to the higher management (or the handlers chain).</p><p>Running the code in the playground:</p><pre><strong>let</strong> stateSportsTeam = StateSportsTeam()<br><strong>let</strong> nationalSportsTeam = NationalSportsTeam()<br><strong>let</strong> internationalSportsTeam = InternationalSportsTeam()</pre><pre>stateSportsTeam.nextLevelManagement = nationalSportsTeam<br>nationalSportsTeam.nextLevelManagement = internationalSportsTeam</pre><pre><strong>let</strong> sports1 = Sports(level: Level.international)<br>stateSportsTeam.manage(sports: sports1)</pre><pre><strong>let</strong> sports2 = Sports(level: Level.national)<br>stateSportsTeam.manage(sports: sports2)</pre><pre><strong>let</strong> sports3 = Sports(level: Level.state)stateSportsTeam.manage(sports: sports3)</pre><pre><strong><em>Output:</em></strong><br><strong>Managed by International Sports Management<br>Managed by National Sports Management<br>Managed by State Sports Management</strong></pre><h3>2. <strong>Command Pattern</strong></h3><p>In Command pattern, the class that executes the command(called <strong><em>Invoker</em></strong>) is decoupled from the class which produces the command(<strong><em>ConcreteCommand</em></strong>) and from the class that knows how to perform it (<strong><em>Receiver</em></strong>).</p><p>Let us follow the below example.<br>The <strong><em>Invoker</em></strong><em> </em>is the heart of the pattern. It<em> </em>can call the<em> </em><strong><em>execute()</em></strong> method to perform an action without being aware of the concrete class <strong><em>ConcreteCommand</em></strong> and what it does. It only knows about the abstract type <strong><em>Command</em></strong><em> </em>protocol.</p><p><strong><em>ConcreteCommand</em></strong><em> </em>class conforms to <strong><em>Command</em></strong> protocol and takes and instance of <em>Receiver </em>object in the initializer. It then calls the receiver object to perform certain task/operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91da10073f0cd120cd5747816284d7d1/href">https://medium.com/media/91da10073f0cd120cd5747816284d7d1/href</a></iframe><p><strong><em>Receiver</em></strong><em> </em>is the class that does the actual work. It can be any business logic, database request or network operation.<br><strong><em>Client</em></strong> is the class that creates the <strong><em>ConcreteCommand</em></strong> object and pass it into the invoker. It can be your view controller class.</p><p>Trying out the code:</p><pre><strong>let</strong> client = Client()<br>client.showPattern()</pre><pre><strong><em>Output:<br>red</em></strong></pre><h3>3. Iterator Pattern</h3><p>This pattern is used for iterating over a collection of elements. It does not expose the data structure used in implementing it (array, dictionary or linked list) rather it gives an interface which iterates over the collection of elements without exposing its underlying representation.</p><blockquote><strong>Ever wondered how for-in loop works in Swift? </strong><br>Swift has a built-in <em>Sequence </em>protocol which helps in creating iterators. The <em>Sequence </em>protocol gives sequential access to its elements by creating an iterator. IteratorProtocol is a type that supplies the values of a sequence one at a time.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c75a696cefd5b654cea499b1672cbc4/href">https://medium.com/media/6c75a696cefd5b654cea499b1672cbc4/href</a></iframe><p>The class <strong><em>MyBestFilms</em></strong> implements the Sequence protocol that creates a custom iterator. Every time the <strong><em>next()</em></strong> function is called, it returns the next element and store the current index. <br>This is absolutely great! You can create your own custom sequence.</p><p>Illustrating the point:</p><pre><strong>let</strong> myFilms = MyBestFilms(films: [&quot;Godfather Trilogy&quot;, &quot;Silence of the Lambs&quot;, &quot;Call Me By Your Name&quot;])</pre><pre><strong>for</strong> film <strong>in</strong> myFilms {<br>  print(film)<br>}</pre><pre><strong>Output:<br>Godfather Trilogy<br>Silence of the Lambs<br>Call Me By Your Name</strong></pre><h3>4. Mediator Pattern</h3><p>Let us take a scenario when two or more classes has to interact with each other. Instead of directly communicating with each other and getting the knowledge of their implementation, they can talk via a <strong><em>Mediator</em></strong>.</p><p>So, for example, there are two teams competing with each other to get selected in the finals of a game. Team A is <em>The Avengers </em>and Team B is <em>The League of Extraordinary Gentlemen.<br></em>So instead of directly communicating with each other, they register to the mediator object and then they can send messages to each other via Mediator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5555d4ab69c44e750d5b7617cf9fe3a3/href">https://medium.com/media/5555d4ab69c44e750d5b7617cf9fe3a3/href</a></iframe><p>Two protocols are defined: <br>Protocol <strong><em>Receiver</em></strong><em> </em>implemented by the Teams which has the abstract <strong><em>receive</em></strong> method that takes a message as a parameter.</p><p>Protocol <strong><em>Sender</em></strong><em> </em>implemented by the Mediator which has the abstract method <strong><em>send</em></strong> that takes message and a Receiver type object as a parameter. <br>Our mediator iterates through each team in its list of teams. If the team A is sending the request, team B receives it and vice-versa.</p><p>Notice that the teams are not aware of each other. There is no reference of team A in team B and team B in team A.</p><blockquote>Note: <a href="http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html">NSNotificationCenter</a> uses <em>Mediator Pattern</em></blockquote><p>Let us try it out.</p><pre><strong>let</strong> mediator = Mediator()<br><strong>let</strong> teamA = TeamA(name: &quot;The Avengers&quot;)<br><strong>let</strong> teamB = TeamB(name: &quot;The League of Extraordinary Gentlemen&quot;)</pre><pre>mediator.register(candidate: teamA)<br>mediator.register(candidate: teamB)</pre><pre>mediator.send(message: &quot;Selected for final! from \(teamA.name)&quot;, sender: teamA)<br>mediator.send(message: &quot;Not selected for final! from \(teamB.name)&quot;, sender: teamB)</pre><pre><strong>Output:<br>The League of Extraordinary Gentlemen received: Selected for final! from The Avengers</strong></pre><pre><strong>The Avengers received: Not selected for final! from The League of Extraordinary Gentlemen</strong></pre><h3>5. Memento Pattern</h3><p><em>Memento Pattern</em> captures the current state of an object and store it in such a way that you can retrieve it at a later time when you would like to return to the previous state.</p><p>We’ve a protocol <strong><em>Memento</em></strong><em> </em>with default implementation of <strong><em>save</em></strong><em> </em>and <strong><em>retrieve</em></strong><em> </em>methods.<br><strong><em>save</em></strong><em> </em>saves the <strong><em>`state`</em></strong> property with key in UserDefaults.<br><strong><em>retrieve</em></strong><em> </em>restores the <strong><em>`state`</em></strong> property using key from UserDefaults.<br><strong><em>state</em></strong><em> </em>is of type dictionary which stores the value with a unique key<br><strong><em>key</em></strong><em> </em>is used to retrieve the corresponding value from the state</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/185cc2d87560a11bd8007884455332b9/href">https://medium.com/media/185cc2d87560a11bd8007884455332b9/href</a></iframe><p>Class <strong><em>Profile</em></strong> will implement <strong><em>Memento</em></strong> protocol. By implementing this protocol, we can save the entire class to persistent storage and then retrieve the state at later time.</p><p>Trying on playground:</p><pre><strong>var</strong> profile = Profile(name: &quot;Nick Jonas&quot;, age: 36, key: &quot;NickProfile&quot;)<br>profile.saveDetails()</pre><pre>profile = Profile(name: &quot;Priyanka Chopra&quot;, age: 26, key: &quot;PriyankaProfile&quot;)<br>profile.saveDetails()</pre><pre><strong>let</strong> profile1Details = Profile(key: &quot;PriyankaProfile&quot;)<br><strong>let</strong> profileState = profile1Details.retrieveDetails()<br>print(profileState)</pre><pre><strong>Output:<br>[&quot;age&quot;: 26, &quot;name&quot;: Priyanka Chopra]</strong></pre><h3>6. Observer Pattern</h3><p>In this pattern, one object notifies other objects about its state change i.e. when the state of one object changes, other object which are subscribed to it gets notified about the state change.</p><p>So, it is a one-to-many relationship. The object whose state changes are called <strong><em>observable</em></strong> or <strong><em>subject</em></strong> and the objects which subscribe for changes on the observable are called <strong><em>observers</em></strong><em>.</em></p><p>The Observable protocol has three abstract methods: <br><em> </em><strong><em>add</em></strong><em>: for adding observers<br></em> <strong><em>remove</em></strong><em>:</em> for removing observers<br><strong><em>notify</em></strong><em>:</em> for notifying all observers about its state change</p><p>Assume a scenario where an Apple Seller has to notify her customers about new apples arriving in her shop. As soon as new apples arrive, she notifies the customer who are added in the loop about the new apples. She can also remove the customers from the loop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51460255f1b909639e06160f829067e7/href">https://medium.com/media/51460255f1b909639e06160f829067e7/href</a></iframe><p><strong><em>AppleSeller</em></strong> is the class that implements the <strong><em>Observable</em></strong><em> </em>protocol. When the <strong><em>appleCount</em></strong> variable value changes, it calls the <strong><em>notify()</em></strong> method to notify the customers who are added to it.<br>Customer is a class that listens to the changes in the <strong><em>appleCount</em></strong> variable. As soon as this variable’s value changes, the customer gets updated via the <strong><em>update()</em></strong><em> </em>method.</p><p>Here’s the usage:</p><pre><strong>let</strong> appleSeller = AppleSeller()</pre><pre><strong>let</strong> james = Customer(name: &quot;James&quot;, observable: appleSeller, customerId: 101)<br><strong>let</strong> david = Customer(name: &quot;David&quot;, observable: appleSeller, customerId: 102)</pre><pre>appleSeller.appleCount = 10<br>appleSeller.remove(customer: james)<br>appleSeller.appleCount = 20</pre><pre><strong>Output:<br>Hurry James! 10 apples arrived at shop.<br>Hurry David! 10 apples arrived at shop.<br>Hurry David! 20 apples arrived at shop.</strong></pre><h3>7. State Pattern</h3><p>State design pattern is a design pattern where an object needs to change his behavior when its internal state has changed. It appears as if the object changed its class.</p><p>First we define a protocol called <strong><em>Human</em></strong> which has a getter for getting the current state and a setter for setting the current state of the object.<br>The state will be carried by a class called <strong><em>Man</em></strong>.<br>The protocol <strong><em>ManState</em></strong> has three states: <strong><em>stand()</em></strong>,<em> </em><strong><em>walk()</em></strong><em> </em>and<em> </em><strong><em>run()</em></strong>. It is implemented by three concrete classes: <strong><em>StandingState</em></strong>, <strong><em>WalkingState</em></strong> and <strong><em>RunningState</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5808299d280576e300480e678c9a05e/href">https://medium.com/media/c5808299d280576e300480e678c9a05e/href</a></iframe><p>To illustrate the point of this pattern:</p><pre><strong>let</strong> man = Man()</pre><pre><strong>let</strong> walkingState = WalkingState(man)<br>walkingState.walk()<br>print(man.getState().toString())</pre><pre><strong>let</strong> runningState = RunningState(man)<br>runningState.run()<br>print(man.getState().toString())</pre><pre><strong>Output:<br>The man is in walking position<br>Walking State<br>The man is in running position<br>Running State</strong></pre><blockquote>You can see from the results that calling the same method on the same instance of a class is producing different results.</blockquote><h3>8. Strategy Pattern</h3><p>This pattern defines a family of algorithms, each one of them written in a separate class allowing us to select which algorithm to execute at runtime.</p><p>We define a protocol called <strong><em>Strategy</em></strong> and it has a method named <strong><em>convert</em></strong> to convert the number into a format decided by the user at runtime.<br>We implement two algorithms: <strong><em>BinaryStrategy</em></strong><em> </em>to convert number to binary and <strong><em>HexStrategy</em></strong><em> </em>to convert number to hex.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95552201d335d781408d4d9d86f1077f/href">https://medium.com/media/95552201d335d781408d4d9d86f1077f/href</a></iframe><p>The class <strong><em>Convert</em></strong> has a property called <strong><em>Strategy</em></strong> so any of the classes can be used which implement the Strategy protocol. <br>At runtime we pass the the class instance of type <strong><em>Strategy</em></strong> depending upon we choose the algorithm that does binary number conversion or we choose the algorithm that does hex number conversion.</p><p>Running the above code:</p><pre><strong>let</strong> binaryConvert = Convert(number: 2, strategy: BinaryStrategy())<br>binaryConvert.update()</pre><pre><strong>let</strong> hexConvert = Convert(number: 123, strategy: HexStrategy())<br>hexConvert.update()</pre><pre><strong>Output:<br>Binary is 10<br>Hex is 7b</strong></pre><h3>9. Template Pattern</h3><p>In this pattern, the base class defines the template of an algorithm and let the subclass implement these abstract methods in the same way they are defined in the base class without changing the overall structure.</p><p>In Template method pattern, classes interact using only base classes that implements the algorithm steps. In swift, we’ll use interface delegation for that.<br>Suppose, in an office there is an office schedule for all the employees.<br>Protocol <strong><em>Office</em></strong> has an abstract method called <strong><em>officeSchedule()</em></strong>. Class <strong><em>XYZOffice</em></strong> will implement this protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf7dd95aa738c846e7a3ab0d83d817b2/href">https://medium.com/media/bf7dd95aa738c846e7a3ab0d83d817b2/href</a></iframe><p>All the employees have shared responsibilities like work and get payment for their work.<br>Protocol Employee has two abstract methods: <strong><em>work()</em></strong> and <strong><em>getPaid()</em></strong><em>.<br></em>Different employees will do different kind of work but still they follow the same template of working and getting paid.</p><p>Illustrating the point:</p><pre><strong>let</strong> xyzOfficeDev = XYZOffice(employee: Developer())<br><strong>let</strong> xyzOfficeManager = XYZOffice(employee: ProductManager())</pre><pre>xyzOfficeDev.officeSchedule()<br>xyzOfficeManager.officeSchedule()</pre><pre><strong>Output:<br>Developer has worked 40 hours/week this month<br>Developer has earned Rs 50,000 this month<br>Product Manager has worked 55 hours/week this month<br>Product Manager has earned Rs 80,000 this month</strong></pre><h3>10. <strong>Visitor</strong> Pattern</h3><p>Visitor design pattern separates the algorithms from the objects on which they operate i.e. the operational logic is moved from each elements of a group into a new class. The new class will perform the operational logic using the data from those elements.</p><p>Each element accepts a visitor which does the logic in another class. So the structure of the visited class is not changed at all.<br>Each country should be able to accept a visitor. So we declare a protocol named <strong><em>Country</em></strong> which has a method to accept a visitor.<br>The visitor is named <strong><em>CountryVisitor</em></strong><em>.<br></em>Let us define concrete classes for our <strong><em>Country</em></strong>.</p><p>And now let’s implement the <strong><em>CountryVisitor</em></strong> protocol and showcase this design pattern.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a984c0fe0601efc40974757d3cc967/href">https://medium.com/media/23a984c0fe0601efc40974757d3cc967/href</a></iframe><p>Running in the playground</p><pre><strong>let</strong> countries: [Country] = [India(), Brazil(), China()]<br><strong>let</strong> names = countries.map { (country: Country) -&gt; String <strong>in<br>    let</strong> visitor = CountryVisitorName()<br>    country.accept(visitor: visitor)<br>    <strong>return</strong> visitor.visitorName<br>}<br>print(names)</pre><pre><strong>Output:<br>[&quot;Chen&quot;, &quot;Ramesh&quot;, &quot;Antonio&quot;]</strong></pre><p><a href="https://github.com/LH17/Behavioral-Design-Pattern">Here is the link to the playground files.</a></p><p>All Behavioral Design Patterns in Swift are fully covered in this article with working examples.</p><p>Behavioral Design pattern focuses on communication and interaction of objects, powerful dynamic interfaces and object composition which should be used for designing softwares.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4e5f13ccf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns in Swift: Part I — Creational Design Pattern]]></title>
            <link>https://medium.com/@lubabahasnain93/design-patterns-in-swift-part-i-creational-design-pattern-18d4be82092f?source=rss-4e72c575efbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/18d4be82092f</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift-playgrounds]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Lubaba Hasnain]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 06:07:39 GMT</pubDate>
            <atom:updated>2019-01-01T16:52:49.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdE8Obi0atnvYEDb6hmdoA.png" /></figure><p>Design patterns are different solutions to software engineering problems. Softwares can be built without them<strong> </strong>but its a lot harder. <br>I will be releasing a three-part series regarding design pattern. In this post, I will be discussing about <strong>Creational design patterns.</strong></p><p><strong>Creational design patterns</strong> are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or in added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.<br>Source: <a href="http://en.wikipedia.org/wiki/Creational_pattern">wikipedia.org</a></p><p>Here we are going to discuss the five creational design patterns and how we can use them in swift.</p><h3><strong>The Prototype Pattern</strong></h3><p>This type of design pattern is used to instantiate a new object by cloning an existing object called <strong>prototype.</strong></p><p>You would see an abstract <strong>clone</strong> function of the<strong><em> Fruit protocol</em></strong> implemented by the <strong><em>Apple class</em></strong> that actually returns the current object itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94b991c3ac1de39c507c3383a4d04e20/href">https://medium.com/media/94b991c3ac1de39c507c3383a4d04e20/href</a></iframe><p>Let us run the above code in the playground.</p><pre>// Create a prototype<br>let prototype = Apple(count: 4)</pre><pre>// Create a copy of existing object<br>let redApple: Apple = prototype.clone() as! Apple<br>redApple.count // 4</pre><pre>// add own properties<br>redApple.set(price: &quot;$2&quot;)<br>redApple.price // $2</pre><pre>// Create a copy of existing object<br>let greenApple: Apple = prototype.clone() as! Apple<br>greenApple.count // 4</pre><pre>// add own properties<br>greenApple.set(price: &quot;$4&quot;)<br>greenApple.price // $4</pre><blockquote>• <strong>When you clone an object, all the properties of that object is copied to <br>another object. <br>• This design pattern should be used when you need to create an object without knowing the hierarchy of that class</strong></blockquote><h3><strong>The Factory Method Pattern</strong></h3><p>It is the most commonly used design pattern. Basically, it just abstracts the creation of an object.</p><p>Create a class called <strong><em>FruitFactory</em></strong> that returns the type of the object needed.<br>Add a static method thats accepts an enum called <strong><em>FruitType</em></strong> as a parameter and returns the object needed at runtime.</p><p>Any instance returned by the factory would be of type Interface(in swift <em>protocol</em>) which any factory candidate class must have implemented.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e188c5bde7ff0d4d4b45dc394023d540/href">https://medium.com/media/e188c5bde7ff0d4d4b45dc394023d540/href</a></iframe><p>After running the above code in the playground:</p><pre>// get the object of class Orange from the FruitFactory class<br>let orange = FruitFactory.getFruit(forType: .orange)<br>orange?.getPrice() // &quot;$5<br>orange?.getCount() // 2</pre><pre>// get the object of class Grapes from the FruitFactory class<br>let grapes = FruitFactory.getFruit(forType: .grapes)<br>grapes?.getPrice() // &quot;$3&quot;<br>grapes?.getCount() // 1</pre><blockquote><strong>• The type of the object created is determined at runtime.<br>• This design pattern makes the codebase more flexible to add or remove new types.</strong></blockquote><h4><strong>This introduces us to the concept of </strong><em>program to an interface, not an implementation</em>.</h4><h3>Abstract Factory Pattern</h3><p>This design pattern provides an interface for creating families of related objects without specifying their concrete classes. They are often implemented with Factory Method pattern.</p><p>We have an abstract factory called<em> </em><strong><em>Furniture Factory </em></strong>for creating different products. The concrete factory class <strong><em>Factory </em></strong>will be implementing<strong><em> Furniture Factory </em></strong>protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6860f66e803166cbbae792046b65e4/href">https://medium.com/media/df6860f66e803166cbbae792046b65e4/href</a></iframe><p>Running the above code.</p><pre>// create MyChair class object<br>let chair = Factory.createChair()<br>chair.count() // 4</pre><pre>// create MyTable class object<br>let table = Factory.createTable()<br>table.count() // 1</pre><blockquote><strong>• Reveals the interface, not their implementation<br>• Abstract Factory is like a protocol that we will use on a concrete class to create objects</strong></blockquote><h3>Builder Pattern</h3><p>This design pattern separate the process of creation of objects from its actual usage.</p><p>First we declare an abstract protocol(or interface) for creating the product. In this case it is <strong><em>ShoeShop</em> </strong>protocol.<br>Class <strong><em>Nike</em> </strong>is a <strong>concrete builder </strong>to encapsulate the product creation process.</p><p><strong><em>Director</em> </strong>creates object using the builder protocol. <strong><em>Director</em></strong> should be initialized with object that conforms to <strong><em>ShoeShop</em></strong> protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e54ef25777a6e1ebfd2966f297ebab3/href">https://medium.com/media/8e54ef25777a6e1ebfd2966f297ebab3/href</a></iframe><p>After running the code.</p><pre>// create a nike object<br>let nike = Nike()</pre><pre>// instantiate Director with nike object<br>let director = Director(shoeShop: nike)</pre><pre>// encapsulated the process of producing the nike product<br>director.produce() // &quot;Shoe produced&quot;</pre><blockquote><strong>• Use Builder pattern when building public APIs because it does not reveal the implementation details<br>• Hides complexity. It provides a simple API behind a complex task.</strong></blockquote><h3><strong>Singleton Design Pattern</strong></h3><p>In swift we define Singleton classes by using the <strong><em>static</em></strong> keyword. It means that the object is going to be instantiated only once. Static properties are lazy initialized and will not be instantiated until called.<br><strong>There is only one copy of this object and is used by the other objects globally.</strong></p><p><strong>We can see the usage in Apple frameworks as well:</strong></p><pre>// Shared url session<br>let urlSession = URLSession.shared</pre><pre>// user defaults<br>let userDefaults = UserDefaults.standard</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddfb9f12e799c8f6fa382568dadf41e3/href">https://medium.com/media/ddfb9f12e799c8f6fa382568dadf41e3/href</a></iframe><p>After running the code</p><pre>Vehicle.sharedInstance.getName() // &quot;Car&quot;</pre><blockquote><strong>• We use the let keyword to make sure that the shredInstance’s value will not change<br>• Don’t forget to add the private initialiser so as to prevent other classes from calling its default initializers</strong></blockquote><p><a href="https://github.com/LH17/Creational-Design-Pattern/"><strong><em>Here is the link to the playground files.</em></strong></a></p><p>The main reason we use Creational Design Pattern is to decouple the logic of creation of an object from its usage. It helps reduce complexities by creating objects in a controlled manner with already mentioned <strong><em>tried &amp; tested </em></strong>solutions.</p><p>For reading about behavioral design patterns, here is the <a href="https://medium.com/@lubabahasnain93/design-patterns-in-swift-part-ii-behavioral-design-pattern-5e4e5f13ccf7"><strong>link</strong></a> to the blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18d4be82092f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sensible Operators]]></title>
            <link>https://medium.com/@lubabahasnain93/sensible-operators-28b27321e7e0?source=rss-4e72c575efbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b27321e7e0</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Lubaba Hasnain]]></dc:creator>
            <pubDate>Sun, 12 Nov 2017 09:00:48 GMT</pubDate>
            <atom:updated>2017-11-12T13:55:28.647Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A new age of custom operators</em></h4><p>We all intend to write code that can provide minimal friction to its readers. An elegant code that enhances readability and understandability. <br>Now, if I tell you to write a code to add two numbers, in how many ways can you do that?<br>You would perfectly write either 1 + 2 or add a function like:</p><pre>func add() -&gt; Int { <br>  return 1 + 2<br>}</pre><p>Basically, both do the same thing. But, using an add operator(1 + 2) is much easier and more readable than writing an add() function because it straightaway reveals the intention of your code.</p><h4><strong>Operators and notations</strong></h4><p>Operator is a character that represents an action. Like mentioned before, a ‘+’ operator(a character) would add two numbers (an action). Operators have different notations: In swift we have four types:</p><ol><li>Infix: Operators are written in-between their operands. (2 + 4)</li><li>Postfix: Operators are written after their operands. (optionalNumber!)</li><li>Prefix: Operators are written before their operands (-3)</li><li>Ternary: Operates on three operands. Swift has only one ternary operator, the ternary conditional operator (a ? b : c)</li></ol><h4><strong>Precedence and associativity</strong></h4><p>In swift, some operators have got a higher priority than the other operators: the higher priority operators are evaluated first. This is called <em>Operator Precedence</em>. <br><em>Associativity</em> determines the order in which the operators of the same precedence are evaluated.</p><p>We have an expression: 1 + 2 * 5 / 2. If you run this expression in the Swift Playground, it will give you 6. But, if you try to read it (from left to right), it might give you a different answer.<br>1. 1 + 2 gives you 3<br>2. 3 * 5 gives you 15<br>3. 15 / 2 gives you 7</p><p>In Swift, the multiply ‘*’ and the divide ‘/’ operators have higher precedence than the add ‘+’ operator. Hence, those are evaluated first. Now, the ‘*’ and ‘/’ operators belong to the same precedence, so how can they be evaluated? Thats where the <em>associativity </em>comes into place. <br>Multiply and divide operators both associate with the expression to their left.</p><p>Hence, the expression becomes:<br>: 1 + ((2 * 5) / 2)<br>: 1 + (10 / 2)<br>: 1 + 5<br>: 6<br>You can check <a href="https://developer.apple.com/documentation/swift/operator_declarations">Operator Declarations</a> for more information.</p><h4><strong>Custom Operators</strong></h4><p>In Swift, you can define your own operators. Could be anything from ASCII symbols to Unicode characters but it should make sense to the person reading the code. Here, we are going to do some operations on Array.<br><strong><em>In all the examples, generics will be used which provides us a flexible way to use any type on the operators.</em></strong></p><p><strong>Prefix Operator<br></strong>We will use a prefix operator to sort an array in an ascending order.<br>First, we declare prefix operator :</p><pre>prefix operator §</pre><p>And then we define a function for that operator:</p><pre>prefix func §&lt;T: Comparable&gt;(lhs: [T]) -&gt; [T] {<br>  let array = lhs<br>  return array.sorted { $0 &lt; $1 }<br>}</pre><blockquote>Remember, if we try to omit the prefix modifier before the function name, the compiler will throw error. For prefix and postfix operators, it is very necessary to add the respective modifier before the function name.</blockquote><p>As mentioned in the function, this operator will operate on an array and return a sorted array.</p><pre>§[4,7,3] // Result is [3,4,7]</pre><pre>§[&quot;s&quot;, &quot;a&quot;] // Result is [&quot;a&quot;, &quot;s&quot;]</pre><p>Everything looks good so far.</p><p><strong>Postfix Operator<br></strong>Lets have an operator ‘ ¶ ’ which will reverse a given array.<br>The first step is declaring the postfix operator followed by the function definition to give meaning to the operator.</p><pre>postfix operator ¶</pre><pre>postfix func ¶&lt;T: Equatable&gt;(array: [T]) -&gt; [T] {<br>  return array.reversed()<br>}</pre><p>Try out this example:</p><pre>[&quot;2&quot;, &quot;1&quot;, &quot;3&quot;]¶ // Result is [&quot;3&quot;,&quot;1&quot;,&quot;2&quot;]</pre><pre>[&quot;d&quot;,&quot;a&quot;, &quot;p&quot;]¶ // Result is [&quot;p&quot;, &quot;a, &quot;d&quot;]</pre><p><strong>Infix Operator<br></strong>Lets create our own Set operator ‘<strong>∪’</strong> to find the union between two arrays. Declare an operator and write a function for this operator:</p><pre>infix operator ∪</pre><pre>func ∪ &lt;T:Equatable&gt;(lhs: [T], rhs:[T])-&gt;[T] {<br>  var result = lhs<br>  for element in rhs {<br>    if !lhs.contains(element) {<br>      result.append(element)<br>    }<br>  }<br>  return result<br>}</pre><p>We know that the union operator ∪ is generally used when we are operating on Sets. To use them in an array will simply mean that we want to find the union of two arrays.</p><blockquote><em>If we are implementing a function for the infix operator, then we do not need to add the infix modifier before the function definition.</em></blockquote><p><em>If you write the infix modifier before the function definition, the compiler will throw error:</em> <strong>‘infix’ modifier is not required or allowed on func declarations.</strong></p><p>Test it out with the following code:</p><pre>[1,2,3] <strong>∪ </strong>[2,3,4] // Result is [1,2,3,4]</pre><pre>[&quot;a&quot;, &quot;e&quot;, &quot;s&quot;] <strong>∪ </strong>[&quot;a&quot;, &quot;e&quot;, &quot;l&quot;] // Result is [&quot;a&quot;,&quot;e&quot;,&quot;s&quot;,&quot;l&quot;]</pre><p>Another example to find the intersection of two arrays using the infix operator ∩.</p><pre>infix operator ∩</pre><pre>func ∩&lt;T: Equatable&gt; (left: [T], right: [T]) -&gt; [T] {<br>  var intersection: [T] = []<br>  for value in left {<br>    if right.contains(value) {<br>      intersection.append(value)<br>    }<br>  }<br>  return intersection<br>}</pre><p>Testing it:</p><pre>[7,8,9] ∩ [8,9,10] // Result is [8,9]</pre><pre>[&quot;a&quot;, &quot;c&quot;, &quot;e&quot;] ∩ [&quot;a&quot;, &quot;b&quot;] // Result is [&quot;a&quot;]</pre><p><strong>Using precedencegroup and associativity<br></strong>So far, we have our union and intersection operators functioning as required. What if we want to use both the union and intersection together in an expression?</p><pre>[1,2,3] ∪ [0,2,4,6] ∩ [2,4,6] // Error</pre><p><em>The compiler will throw error:</em> <strong>adjacent operators are in non-associative precedence group ‘DefaultPrecedence’.</strong></p><p>This is because for infix operators, the default associativity is none and the precedence group is <em>DefaultPrecedence</em> i.e. both the operators belong to the same precedence group and are non-associative<em>. </em>So, the compiler does not know which one to evaluate first.<em><br></em>For reading more about operator precedence, check this link: <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0077-operator-precedence.md"><em>Operator Precedence</em></a><em>.</em></p><p>Lets define a precedenceGroup for the infix operator:</p><pre>precedencegroup UnionOperatorPrecedence {<br>  associativity: left<br>}</pre><p>Each precedencegroup has an optional associativity which is either left or right. In this example, the UnionOperatorPrecedence is left assocative which means that the order in which operators will be evaluated will be from left.</p><p>Let us re-write the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4353a5c263dbff1d40da8a74a4914f68/href">https://medium.com/media/4353a5c263dbff1d40da8a74a4914f68/href</a></iframe><p>We will add the precedenceGroup for the Intersection operator ∩ too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c2f42b772bc1d899c0b2b898254e2c3/href">https://medium.com/media/4c2f42b772bc1d899c0b2b898254e2c3/href</a></iframe><p>Re-run the expression:</p><pre>[1,2,3] ∪ [0,2,4,6] ∩ [2,4,6] // Error</pre><p>The compiler is still not happy! It says:<br><strong>adjacent operators are in unordered precedence groups ‘UnionOperatorPrecedence’ and ‘IntersectionOperatorPrecedence’.</strong></p><blockquote>With expressions involving two infix operators, precedence relationship must be defined between their precedence groups.<strong><br></strong>It is performed by adding the <strong>higherThan</strong> clause.</blockquote><p>We will give ‘UnionOperatorPrecedence’ higher precedence than the ‘IntersectionOperatorPrecedence’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4b6a60bbe6dac7a46406f8788cc89e6/href">https://medium.com/media/d4b6a60bbe6dac7a46406f8788cc89e6/href</a></iframe><p>We can also use the clause <strong><em>lowerThan</em></strong> to relate a precedence with another precedence which is imported from another module.</p><p>Let us again run the expression:</p><pre>[1,2,3] ∪ [0,2,4,6] ∩ [2,4,6] // [2, 4, 6]</pre><p>And yes it compiled this time!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7TKDkDbIDJieKbVm%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstudiosoriginals-parker-jackson-mushy-3o7TKDkDbIDJieKbVm&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7TKDkDbIDJieKbVm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="290" frameborder="0" scrolling="no"><a href="https://medium.com/media/0917c841d154f6177e325e29c824aff1/href">https://medium.com/media/0917c841d154f6177e325e29c824aff1/href</a></iframe><p>The union operation is performed first as the union operator has a higher precedence than the intersection operator. The evaluation step becomes:<br>: ([1,2,3] ∪ [0,2,4,6]) ∩ [2,4,6]<br>: [1, 2, 3, 0, 4, 6] ∩ [2,4,6]<br>: [2,4,6]</p><p><strong>Should custom operators be used?</strong></p><blockquote><em>You don’t code just for compilers, you code for people who are going to read your code!<br>A good coding style is going to serve people well.</em></blockquote><p>Said this, introducing a good style in your code is good but lets not trade it for usefulness. We should not use custom operators if they are not useful. Also, you have to be very careful in choosing your own set of operators and you got to document it well. An operator which doesn’t have any meaning outside its documentation is useless.</p><p><a href="https://github.com/LH17/Custom-Operators-">Here is the playground file.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b27321e7e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration of Xcode 9 with GitHub]]></title>
            <link>https://medium.com/technology-nineleaps/integration-of-xcode-9-with-github-a350bf563278?source=rss-4e72c575efbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/a350bf563278</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode-9]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Lubaba Hasnain]]></dc:creator>
            <pubDate>Thu, 22 Jun 2017 17:00:32 GMT</pubDate>
            <atom:updated>2017-06-30T11:48:59.708Z</atom:updated>
            <content:encoded><![CDATA[<h4>Source control is now a first class citizen of Xcode</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*LvHxcP7bmb2VgjqUH8vn-w.jpeg" /></figure><p>At WWDC 2017’s talk of <a href="https://developer.apple.com/videos/play/wwdc2017/405/"><strong>GitHub and the New Source Control Workflows in Xcode 9</strong></a><strong>, </strong>new tools were announced for exploring the source control history of our projects, GitHub&#39;s integration with Xcode and how we can use the source control navigator to commit changes, pull &amp; push the code to GitHub, see the entire commit history and information — all integrated right inside the Xcode. Sounds good?</p><p>Let’s dive right with these five easy steps to explore how we can get the full advantage of GitHub within Xcode. If you do not have Xcode 9, download it <a href="https://developer.apple.com/download/">here</a>.</p><h3><strong>1. Add a GitHub account</strong></h3><p>Open <em>Xcode -&gt; Preferences -&gt; Accounts</em> and add an account by clicking the plus sign at the bottom. Now, click on the GitHub option and enter your GitHub&#39;s email and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*04puaS92WCnYsRH7Atewpg.png" /></figure><p>Congratulations, your GitHub account is added to your Xcode’s Source Control Accounts.</p><h3><strong>2. Clone the repository</strong></h3><p>Open Xcode, from the menu, select <em>Source Control -&gt; Clone</em>. A new window will appear that will list all the projects in your repository including the one you have starred. Select a project and click <em>Done</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*FT2Dszge8IAQbXMgC8BtSg.png" /></figure><h3><strong>3. Source control navigator</strong></h3><p>After you have cloned the project, select your project and press <em>Command+2 </em>to open the brand new <em>Source Control Navigator</em>. You can see the entire commit history of the project. Select a commit and open Inspector. It will display the branches which have your commit, the commit hash, date, author and the commit message. The best part — <strong>we can even filter our commits in the source editor on the basis of author, commit message, branch, etc.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*_A_pJJWto5jqJhfjc9OiWQ.png" /></figure><h3><strong>4. Basic GitHub operations (commit, push, pull &amp; create a branch)</strong></h3><p>Create a new branch by right-clicking the <em>master </em>branch from the navigator area -&gt; New Branch from “master” and a new branch will be created. Commit the changes by selecting from the menu <em>Source Control -&gt; Commit</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*oLcrHbML6PrE01kZpZ7Tbg.png" /></figure><p>You will see a window is displayed. Add the <em>“commit message”</em> at the bottom and make sure the <em>“Push to remote”</em> button is checked at the bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*bfRmzIAg-jm3Ruw55gI-2w.png" /></figure><p>In order to view the branch on GitHub, right-click on the <em>newly created branch -&gt; View on GitHub</em>. You can see your branch automatically created on the GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*0POYSEHot_OKzIGIrpWdtA.png" /></figure><h3><strong>5. Tags</strong></h3><p>Tag a commit by right-clicking it -&gt; <em>Tag</em>. Name the tag (like <em>v1.0</em>) and add a message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*G-FDGuRQvTlTa2VRMpDStA.png" /></figure><p>You will see the commit gets tagged with that version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*pDC3v4LJQq3UIreSZi3nbA.png" /></figure><p>You can try other operations like merging a branching, deleting a branch, discarding all the changes (like a git stash), checking the commits made for each file etc.</p><p>This is completely a new feature that has been integrated by Apple in Xcode. Think about the time that will be saved which is otherwise consumed in writing the git related operations in your terminal.</p><blockquote>Note: It is highly recommended to try out these steps yourselves and let me know your suggestions regarding Xcode’s integration with Github in the comments below.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a350bf563278" width="1" height="1" alt=""><hr><p><a href="https://medium.com/technology-nineleaps/integration-of-xcode-9-with-github-a350bf563278">Integration of Xcode 9 with GitHub</a> was originally published in <a href="https://medium.com/technology-nineleaps">Technology at Nineleaps</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing network states with protocol extensions]]></title>
            <link>https://medium.com/@lubabahasnain93/managing-network-states-with-protocol-extensions-cab07ed9048d?source=rss-4e72c575efbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/cab07ed9048d</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <dc:creator><![CDATA[Lubaba Hasnain]]></dc:creator>
            <pubDate>Fri, 02 Jun 2017 12:59:21 GMT</pubDate>
            <atom:updated>2017-06-09T01:40:01.592Z</atom:updated>
            <content:encoded><![CDATA[<h4>Content? Loading? Error? Empty? Lost…</h4><p>Today morning I opened the Apple’s music app to soothe my ears with some songs. But of course, as an iOS developer I was more drawn to examine the functionality of the app instead. What I found was the subtle ways in which the app handles state changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*roW0i0POoN9nzTK4ItQGVw.png" /><figcaption>Content, Loading, Error and Empty states</figcaption></figure><p>So, it drew me to find the best ways in which we could handle network states in our applications.</p><p>Let’s say we’re building an app which manages four states, namely:<br>1. Content: The data is presented to the user<br>2. Loading: The data is being loaded over network<br>3. Error: Error encountered while loading data over network<br>4. Empty: No data available to be displayed to the user</p><blockquote>The questions which arises are: Is my code <strong>reusable</strong>? Do I follow the <strong>DRY</strong> principle? What if I have different methods to manage states in different classes? Is <strong>code</strong> <strong>refactoring</strong> easy?</blockquote><p>If your answer is ‘No’, you can refer to the ‘The Solution’ or else have your spaghetti.</p><h3><strong>The Solution</strong></h3><p>At WWDC 2015, Apple introduced <em>Protocol-Oriented Programming. </em>With it came the most powerful feature: <strong>Protocol Extensions.<br></strong>Wait, what did you say? Now, what the hell is<strong> protocol extension</strong>. If you are new to the concept, please refer to the links:</p><p><a href="https://www.raizlabs.com/dev/2015/06/protocol-extensions-swift-2-0/"><em>https://www.raizlabs.com/dev/2015/06/protocol-extensions-swift-2-0/</em></a><em><br></em><a href="http://machinethink.net/blog/mixins-and-traits-in-swift-2.0/"><em>http://machinethink.net/blog/mixins-and-traits-in-swift-2.0/</em></a><em><br></em><a href="http://cutting.io/posts/stateful-mixins-in-swift/"><em>http://cutting.io/posts/stateful-mixins-in-swift/</em></a></p><h3><strong>Quick look at the Demo</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*YzcAc17nyz9YKse-q6B1jQ.gif" /><figcaption>Content and Error states</figcaption></figure><h3><strong>Let’s start with Protocol</strong></h3><p>We have a protocol named ViewStateProtocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/994aa8297c71515c188c93c01c471866/href">https://medium.com/media/994aa8297c71515c188c93c01c471866/href</a></iframe><p>Let’s talk about it. We have a state manager class instance (class which manages adding and removing views), loading, error and empty views, an error message and a method declaration <strong>addView</strong> which takes States Type as a parameter(an enum containing the various states)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f0f719c2ff50acdfa4fc0baf02dacc/href">https://medium.com/media/43f0f719c2ff50acdfa4fc0baf02dacc/href</a></iframe><p>Now, let’s have some magic with protocol extensions. <br>First, we created a single instance of State manager class which takes care of adding and removing views. Then, we create loading, error and empty view objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82438d37a21a3802e2fa135a991cffcf/href">https://medium.com/media/82438d37a21a3802e2fa135a991cffcf/href</a></iframe><p>Awesome! But, we still need to add these views to our view controller’s view. So, how to do that? Not a problem, we have state managers to our rescue. State Manager class will take care of adding these views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7a3679bfc476bd0af80331c153231d2/href">https://medium.com/media/b7a3679bfc476bd0af80331c153231d2/href</a></iframe><p>Yay! We did it. But wait, where’s our State Manager class. Let’s have a look at it too…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f77d75e4850fb54e09068ae3b18da21/href">https://medium.com/media/4f77d75e4850fb54e09068ae3b18da21/href</a></iframe><p>So, we’ve the default implementation for all the views. But how do we implement it? Ever wondered?</p><h3><strong>Implementation of protocol</strong></h3><p>Our view controller is going to implement the ViewStateProtocol and call the methods whenever it needs to display the views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a30eeeb47f8f5681725d2fc425ce98a/href">https://medium.com/media/6a30eeeb47f8f5681725d2fc425ce98a/href</a></iframe><blockquote>Any view controller that is concerned with managing network related states can implement the ViewStateProtocol and reuse all the code. As simple as this :)</blockquote><h3><strong>Wrap up</strong></h3><p>Protocol Extensions allow us to have mixin like pattern. Its advantageous for <strong>code</strong> <strong>reusability</strong> and <strong>maintainability</strong>.<br>This github repository has a demo application.</p><p><a href="https://github.com/LH17/ViewStates">LH17/ViewStates</a></p><p>Thanks for reading. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cab07ed9048d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>