<?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 Alok Subedi on Medium]]></title>
        <description><![CDATA[Stories by Alok Subedi on Medium]]></description>
        <link>https://medium.com/@aloksubedi?source=rss-8fde38e1f6ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4CeCrxi6OXtsN7zb.</url>
            <title>Stories by Alok Subedi on Medium</title>
            <link>https://medium.com/@aloksubedi?source=rss-8fde38e1f6ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:05:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aloksubedi/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[Better iOS through Factory Method Pattern — A basic chat view]]></title>
            <link>https://medium.com/@aloksubedi/better-ios-through-factory-method-pattern-a-basic-chat-view-b46d1078e099?source=rss-8fde38e1f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b46d1078e099</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Alok Subedi]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 05:19:03 GMT</pubDate>
            <atom:updated>2021-09-08T05:56:52.842Z</atom:updated>
            <content:encoded><![CDATA[<h3>Better iOS through Factory Method Pattern — A basic chat view</h3><p>Design pattern for me was one of the greatest revelation. They taught me to look at object-oriented programming beyond simple inheritance and interface. It taught me to make use of them in all different ways. Learning design patterns was my first step towards learning software architecture.</p><p>We all have been in a situation where we find a problem and brilliantly solve it. We later find similar problems and use the same technique to solve them. Sometimes we even come up with better solution.</p><p>Seems like developers decades ago were also the same. But they were smart enough to document the solutions so others don’t have to go through iterations to get the best solution. These solutions for the commonly occurring problems are called design patterns.</p><p>In this article, we will look at one of the common problems and use the factory method pattern to solve it.</p><p>Download starter project form <a href="https://github.com/aloksbd/Factory-Method-Pattern">here</a> if you want to code along.</p><h3>Project Overview</h3><p>We are creating a simple chat UI with two types of messages- text and image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Svah7lzjYaVTlZ8UyGGoVg.png" /></figure><p>We have Message with optional text and optional image, so that there can be either text or image per message. We have created ImageChatCell and TextChatCell and their respective BubbleViews using generics. You can follow my last article about generics- <a href="https://medium.com/@aloksubedi/remove-code-duplication-with-generics-a-basic-chat-view-9c736eaae5de">Remove code duplication with Generics — A basic chat view</a> to see how we did that. <br><em>I also suggest you visit that article if you would create a single message cell that hides label if message has an image and hide imageView if message has text.</em></p><p>The class of our concern is ChatTableViewController. We render the messages in tableView(cellForRowAt: ) using if-else. If message does not have an image, we render TextChatCell and if it does, we render ImageChatCell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0840c8a4912f5775d0f53dec22c64c72/href">https://medium.com/media/0840c8a4912f5775d0f53dec22c64c72/href</a></iframe><h3>Problem</h3><p>Imagine if we have to add more types of messages like video message, audio message, separate ui for incoming and outgoing messages; we will have to add lots of ‘else if’. That is because we won’t know which cell is needed without knowing what the message is.</p><p>The problem we have here is we will have a huge ‘if-else if’ inside a single function resulting in bad code. The reason is this function is responsible for the creation of all possible cells and the cell type it needs to create is determined at the runtime.</p><h3>Solution — Factory Method Pattern</h3><p>Factory method pattern is one of the creational pattern that solves this issue of creating an object whose exact type(class) is determined at runtime.</p><p>It works by creating a protocol factory that has a function to create an object of a parent type. Its child factories now implement what type of object to create. In the diagram below we can see there are Factory1 and Factory2 implementing Factory. They can create any Product, Product1 or Product2 depending on the implementation. Factory1 might create a random Product based on some parameters or always create Product1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*4_aBXWXL3R6NyYxuVRVg7A.png" /></figure><p>In our case, our ‘Product’ is UITableViewCell and our products are TextChatCell and ImageChatCell. Now let&#39;s create CellFactory that creates cell.</p><p>To create a cell we need tableView to dequeue the cell and message to setup the cell. Let&#39;s create a ChatCellFactory with this createCell method that takes message and tableView as arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e96d61717e479fa53bc1c038a6c8fa50/href">https://medium.com/media/e96d61717e479fa53bc1c038a6c8fa50/href</a></iframe><p>Now we can create TextChatCellFactory for TextChatCell and ImageChatCellFactory for ImageChatCell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dde1a14959573378cc2ed64277eae5ff/href">https://medium.com/media/dde1a14959573378cc2ed64277eae5ff/href</a></iframe><p>Now in tableView(cellForRowAt: )in ChatTableViewController we can replace cell creation with the factory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c49d095483df8af0648291e07267be0a/href">https://medium.com/media/c49d095483df8af0648291e07267be0a/href</a></iframe><p>That’s it. We moved creational logic to the factory. Now when we need to add a new type of chat cell, we create its factory.</p><p>Wait we still have that if-else, we have not yet solved the mess we will end up having when we add lots of message types.</p><p>Factory doesn&#39;t have to create only one type of object, it can create any type of object depending on the parameter. So we can create a new factory that uses message to determine what type of cell to create. Basically, a factory where we will move the if-else logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fc3e702309579cf20ed77610f1f30cb/href">https://medium.com/media/6fc3e702309579cf20ed77610f1f30cb/href</a></iframe><p>Now cellForRowAt: can use MasterChatCellFactory and it gets the required cell on the runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/449be71c4034064289daffae6c2179df/href">https://medium.com/media/449be71c4034064289daffae6c2179df/href</a></iframe><h3>Confusion</h3><p>Well, we just succeeded in increasing 15 lines of code to 3 different classes and a protocol. We only moved the creational logic inside an if-else to those classes. So didn’t we end up having more complex code?</p><p>Yes, if we are 100% sure there won&#39;t be a new type of message added later. But if we have more message types, a function with large if-else would be more complex than different classes with one responsibility.</p><p>By using Factory Method Pattern we have created a solution/architecture, where we don&#39;t need to change a code in ChatTableViewController to add a new type of message. When we add a video message, we can now create a VideoChatCell with VideoChatBubbleView, VideoChatCellFactory with creational logic and add a conditional in MasterChatCellFactory that calls VideoChatCellFactory.createCell().</p><p>The benefit we have are.</p><ol><li>Open/Closed Principle. We made ChatTableViewController change proof, we don’t have to change it to add a new type of message.</li><li>Single Responsibility Principle. We moved the responsibility of determining the type of cell to MasterChatCellFactory and the responsibility to create cells to their respective factories.</li><li>Cleaner code. We now have multiple classes with precise name defining its responsibility and scope making it easier for the eye.</li><li>Communicate intent. When someone who knew factory method pattern looks at this code, they will immediately understand the architecture and problem it is trying to solve.</li></ol><h3>Exercise</h3><p>Try creating a new type of cell (<em>try url message using a button</em>).</p><h4>References:</h4><ul><li><a href="https://www.youtube.com/playlist?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc">Christopher Okhravi’s youtube playlist.</a></li><li><a href="https://refactoring.guru/design-patterns">Refactoring Guru</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b46d1078e099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove code duplication with Generics — A basic chat view]]></title>
            <link>https://medium.com/@aloksubedi/remove-code-duplication-with-generics-a-basic-chat-view-9c736eaae5de?source=rss-8fde38e1f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c736eaae5de</guid>
            <category><![CDATA[chat-ui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Alok Subedi]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 17:37:14 GMT</pubDate>
            <atom:updated>2021-09-03T06:19:51.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Remove code duplication with Generics — A basic chat view</h3><p>For a very long time I couldnot use generics beyond a generic api call. I used this get function that can make all get requests and decode to their respective model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1ee2f91346abf23f670e067a6f92dc5/href">https://medium.com/media/f1ee2f91346abf23f670e067a6f92dc5/href</a></iframe><p>I learned to use generics on smaller functions or classes but was always afraid to try generics when I encountered duplication in a bigger code base.</p><p>I have been in many situations where I had similar views with a single different type. One of those is chat UI. It has multiple similar cells with few differences. I would end up creating different UIView class for all the different types with all duplicate codes.</p><p>A big shout-out to <a href="https://medium.com/u/27b1c64c3b48">Caio Zullo</a> and <a href="https://medium.com/u/f385ad8c816a">Mike Apostolakis</a> and their course <a href="https://iosacademy.essentialdeveloper.com/p/ios-lead-essentials/">iOS Lead Essentials</a> where I learned generics in different light.</p><p>In this article we will create a simple chat UI like messenger and see how we can use generics to remove code duplication.</p><p>You can download starter project from <a href="https://github.com/aloksbd/Generics">here</a> to follow along.</p><h3>Project Overview</h3><p>This is the basic chat UI we will make. It is an inverted UITableView which has two type of cells- one with text message and next with image. Both cell looks similar except for the main message. Both cell has a view with rounded corner, a name label, and similar constraints resulting in two cell class with same codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D30TL2yXu5qdp77lGZZ20g.png" /></figure><h3>Code Overview</h3><p>We already have a working code that renders the above UI. Let’s go through them one by one.</p><h4>Message</h4><p>It is a simple model with sender name, optional text and optional image, so message will only have either of text or image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fdbd8f1b5741f8ff007632957b1da78/href">https://medium.com/media/5fdbd8f1b5741f8ff007632957b1da78/href</a></iframe><p><em>Note: Using UIKit in model is not a good practice. I am using it to have minimum code base for this article.</em></p><h4>TextChatBubbleView</h4><p>It is that rounded view with name and message labels for text messages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f7cf61889beab5351d92d5cade880cb/href">https://medium.com/media/0f7cf61889beab5351d92d5cade880cb/href</a></iframe><h4>ImageChatBubbleView</h4><p>It is same as TextChatBubbleView but has messageImageView instead of messageLabel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc0269388339285d050ca4d40ca755e6/href">https://medium.com/media/dc0269388339285d050ca4d40ca755e6/href</a></iframe><h4>TextChatCell</h4><p>It is the UITableViewCell for text message. It has TextChatBubbleView and name and message attributes that is bound to name and message labels in TextChatBubbleView using didSet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8980d170f15899d899fab0ccca371ffe/href">https://medium.com/media/8980d170f15899d899fab0ccca371ffe/href</a></iframe><h4>ImageChatCell</h4><p>It is same as TextChatCell, but for image message. It has ImageChatBubbleView instead of TextChatBubbleView and image instead of message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f17f42bf31b73b2ee00ea8eeff5d73d8/href">https://medium.com/media/f17f42bf31b73b2ee00ea8eeff5d73d8/href</a></iframe><h4>ChatTableViewController</h4><p>It has an array of messages which is rendered on tableView. It also rotates the tableView so first element is displayed at the bottom. We render two types of cell- TextChatCell when image of the message is nil else ImageChatCell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d24d1a9977676d5b5ff9fbddf352cdbd/href">https://medium.com/media/d24d1a9977676d5b5ff9fbddf352cdbd/href</a></iframe><h3>Generic</h3><blockquote><em>Generic code</em> enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.</blockquote><p>This is the definition from apple’s <a href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html">Swift Book.</a> Lets see how we can write flexible, reusable code to avoid duplications.</p><p>First thing to remember, we use generics when the code is same for different type. We all have been in a situation where we have similar code, we create a function in same class or a new class with those code and call it to remove duplication. However, when there is different types involved, even though the code is same we cannot create a common function. That is where generics comes in.</p><p>We can clearly see there are exact same code in TextChatBubbleView and ImageChatBubbleView, and TextChatCell and ImageChatCell. The only difference we can see is ‘Type’. TextChatBubbleView uses UILabel and ImageChatBubbleView uses UIImageView to render message. TextChatCell has TextChatBubbleView and string message while ImageChatCell has ImageChatBubbleView and image message.</p><p>So lets make a generic class that works with both text and image type.</p><h4>GenericChatBubbleView</h4><p>Start by copying TextChatBubbleView class and rename it to GenericChatBubbleView. <br>class GenericChatBubbleView&lt;MessageView&gt;: UIView</p><p>See &lt;MessageView&gt;, it is the syntax for generics. This is saying that this class will use a generic type, and we have named this generic type as a MessageView. The type is to be defined when it is used. So in TextChatCell instead of declaring bubbleView as TextChatBubbleView, we can declare it as GenericChatBubbleView&lt;UILabel&gt;.</p><p>Now, instead of declaring messageLabel as UILabel, we can make it of type MessageView. Change messageLabel to messageView let messageView = MessageView(). By doing this we are saying type of messageView can be anything defined when GenericChatBubbleView is used. By decalring GenericChatBubbleView&lt;UILabel&gt; in TextChatCell, we are saying messageView is UILabel.</p><p>Got an issue ‘Type ‘MessageView’ has no member ‘init’’. It is because swift doesnot know if type we use for MessageView will even have init. Lets fix it this way &lt;MessageView: UIView&gt;. It is called ‘Type Constraint Generics’, meaning we are constraining this generic to certain type only. Here we are saying MessageView can be any type of UIView- UIlabel, UIButton, UITableViewCell, etc.</p><p>Solve next issue on line $0.numberOfLines = 0 by removing this line.</p><p>In TextChatCell instead of declaring bubbleView as TextChatBubbleView, declare it as GenericChatBubbleView&lt;UILabel&gt; if you haven’t already.</p><p>Solve the issues by renaming all the messageLabel to messageView. Now run the app to see everything is working. Well, except for number of lines.</p><p>Try using GenericChatBubbleView in ImageChatCell. Now the image is not displayed. It is because we have not addressed the difference that is specific to UIImageView- constraints.</p><h3>Generics with Typealias</h3><p>Instead of defining generics from where it is used we can use typealias to define the type for generics.</p><p>We can create a TextChatBubbleView as a typealias of GenericChatBubbleView where MessageView is UILabel. <br>typealias TextChatBubbleView = GenericChatBubbleView&lt;UILabel&gt;.</p><p>Now we can make bubbleView in TextChatCell a TextChatBubbleView and run.</p><p>Try making ImageChatBubbleView using typealias the same way.</p><h3>Inheritance with Generics</h3><p>We saw that image and line of message are not displayed as intended because we have not addressed the differences. We can use inheritance with generics to address the difference.</p><p>Lets start by creating a function called setupMessageView with no code in GenericChatBubbleView and call it from init before addViews(). It is a template function which is to be implemented by its children.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d0d95b51837df27216d3b49f3e381eb/href">https://medium.com/media/9d0d95b51837df27216d3b49f3e381eb/href</a></iframe><p>Now lets make TextChatBubbleView a class that inherits from GenericChatBubbleView and override setupMessageView method to set numberOfLines to 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/073372647f71c1a3de1f4afc034b7ce8/href">https://medium.com/media/073372647f71c1a3de1f4afc034b7ce8/href</a></iframe><p>Lets also create a ImageChatBubbleView class similarly. Here we give it color, rounded corner, and size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb5d019a99fad684e09bd3309b9c2c2/href">https://medium.com/media/3bb5d019a99fad684e09bd3309b9c2c2/href</a></iframe><p>Now we have created ImageChatBubbleView and TextChatBubbleView by removing all the duplicate code between them using generics.</p><p>Here is the final GenericChatBubbleView.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/320ee1b814c8b502c84a2d89b9eebf8e/href">https://medium.com/media/320ee1b814c8b502c84a2d89b9eebf8e/href</a></iframe><h3>GenericChatCell</h3><p>This exercise is really important. Try creating a GenericChatCell where bubbleView and message are generic.</p><p>If you need help, or want to see how I did it, here is the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/969c1e5014d0f0afcc313d884774b58f/href">https://medium.com/media/969c1e5014d0f0afcc313d884774b58f/href</a></iframe><h3>What Next?</h3><p>We not only removed the code duplication, but also created a system where if we have to add new type of message, we can do it easily and with less code.</p><p>Apple’s language guide for generics is good place to visit now, get all the concepts of generics. Next time when you see code duplication that takes different types, try using generics. Even if you feel like you are lost, just try to get the code working with generics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c736eaae5de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dissecting functional programming with closure in Swift]]></title>
            <link>https://medium.com/@aloksubedi/dissecting-functional-programming-with-closure-in-swift-f318af54fc61?source=rss-8fde38e1f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/f318af54fc61</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Alok Subedi]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 15:15:34 GMT</pubDate>
            <atom:updated>2021-08-24T15:17:51.473Z</atom:updated>
            <content:encoded><![CDATA[<p>I used map and sort frequently, but was always confused when I had to use reduce. I would rather create a variable to store the result and a loop to calculate it. I used completion: @escaping all the time for api call, but I never knew why it worked.</p><p>It was because I didn’t understand functional programming. Going a step deeper, it was because I didn’t understand closure.</p><p>I will try to write about how I see closure and how my mind decode the functional codes.</p><h3>Closure as a function</h3><p>When I first read the <a href="https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html">Swift Programming Language</a>, I did not understand the closure, neither on the second nor third time. I was working with socket in node.js for a chat app, when I first saw closure as a function. Then back to swift, slowly the concept started to clear up.</p><p>Lets dive into codes. You can create a playground to try for yourself.</p><p>Lets see this simple function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dc646610af34a67e168018b09b79def/href">https://medium.com/media/8dc646610af34a67e168018b09b79def/href</a></iframe><p>We created a function called helloWorld which takes no parameter, prints “Hello World!!!” and returns nothing. Then we call it to print “Hello World!!!” when we need.</p><p>Instead of declaring func, lets make helloWorld a variable of a function type and assign the block of code inside the curly braces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6ee8c9033d2fcac0fd2d41e1e709b41/href">https://medium.com/media/e6ee8c9033d2fcac0fd2d41e1e709b41/href</a></iframe><p>BOOM!! That’s a closure, a function stored in a variable.</p><p>Lets try changing this add function to a add closure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be29f12e2f2b05bde6fc2d8bfd7ea7ef/href">https://medium.com/media/be29f12e2f2b05bde6fc2d8bfd7ea7ef/href</a></iframe><p>This is what it looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f5d1241ecd33b581006b4b9d6a27957/href">https://medium.com/media/7f5d1241ecd33b581006b4b9d6a27957/href</a></iframe><p>Wait! Why are we not using parameter name while calling it?<br>Do alt+click on add you will see it is (Int, Int) -&gt; Int. Unlike function (try alt+click on any function), closure doesn&#39;t have named parameter. There is a benefit to it - different type of closure declaration.</p><h3>Types of closure syntax</h3><p>The main block in learning closure for me was that closure was declared in different ways in different code. I was always confused when one closure had named parameters and the next one was {$0 + $1}.</p><h4><strong>1. General syntax:</strong></h4><p>We saw the general closure syntax in add.<br>{ (parameters) -&gt; returnType in <br> statement<br>}</p><h4><strong>2. No parameter type:</strong></h4><p>When we give closure to a variable that was already declared, we don’t need to define type for parameter. In this add closure swift will know that a and b both are Int and the returned value should be Int.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e272fc1fb65dc2b5dd84e8c69d1f4c1/href">https://medium.com/media/6e272fc1fb65dc2b5dd84e8c69d1f4c1/href</a></iframe><p>One common example is URLSession.shared.dataTask(with: URL) { data, response, error in }. <br>If you alt+click on dataTask you will see completionHandler is already defined with parameter. So swift will automatically deduce that data is optional Data, response is optional URLResponse and error is optional Error.<br>If some variable is not used it is replaced by ‘_’.</p><h4>3. <strong>Damn $ (one liner):</strong></h4><p>The parameters can be represented with $ and number. $0 is first parameter, $1 is second, $2 is third and so on. We can use it on multi line closure but my preference, for the sake of readability, is to use it only on one liner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1325c4322b0271b576d9c54028593e6b/href">https://medium.com/media/1325c4322b0271b576d9c54028593e6b/href</a></iframe><p>Remember it works only on pre-defined closures.</p><h4>4. Trailing Closure:</h4><p>We can pass closure as parameter to a function, after all we have been storing closure to a variable. Using trailing closure we can even declare it while calling a function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2fdd3bb4ed6e9119320e769b6806429/href">https://medium.com/media/c2fdd3bb4ed6e9119320e769b6806429/href</a></iframe><p>printSum is a function that takes a and b and also a closure that defines what calculation it needs to do and prints the result. Usually we would call this function like this: add(a: 2, b: 2, action: { $0 + $1}). See how we can directly declare a closure without mentioning action parameter. This way of declaring closure is called trailing closure.</p><h3>Passing Closure</h3><blockquote>“Closures are self-contained blocks of functionality that can be passed around and used in your code.”</blockquote><p>This is the definition from <a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html">Swift Book</a>.</p><p>Closures or functions in swift are reference type. You can pass its reference around like class. Lets see the ways we can pass closure around.</p><h4>1. Direct declaration</h4><p>The examples we have been using is direct declaration of closure. We can do so to pass a closure even from one class to another.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a3db3dab613d283e4f9ed18ce225cfe/href">https://medium.com/media/1a3db3dab613d283e4f9ed18ce225cfe/href</a></iframe><p>Here we have directly declared closure for add of A from B.</p><p><em>Notice how we have wrapped </em><em>(Int, Int) -&gt; Int with ‘!’ like any other variables.</em></p><h4>2. As parameter</h4><p>We can also pass closure as a parameter of a function. We are passing a closure as parameter in init() function below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fbf258971c6feff5c387e7fad2d1c2a/href">https://medium.com/media/2fbf258971c6feff5c387e7fad2d1c2a/href</a></iframe><p>Why do we use @escaping? <br>Apple explains it better —</p><blockquote>A closure is said to <em>escape</em> a function when the closure is passed as an argument to the function, but is called after the function returns.</blockquote><p>Here we are saving the closure in variable ‘add’, so it can be called whenever needed, which is always after initialization.</p><p>Which means we don’t need @escaping if the closure is called inside the function before it returns.</p><p>But what about @escaping in a function that makes url requests even though we call completion closure inside the function?? <br>That is because the request we are making runs asynchronously. Which means the function has already returned when the response is received and the closure is called.</p><h3>Functional Programming</h3><p>Lets see the function I found easier —sort().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbaa2b470fc2c2c785f6669470601d0c/href">https://medium.com/media/fbaa2b470fc2c2c785f6669470601d0c/href</a></iframe><p>Alt+click on sort to see what it is. <br>sort(by areInIncreasingOrder: (Int, Int) throws -&gt; Bool) rethrows.</p><p>So sort is just a function that takes a closure which is of type (Int, Int) throws -&gt; Bool. When we pass a closure { $0 &gt; $1 }, what happens is, sort function holds this closure and calls it by passing two integers to compare. The code in our closure says return true if first element is greater than second, meaning if the first element is greater they are in our desired sorting order, else return false and the sort function will swap them.</p><p><em>Dont confuse </em><em>areInIncreasingOrder as ascending order.</em></p><p>See if you can understand this code and try some other ways you can to create and pass closure to sort.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8901b81e33b4ffb201390f6f33d800d2/href">https://medium.com/media/8901b81e33b4ffb201390f6f33d800d2/href</a></iframe><h3>Creating a custom sort function</h3><p>Finally we are here, lets see the whole functional programming in action. We will try to recreate what the code inside sort function might be like.</p><p>Lets create a class Numbers that has array of Int and a sort function. Copy the syntax for sort function that you saw after alt+click over sort. Remove throws and rethrows, we wont deal with them. Then lets use a bubble sort, that loops through each element and see if current and next element are in increasing order (not referring to ascending order). If they are not swap there position. Repeat it for the number of elements in the array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f87aae57fd956fa1b9a424b6e64b120/href">https://medium.com/media/1f87aae57fd956fa1b9a424b6e64b120/href</a></iframe><p>That’s it. I hope you can understand what is going on in this sort function.</p><h3>Exercise</h3><p>Try recreating map and reduce function.</p><p>This should be the right time to revisit the <a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html">Apple’s guide about closure</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f318af54fc61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Delegate Pattern and protocol/interface in swift]]></title>
            <link>https://medium.com/@aloksubedi/understanding-delegate-pattern-and-protocol-interface-in-swift-43a1dee2e2ee?source=rss-8fde38e1f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a1dee2e2ee</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[delegate]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Alok Subedi]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 13:52:11 GMT</pubDate>
            <atom:updated>2021-08-17T16:47:22.757Z</atom:updated>
            <content:encoded><![CDATA[<p>I never understood why we needed an interface that can’t have code. We even have to write code for different class every time we implement an interface. I still remember the first time I understood this concept of interface, something I learned almost 4 years ago in college, at that time, through delegate.</p><h3>Interface</h3><blockquote>a point where two systems, subjects, organizations, etc. meet and interact.</blockquote><p>This is the first definition from google. Interface is something that enables communication with some other system. Mobile screen is an interface where human communicates with computer. When we tap on screen, it notifies the system which does some computation and sends result back to screen where it is rendered for us to see.</p><p>Screen gives us some option we can interact with smartphone, like tap, swipe, long press, etc. Developer is free to implement what to do on those interaction. On tap, phone app will make a call, messaging app will send message, game can have a character jump. On swipe, we can scroll through Instagram feeds or cut fruits in Fruit Ninja.</p><p>Similarly, in OOP, an interface is where two different objects/classes can communicate. Interface defines how another class can send message and what result it will get without defining how to do it. So interface is a contract for communication between its user and implementer.</p><p>But isn’t a class function an interface? Of course it is. But with class function we can communicate with object of that class only and with interface we can communicate with different type of objects.</p><h3>Protocol</h3><blockquote>the official procedure or system of rules governing affairs of state or diplomatic occasions.</blockquote><p>Protocol is just a predefined set of rules. You follow protocol of your company while in work. You have to follow protocols of road if you are driving. A class has to follow the Protocol it is implementing.</p><p>When we define functions in interface, in a way we are creating a set of rules, its implementer has to implement. So interface can also be called protocol, which swift does. Remember this error “Type _ does not conform to protocol _” in swift, it is saying that you are not following all set of rules created in protocol.</p><p>Here is definition from apple:</p><blockquote>“A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.”</blockquote><blockquote>Excerpt From<br>The Swift Programming Language (Swift 5.4)<br>Apple Inc.<br><a href="https://books.apple.com/np/book/the-swift-programming-language-swift-5-4/id881256329">https://books.apple.com/np/book/the-swift-programming-language-swift-5-4/id881256329</a><br>This material may be protected by copyright.</blockquote><p>Protocol in swift can also have attributes, which other OOP languages doesnot support. So it is one of the powerful feature of swift.</p><h3>Delegate</h3><blockquote>a person sent or authorized to represent others, in particular an elected representative sent to a conference.</blockquote><p>Delegate is a representative. A project manager is a interface for client to communicate with developers, aren’t they also a representative of developers to the clients. So, in OOP we use interface as a representative for a concrete class or an object.</p><p>We use delegate when the class (think UITableView) has to pass message to its user but don’t know who it is. We create a protocol with a function and call that function from this class when needed.</p><p>By using this protocol, the class is saying -“Hey, if you are using me you need to send me your representative (delegate) with whom I can communicate when needed, and your representative needs to follow this protocol.”</p><p>When another class use a class that needs delegate (think a ViewController using UITableView), we implement and pass ‘self’ as delgate. So what it is saying is -“Hey, I will be representing myself and I have followed all the necessary protocol you need. So you can call me when you need to.”</p><p>Confused?? Maybe the code will help you understand better.</p><p>We will use the same MVC project from my previous tutorials — <a href="https://medium.com/@aloksubedi/separating-views-from-viewcontroller-522f4439ef95"><strong>Separating Views from ViewController</strong></a><strong>. </strong>We will create a custom view, TextFieldWithLabel and make a delegate for it. We will also separate delegate implementation from view/ViewController.</p><p>Download starter project from <a href="https://github.com/aloksbd/Delegate-Protocol">here</a> to follow along.</p><h3>Project Overview</h3><p>We will work with LoginForm which has textfields with title. LoginFormViewController which was separated from LoginViewController in the article — <a href="https://medium.com/@aloksubedi/mvc-that-is-not-massive-991cb33bf2a5">MVC that is not massive</a>. SignupViewController and HomeViewController are for navigation and DummyThirdPartyLogin fakes login with Facebook and Google.</p><h3>LoginForm</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df4b4d6e9dd902e6a0fb01ca788cd719/href">https://medium.com/media/df4b4d6e9dd902e6a0fb01ca788cd719/href</a></iframe><p>It is a composition of labels, textFields and button. It has a label and textField combo for username and password. Lets create a custom view TextFieldWithLabel for it.</p><h3>Creating TextFieldWithLabel</h3><ul><li>Lets create a TextFieldWithLabel class inherited from UIView. Copy creator method from the LoginForm. Then create a constructor that takes title, placeholder and isPassword to initialize a label and a textField.</li><li>Add them as subViews and give them constraints to tightly enclose them.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37458307f6d5bc0a312a506cf0cec169/href">https://medium.com/media/37458307f6d5bc0a312a506cf0cec169/href</a></iframe><h4><strong>Using Delegate Pattern</strong></h4><p>Here we know that LoginForm will be using TextFieldWithLabel so maybe we can create a property of type LoginForm and pass message directly to it. Then we will have to use a class function of LoginForm. If we create a SignupForm that will use TextFieldWithLabel, we will not have a way to pass message to it.</p><p>So we will need an interface that many class can implement if they are to use TextFieldWithLabel. Then we will use it as a delegate in our TextFieldWithLabel class.</p><ul><li>Lets create a TextFieldWithLabelDelegate with function textFieldShouldReturn() -&gt; Bool imitating UITextFieldDelegate.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fcfdbc3e75201cab516523adbf3736e/href">https://medium.com/media/4fcfdbc3e75201cab516523adbf3736e/href</a></iframe><ul><li>Now lets use this delegate inside TextFieldWithLabel. First TextFieldWithLabel needs to get notified from its textField then only it can notify its TextFieldWithLabelDelegate that return is tapped.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b10c45d46204734185a5957c9124c60/href">https://medium.com/media/4b10c45d46204734185a5957c9124c60/href</a></iframe><h3>Updating LoginForm</h3><ul><li>First remove username and password textField and label with creator methods. Then create a new creator method for creating usernameTextField and passwordTextField of TextFieldWithLabel type. Update addViews and addConstraints methods.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33892cd07894edbf65b1c146179de8c9/href">https://medium.com/media/33892cd07894edbf65b1c146179de8c9/href</a></iframe><p>Now lets make a TextFieldWithLabelDelegate for LoginForm. We usually implement protocol for delegate in the class using the view. We know that delegate is just a representative and theoretically representative can be anyone. Remember in a software company representative for a client can be a developer himself, or a project manager whose sole responsibility is to represent the company, or even a manager who also looks after the management. <br>Lets explore this theory by creating a separate class whose responsibility is only to represent LoginForm or implement TextFieldWithLabelDelegate. Lets call it TextFieldWithLabelDelegateForLoginForm.</p><ul><li>First copy all codes from the LoginForm extension where it implemented UITextFieldDelegate including dismissKeyboard. It can have whole LoginForm or just the views it needed. Lets just pass it username and password textfield through initialization and an editingView which is responsible for keyboard, to endEditing in dismissKeyboard.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d06f82c2d98e3beafbcf238ac35996a/href">https://medium.com/media/7d06f82c2d98e3beafbcf238ac35996a/href</a></iframe><ul><li>Now create a login variable of type function to pass message to LoginForm. This time lets use it as escaping closure in init.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63a6245f6d3c31b708a549b92ad6fffe/href">https://medium.com/media/63a6245f6d3c31b708a549b92ad6fffe/href</a></iframe><ul><li>Back to LoginForm, lets pass TextFieldWithLabelDelegateForLoginForm as a delegate to our TextFieldWithLabels. First create a textFieldWithLabelDelegateForLoginForm and initialize it with required fields and a closure that calls login function. Then pass it to username and password textfields as delegate.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2df81157d8d11a186fdf425d82cec2/href">https://medium.com/media/9c2df81157d8d11a186fdf425d82cec2/href</a></iframe><ul><li>Now remove the final error by creating a computed property text in TextFieldWithLabel.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af46eac3f0d0d5f393c50fca62a0cc9d/href">https://medium.com/media/af46eac3f0d0d5f393c50fca62a0cc9d/href</a></iframe><ul><li>If you run it, you will notice return is not working on usernameTextField, but works on passwordTextField. Problem is in this line passwordTextField.becomeFirstResponder(). It makes the view, TextFieldWithLabel, the first responder but not its textField. Lets override this function to make textField the first responder. Finally add @discardableResult to remove warning .</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bb8184cecf1fc80fb97f02aa8ba3e7b/href">https://medium.com/media/5bb8184cecf1fc80fb97f02aa8ba3e7b/href</a></iframe><h3>Still Confused??</h3><p>I would like to say it is normal. I had almost two years of professional iOS development and two apps in app store before it clicked to me. So have patience, explore as many resources as you can, don’t be afraid to ask your senior. Most importantly, when you are using delegate or protocol, try making sense of all the things you learned or heard about them. One day it will just click to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a1dee2e2ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Separating Views from ViewController]]></title>
            <link>https://medium.com/@aloksubedi/separating-views-from-viewcontroller-522f4439ef95?source=rss-8fde38e1f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/522f4439ef95</guid>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Alok Subedi]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 15:17:34 GMT</pubDate>
            <atom:updated>2021-08-11T15:17:34.365Z</atom:updated>
            <content:encoded><![CDATA[<p>ViewController in iOS is both view and controller, which makes it massive. Let’s separate View from ViewController.</p><p>We will use LoginFormViewController from my last article - <a href="https://medium.com/@aloksubedi/mvc-that-is-not-massive-991cb33bf2a5">MVC that is not massive</a>. Although this is a continuation of that project, you can go through this one independently.</p><p>You can download the starter project from <a href="https://github.com/aloksbd/View-From-ViewController">here</a> if you want to follow along.</p><h3>Project Overview</h3><p>We will work with LoginFormViewController which has textfields with sigInButton. It was separated from LoginViewController in the last article. SignupViewController and HomeViewController are for navigation and DummyThirdPartyLogin fakes login with Facebook and Google.</p><h3>LoginFormViewController</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a6649260abb6b0b9c6898aaad573f86/href">https://medium.com/media/7a6649260abb6b0b9c6898aaad573f86/href</a></iframe><p>While, almost half of the LoginFormViewController is about handling views, it would be awesome if the controller does not have to care about views.</p><h3>Separating View</h3><p>The idea is very simple; we create a view class that is responsible for creating and laying out views, then we add this view to ViewController. We can make multiple views or a single view per ViewController.</p><ul><li>Let’s start by creating a class LoginForm, which is a child of UIView. Copy all the views from LoginFormViewController with its creator methods.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab8bac496bc52838e36b35feee0df346/href">https://medium.com/media/ab8bac496bc52838e36b35feee0df346/href</a></iframe><ul><li>Next, bring the addView and addConstraints methods and call it from init.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09ff85b02a15067e982a305fee010971/href">https://medium.com/media/09ff85b02a15067e982a305fee010971/href</a></iframe><ul><li>Let’s fix the issues now. First, make LoginForm a UITextFieldDelegate by copying the extension of LoginFormViewController.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/722c554bd8a2fa30665d723973c19ea7/href">https://medium.com/media/722c554bd8a2fa30665d723973c19ea7/href</a></iframe><ul><li>We don’t have login function. Login is the responsibility of controller so we can not put it in view. We need to find a way to notify controller to call login. Let’s use closure this time. <br>Create an optional variable login of type function that takes no parameter and returns void. For signInButton action, let’s create an objc function loginTapped that calls login that we just created.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccdec1720b162903d753acd56640a6bd/href">https://medium.com/media/ccdec1720b162903d753acd56640a6bd/href</a></iframe><h3>Update LoginFormViewController</h3><ul><li>First, remove everything moved to LoginForm. Now create form of type LoginForm and add it to view and add constraints.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61f8cd6cddb6e2b722254a57027169ef/href">https://medium.com/media/61f8cd6cddb6e2b722254a57027169ef/href</a></iframe><ul><li>Setup the login variable of LoginForm. Make it a closure that calls login function in the controller.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e36e694fd7dcf304d55f856edb23add4/href">https://medium.com/media/e36e694fd7dcf304d55f856edb23add4/href</a></iframe><ul><li>Fix the issue in login function by creating computed properties username and password in LoginForm.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7741f9bf82c7881061b0eb0dceb98c82/href">https://medium.com/media/7741f9bf82c7881061b0eb0dceb98c82/href</a></iframe><p>Now that we have successfully moved view to LoginForm, LoginFormViewController is a lot smaller. Let’s go a step further, instead of adding the LoginForm, let’s just make it the view of LoginFormViewController. Then, remove form.translatesAutoresizingMaskIntoConstraints = false from the form. Remove addViews and addConstraints functions and add view = form in viewDidLoad instead.</p><h3>Exercise</h3><p>LoginForm has a label and textField combo for username and password. Try creating a new view TextFieldWithLabel. While you are at it, try making label and textfield private by creating TextFieldWithLabelDelegate.</p><h3>What Next?</h3><p>If we look at login function, we can see it is huge and has multiple responsibilities. We can create different functions for validation and different for data task. Even better, different class with particular responsibilities.</p><p>Take your time learning one technique at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=522f4439ef95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVC that is not massive]]></title>
            <link>https://medium.com/@aloksubedi/mvc-that-is-not-massive-991cb33bf2a5?source=rss-8fde38e1f6ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/991cb33bf2a5</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[massive-viewcontroller]]></category>
            <category><![CDATA[ios-beginner]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Alok Subedi]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 16:32:56 GMT</pubDate>
            <atom:updated>2021-08-11T04:31:04.807Z</atom:updated>
            <content:encoded><![CDATA[<p>I started my iOS development following Apple’s food rating app. iOS development was in an early stage in my country, so I was a solo iOS developer. MVC was my single source of truth. All the code should go in either of Model, View or Controller. My controller handled everything. That was how most of the tutorials taught.</p><p>My MVC rules were simple.<br>1) Model is a dumb data structure.<br>2) View is storyboard. Use separate file for view only if the inspector is not enough.<br>3) One ViewController is one screen. It handles everything that happens when you are on that screen, network call, persistence, business logic, rendering view, getting UI feedback.</p><p>We will look into how I used to write my earlier iOS apps and refactor it into multiple MVCs. You can download the starter project from <a href="https://github.com/aloksbd/Massive-ViewController-refactor">here</a> to follow along.</p><h3>Project Overview</h3><p>This is the UI of a login view we are creating. It is a pretty standard login view with app icon, app name, login form, third party login and sign up button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ojxaFnyYfh_UmZmy12GTAA.png" /><figcaption>UI for the login view</figcaption></figure><p>Open the project. We will work with LoginViewController. SignupViewController and HomeViewController are for navigation and DummyThirdPartyLogin fakes login with Facebook and Google.</p><h3>LoginViewController</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf19008f03143c4d2872e84a69cae8ce/href">https://medium.com/media/cf19008f03143c4d2872e84a69cae8ce/href</a></iframe><p>Let’s see what’s in this 236 lines of code.</p><ol><li><strong>Creation, addition and laying out views</strong><br>Apple’s ViewController is both view and controller so it is logical that LoginViewController creates and handles its views. There are first 53 lines for creating views and 178 to 236 (58) lines for addition and giving them auto layout constraints.</li><li><strong>UITextFieldDelegate<br></strong>It acts as UITextFieldDelegate to handle what to do when user taps return on keyboard for usernameTextField and passwordTextField.</li><li><strong>Hide keyboard when tapped anywhere on view<br></strong>It adds tap gesture to view and handles hiding of keyboard.</li><li><strong>Login<br></strong>Main job of LoginViewController. It first checks if username and password is empty, validates password is 8 characters or long, creates URLRequest with username and password, makes asynchronous URL request, handles the response. So much task in one function.</li><li><strong>Login with third party<br></strong>It configures third party login and handles the response.</li><li><strong>Show error<br></strong>It shows error in form validation or login failure.</li><li><strong>Navigation<br></strong>It creates the viewController and present them. Home view on successful login and signup view when user taps sign up button.</li></ol><p>These are the responsibilities of LoginViewController and seven reasons it is massive. Lets refactor it now.</p><h3>Sevaral Smaller MVCs</h3><p>My understanding of MVC like many other fellow iOS developers, was “One Screen = One MVC”. Oh, I was wrong. We can have separate smaller MVCs, as small as one view, one model and one controller, and compose them on one big MVC.</p><p><strong>How to separate them?</strong></p><h4>See if a part can exist as a single screen.</h4><p>We can clearly see that login form, including login button, can exist as a single screen. Let’s create a separate MVC for login form.</p><ul><li>Create a new class LoginFormViewController, and copy the views necessary for login form along with creator methods.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37aaa2cbf7947542a37efe6b3b028ed3/href">https://medium.com/media/37aaa2cbf7947542a37efe6b3b028ed3/href</a></iframe><p>We got some errors, let’s fix them.</p><ul><li>Copy text UITextFieldDelegate extension from LoginViewController to LoginFormViewController. It asks for ‘dismissKeyboard’ function, copy that as well.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e40a0789729665500f5709899a488b5/href">https://medium.com/media/9e40a0789729665500f5709899a488b5/href</a></iframe><ul><li>Now move the ‘login’ function to LoginFormViewController. We don’t have ‘showError’ and ‘openHomeView’ methods. Error label is in LoginViewController and navigation to HomeView too, so we cannot just copy those methods. Delegate pattern to the rescue. Lets create a LoginFormViewControllerDelegate and use it to notify errorOnLogin or loggedIn.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9462751bc7341ff753e384848b086aa5/href">https://medium.com/media/9462751bc7341ff753e384848b086aa5/href</a></iframe><ul><li>Add and layout the views. Remeber to pin the top and bottom of viewController’s view to username signInButton. I have also removed trailing and leading space, so the view remains tight and open for spacing in parent view.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d592b0cfa2cbc485a934ccb0261b5364/href">https://medium.com/media/d592b0cfa2cbc485a934ccb0261b5364/href</a></iframe><ul><li>Clean up LoginViewController. Remove the views moved to LoginFormViewController, and addition and layout of those views, UITextFieldDelegate, and login function.</li><li>When error free, add LoginFormViewController as a child.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774cff1213fa983e91f238b979ded27a/href">https://medium.com/media/774cff1213fa983e91f238b979ded27a/href</a></iframe><ul><li>Make it LoginFormViewControllerDelegate to show error and open homeViewController.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e26d3b74f37656f8263218b8158b769/href">https://medium.com/media/6e26d3b74f37656f8263218b8158b769/href</a></iframe><ul><li>Add and layout the loginFormView.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97de0b4e6861504b6b369c4610c664c4/href">https://medium.com/media/97de0b4e6861504b6b369c4610c664c4/href</a></iframe><p>Now we have a smaller MVC that handles login and is UITextFieldDelegate, two fewer responsibilities for LoginViewController. We added two extra responsibilities of creating LoginFormViewController and acting as its delegate. We can use composer and dependency injection instead.</p><h3>Exercise</h3><p>Now that we separated a LoginFormViewController, how about we create a MVC for google and facebook login? Try it.</p><h3>What next?</h3><p>We just separated a big MVC to smaller MVCs, yet we are a long way to have a cleaner code. We can move dependency creation to dependency injection, navigation responsibilities to the router or coordinator, URLSession task to api service, view creation, addition and layout to separate view classes and other techniques.</p><p>The idea is to reduce responsibilities from massive viewController by learning one technique at one time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=991cb33bf2a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>