<?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 Dhruvik Chevli on Medium]]></title>
        <description><![CDATA[Stories by Dhruvik Chevli on Medium]]></description>
        <link>https://medium.com/@dhruvik.chevli?source=rss-757271a2e3fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MKV7LOcUKjd6M-bQXsOfIA.jpeg</url>
            <title>Stories by Dhruvik Chevli on Medium</title>
            <link>https://medium.com/@dhruvik.chevli?source=rss-757271a2e3fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:10:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhruvik.chevli/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[Swift Part 9 — Working with UIAlertController]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-9-working-with-uialertcontroller-c0726a84eb56?source=rss-757271a2e3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0726a84eb56</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[uialertcontroller]]></category>
            <dc:creator><![CDATA[Dhruvik Chevli]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:13:31 GMT</pubDate>
            <atom:updated>2020-05-31T08:27:44.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 9 — Working with UIAlertController</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktuu1bw0WImg3BbiTQyo7w.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the ninth article of the series <strong>IECSE Crash Course: Development with Swift</strong>. Through the course of 10 articles, we are going to make a small app which will display a set of users that we will fetch from the net. While making the app, we will cover some of the most important topics that every iOS developer must know. You can get the code till the previous article<a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article8/Users"> here</a>.</blockquote><p>In this tutorial, we’re going to go through one of the building blocks for any app, the <strong>UIAlertController</strong>. This is the class that helps us in showing alerts, responding to user actions and taking text inputs.</p><p>According to the Apple Documentation,</p><blockquote>An object that displays an alert message to the user.</blockquote><h3>Alerts</h3><p>The first step of using the AlertController is to instantiate it.</p><p>let alertController=UIAlertController(title: String, message:String, preferredStyle:UIAlertController.style)</p><p>The <em>title</em>, as the name suggests is the title of the AlertController that will pop up on the screen. Message is the description for the AlertController.</p><p>AlertControllers help us in presenting alerts and Action Sheets, <strong>Action Sheets</strong> are another specific type of alerts that appear in response to a control or action and presents a set of two or more choices related to the current context. We’ll have a look at ActionSheets in the latter part of this article.</p><p>In our Users app, in SampleScreen.swift, we are going to use the UIAlertController to handle the errors when the User doesn’t fill in all textFields properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6T4EeE9mpdJ2vHAoIX_5w.png" /></figure><p>addAction(_:) is where we add the buttons/actions that the user can take. The UIAlertAction takes 3 parameters, title, this is the text that’ll go on the buttons. Style has 3 enum options,</p><ul><li>.default.</li><li>.cancel, this is used to give the user a choice to go back to the previous screen if the user has made some mistake,</li><li>.destructive, this makes the text in the button appear in red, its supposed to tell the user that the action that’s going to be taken is dangerous and it cannot be undone.</li></ul><p>The next parameter is the handler, which can either be a closure which will be passed or you can pass a function too.</p><blockquote>Try and make the title of all the actions as concise as possible as there is not much space on the buttons in an AlertBox.</blockquote><p>In the last line, we <strong><em>present</em></strong> this AlertController <em>on top of our viewController</em>.</p><p>Now, if we run the app and Press the <strong>Add User</strong> button on our Sample Screen without pressing filling all the fields, we get an alert that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*DGBoK1A7X1DIVIgIaf8G6g.png" /></figure><p>We can add more actions with addAction function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avWboTOjXJ7-COC1BY_Y7A.png" /><figcaption>Make a note of how we use different styles for each action here.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*ZQN0Y0KF_SCzaacDDDDzxQ.png" /></figure><p><em>As you can see, the action with style cancel always stays at the bottom irrespective of what order you add the actions in.</em></p><h3>Adding TextFields</h3><p>We can also add textFields to our alerts and ask for input from the user and then handle them accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHtUYfXO5snzJfIvvJJKrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*iBmUVtOXPf36ivQ3zEqkKA.png" /></figure><h3>Action Sheets</h3><blockquote><em>An action sheet is a specific style of alert that appears in response to a control or action and presents a set of two or more choices related to the current context. Use an action sheet to let people initiate tasks, or to request confirmation before performing a potentially destructive operation.</em></blockquote><p>We can use an action sheet by changing the preferred style of our controller to <strong>.actionSheet</strong>.</p><p>Adding actions to the controller is done in the same way that we did before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JID6dlalEer_plqZf5nZ8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*7shwRyYWDzieFkl_TcNM4g.png" /></figure><p><strong><em>Action sheets</em></strong> have three benefits over alerts:</p><ul><li>They slide up from the bottom of the iPhone screen, so you can reach the action sheet buttons with your thumb. Easy!</li><li>You can fit more text on the button, compared to the alert style.</li><li>Usually, you need <em>less</em> text than an alert, because the action sheet buttons are self-explanatory.</li></ul><h4>Wrapping Up</h4><p>We’re only going to keep the alert popup we wrote in the beginning in our app. You can get see the final project over here. In this article, we’ve taken a look at the different ways that we can work with UIAlertController. You can continue with the series in the <a href="https://medium.com/iecse-hashtag/swift-part-10-storing-data-using-disk-8d1d31022ba9">final</a> article where we learn about storing data!</p><h4>Congratulations 🎉! You have just finished the 9th tutorial!</h4><p>All of the above-written code is available on <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article9/Users"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0726a84eb56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-9-working-with-uialertcontroller-c0726a84eb56">Swift Part 9 — Working with UIAlertController</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Part 8 — Passing Data Between ViewControllers Using Delegates]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-8-passing-data-between-viewcontrollers-using-delegates-80184fca91e6?source=rss-757271a2e3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/80184fca91e6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[passing-data]]></category>
            <category><![CDATA[swift-delegate]]></category>
            <dc:creator><![CDATA[Dhruvik Chevli]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:13:09 GMT</pubDate>
            <atom:updated>2020-05-31T08:27:09.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 8 — Passing Data Between ViewControllers Using Delegates</h3><blockquote>In this tutorial, we are going to look at how we can pass data between ViewControllers.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9qhV-hYw-3jPrbd8Vz9qA.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the eighth article of the series <strong>IECSE Crash Course: Development with Swift</strong>. Through the course of 10 articles, we are going to make a small app which will display a set of users that we will fetch from the net. While making the app, we will cover some of the most important topics that every iOS developer must know. You can get the code till the previous article <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article7/Users">here</a>.</blockquote><p>The official documentation of Apple defines delegation as:</p><blockquote>Delegation is a design pattern that enables a class to hand off (or “delegate”) some of its responsibilities to an instance of another class.</blockquote><p>In simple terms, what <strong>delegation</strong> means is that a viewController delegates one of its task to some other viewController. Once that task is completed by the other viewController, the other viewController sends a notification to the original viewController that the task has been completed.</p><p>In our last article, we made a form in a viewController where we made a new object of struct User. Now, we are going to try and pass the created user to the original TableViewController from the SampleScreen so that we can display in our tableView.</p><p>You can get the code for the app from where we will start by cloning <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp">this repository.</a></p><p>For us, the TableViewController will delegate the work of making a user object to SampleScreen, i.e, a user object will be made in the form that we made in the<a href="https://medium.com/iecse-hashtag/swift-part-7-making-a-form-with-validation-4ee72f321ac4"> last</a> tutorial and then pass this object back to TableViewController once the object is made.</p><h3>Protocols</h3><p>A <strong>protocol</strong> defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.</p><p>What this means is that protocols have to define a set of rules or requirements, i.e functions and properties. Any class that inherits the protocol needs to conform to it. A class that inherits a protocol should have all the functions and properties that the protocol defines, otherwise, iOS will throw an error.</p><p>In the first step-in the file SampleScreen.swift, we are going to define a protocol, <strong><em>passingUser</em></strong>, which will have one function, <strong><em>passUser</em></strong>(This protocol will be <em>global</em>). This function will be called whenever the user object is created by the form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*NKOWCVJzfqBjLzmR7sMbcg.png" /></figure><p>Second, we’re going to incorporate delegation into SampleScreen class. For this, we create a delegate property in the SampleScreen class and this should be <strong><em>optional</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*LU-DJUUwVCHFy-h32Svy2Q.png" /></figure><p>Next, we are going to make the call to passUser with the user object that we have created. As you can guess, this will go inside our <strong>addUser</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neQZtUdkES-XcuHIo9z_4w.png" /></figure><p>Here, we call our passUser function and pass the user that we just created. And after that, we remove the current ViewController from our navigationController by dismiss(..).</p><p>If we now build our app, it’ll still work fine but it won’t pass the data yet. This is because we haven’t <em>initialized</em> the delegate yet. This is why we made the delegate optional in SampleScreen. It’ll start working fine after the next few steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*AW5cNCMNZe0DrlO26Wv-3Q.png" /></figure><p>Next, we make our TableViewController conform to <strong>passingUser</strong>, once you do this your app will be broken till the next step. This is because as we discussed before, once a class conforms to a protocol, it should have all the functions defined in the protocol. For example, until we add the function <strong>passUser(user:User)</strong>, iOS will not let us build our app. Basically here, we are making the TableViewController as the delegated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ty6O8NSIYcUw0wVdvWOG4Q.png" /></figure><p>We call the passUser function with the user that was just created. You can think about this function as the function that is executed once you have the new user object. Here, we add the user that we just received to our users array. But even if the user has been added to the users array, it won’t visible yet. For that we’ll have to reload the data in our tableView, that is what tableView.reloadData() does.</p><p>Finally, even though our TableViewController conforms to PassingUser, it still won’t work as the delegate that we had made optional in the SampleScreen class still hasn’t been initialized. We do this just before presenting our SampleScreen.</p><p>In our goToSecondScreen(), we have already made an instance of sampleScreen, here we add sampleScreen.delegate = self, this is to initialize the optional delegate that we had in our SampleScreen class to self. But the self that we refer to over here isn’t SampleScreen, it is TableViewController, the delegated.</p><h3>Why use Delegation?</h3><p>Why use delegation <em>at all</em>? It seems overly complicated, to just pass data back and forth in your code.</p><p>A few reasons in favor of delegation:</p><ul><li>Delegation, and the delegation pattern, is a lightweight approach to hand-off tasks and interactions from one class to another.</li><li>You only need a protocol to communicate requirements between classes. This greatly reduces coupling between classes.</li><li>And it separates the responsibilities of the class that generates interactions from the class that responds to these interactions.</li><li>Delegation is useful for 1-on-1 relationships, ie when one ViewController needs something it delegates it to the other ViewController and this delegate and sends the result back to the ViewController that delegated it the task.</li></ul><h4>Wrapping Up</h4><p>In this article, we have looked at how we can pass the data around in our app between 2 viewControllers. You can find the code over <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article8/Users">here</a>. Now if we build our application and fill the form and click on addUser, we will be redirected to our tableView and now it’ll have the user that we just created. You can continue with the series in the <a href="https://medium.com/iecse-hashtag/swift-part-9-working-with-uialertcontroller-c0726a84eb56">next </a>article where we learn to work with a UIAlertController!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*8b7CbO85A8TAMiHgEhNigw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*LKa7HtxQSK0dxirdu60fjA.png" /></figure><h4>Congratulations 🎉! You have just finished the 8th tutorial!</h4><p>All of the above-written code is available on <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article8/Users"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80184fca91e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-8-passing-data-between-viewcontrollers-using-delegates-80184fca91e6">Swift Part 8 — Passing Data Between ViewControllers Using Delegates</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Part 7 — Making a form with validation]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-7-making-a-form-with-validation-4ee72f321ac4?source=rss-757271a2e3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ee72f321ac4</guid>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Dhruvik Chevli]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:12:40 GMT</pubDate>
            <atom:updated>2020-05-31T08:25:28.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 7 — Making a form with validation</h3><blockquote>In this article, we are going to look at how we can make a form and validate it in Swift.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvu0MlXIrElcKIgQprfSBQ.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the seventh article of the series <strong>IECSE Crash Course: Development with Swift</strong>. Through the course of 10 articles, we are going to make a small app which will display a set of users that we will fetch from the net. While making the app, we will cover some of the most important topics that every iOS developer must know.</blockquote><p>If you haven’t been following the whole course, I’ll request you to go through and clone this repository as we are going to start from <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article6/Users">here</a>.</p><p>Up till now, we have already presented the <em>viewController</em> in a <em>navigationController</em>. We’ll make the form in this viewController. So now, let’s have a look at how we are going to make the form!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*dh3_Wuae3TbnK2lJvkPjSQ.png" /><figcaption>SampleScreen.swift</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*CQ7HXMAsgrvhOQVSZZ0PHw.png" /><figcaption>struct User, we will be making an object of this.</figcaption></figure><p>In our form, we are going to have <em>6 textfields</em> and are going to make a User object when submit button is pressed.</p><p>First, let’s make all the elements that we are going to need.</p><ol><li><strong>One label</strong> that tells the user what the form is about.</li><li><strong>Six TextFields</strong>, one for each field for our User.</li><li><strong>One submit button</strong>.</li></ol><p>Now that we know what elements our ViewController is going to have embedded in it, let’s start making the ViewController. We’ll write this code in the SampleScreen class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_wPW6JdSu0AOBTnk7Eo3g.png" /></figure><p>In the above lines, we make a label that will work as a title to our viewController.</p><p>Before we start making the textfields, let’s take a look at the class UITextField. All the textfields that we are going to make are going to be objects of this class. Also, iOS allows us to configure and make several changes to our textfields. For this article, we are going to make one global function that will be responsible for configuring the textField.</p><p>Let’s first look at the function and then try and understand the lines of code in the function. This function will go outside our SampleScreen class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uJpaA2La6pCu481MUTB0w.png" /></figure><p>The function setUpTextField requires 2 parameters, one is the textField that we want to configure and the other is the placeholder that we want to represent in our textField. Let&#39;s try and understand the code line by line. As we can see, most of the instance properties are self-explanatory, I’ll only be explaining certain properties that are important and a little difficult to understand.</p><ul><li>textField.translatesAutoresizingMaskIntoConstraints = false , like we have also done previously, this is done so that we can manually set Anchor Constraints for our textField.</li><li>textField.placeholder = placeholder, this is the line where we configure what the placeholder should be for our textField. This placeHolder is one of the parameters that we received in the function.</li><li>Sometimes, when we tap on a textField, Phone Number, for example, you might want the keyboard that appears to be numeric. textField.keyboardType, is where we define the type of keys that you want to appear on the keyboard by default when the user clicks on a textField.</li><li>returnKeyType is the instance property that sets up the title of the return key on the keyboard.</li><li>If we want to change the colour of the textField, the syntax of attributedPlaceholder is how that is done.</li><li>If we want to change the colour of the border of the textField, it can only be done when you give your border some width.</li></ul><p>Now that we have a function that configures our textField, let’s make 6 instances for the textFields that we are going to need in our ViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTfJHe1m-8CTuiNyexwHQg.png" /></figure><p>Here, for every textfield that we instantiate, we call the setUpTextField function with the placeholder that we want the textfield to have.</p><p>Next, we add the submit button, which will be an object of <strong>UIButton</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRcbflVbxiHo73_oRqP6yQ.png" /></figure><p>Most of the code is responsible for configuring the appearance of the button. The line that interests us most is button.addTarget(..), which tells the button what function to call when it is pressed.</p><p>The syntax for this is,</p><p><em>button.addTarget(self, action: #selector(&lt;functionToBeCalled&gt;),for: .touchUpInside)</em></p><p>All the functions that you call from a button need to be exposed to Objective-C, that is what @objc does. For now, we are going to leave this function empty.</p><p>Once we are done with all this, we need to add these elements that we have instantiated into our SampleController. So as you might have guessed we do this in the function viewDidLoad(). We are going to set the elements up in our ViewController depending on how we want our view to look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4PurtGq_hjvJTq8iQg91Q.png" /></figure><p>Once, we add all our elements to the SampleController, we call the function setUpView(). It’ll be in this function that we will set up constraints for all the elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMDd3cKnQbRPbaVBV6KWng.png" /></figure><p>Here, we have made an additional function setUpTF(_ tf:UITextField), so that we can avoid a little redundancy as many constraints for all the textFields are going to be same to maintain uniformity.</p><p>If you have doubts about the <strong>Auto Layout and constraints</strong>, I suggest that you go check out <a href="https://medium.com/iecse-hashtag/swift-part-2-custom-tableview-cells-43a540e9ed3a">this</a> article.</p><p>With this step our form is ready and all that is left is for us to write the function addUser, which we will do in the next section. If you have followed all the steps correctly until now, your SampleScreen looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*8fXVbVI8_19Jl_wOdWEsnQ.png" /></figure><h3>Validation</h3><p>When the submit button is pressed, we might want to make sure that all the fields are properly filled so that we have all the required fields to make our object. This is where validation comes in. Let’s have a look at how our addUser function looks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMmrAU4FH9N6y29m65vDfQ.png" /></figure><p>First, we make a custom error, this is the error that we are going to throw when the user presses the button without all the fields.</p><h3>Do-try-catch</h3><p>In Swift, error handling is done with the <strong>do-try-catch</strong> block to respond to recoverable errors in our code. As per our need, what we want to do is make sure that all the fields are filled before we make a User object. The do-try-catch block can be thought of as an <em>if-else conditional</em>. When we put some statement in do, we try certain things that we know might give an error. When that happens we throw the appropriate error and we leave the do block and enter the catch block, this is where we handle the error appropriately.</p><p>The do-try-catch block is preferred because the other alternative would be to force-unwrap the object, but when you do that it means that your app will crash if the unwrapped value is null. Hence, that is only done when you are sure that the value you are unwrapping will not be nil. <em>Avoid force-unwrapping as much as possible.</em></p><p>In our code, we also use the <strong>guard</strong> statement. This can also be imagined like an if-else block. What happens here, is that if the condition after the guard statement is evaluated to false, the else block is invoked. One thing to note when using guard, is that it can only be used to “<em>transfer program control out of scope</em>”. This is a fancy way of saying that the body of the guard block, i.e. what’s inside the squiggly brackets, needs to exit the function. Hence in the else block, you are only allowed to use the following :</p><ul><li>return, to exit a function or closure</li><li>break, to exit a loop like for</li><li>continue, to continue to the next loop iteration</li><li>throw, to exit a function and throw an error.</li></ul><p>In our code, what we do is try to unwrap the text in all the textFields one by one, there is a good chance that one of the textFields might be empty and give nil on being unwrapped, this is the case where our else block gets executed. It is this else block that we throw an error.</p><p>Once we have taken care of all the fields that we need, ie if we have not entered the else block of the guard statement, we will make our object. So before we can make the User object, we are going to make an object for the city and company of struct Address and Company. We will use these objects to make the object for our new user.</p><p>Next, we reset all the other fields so that new data can be entered.</p><p>It is in the catch block where we will take care of the case that an error was encountered while unwrapping the values, ie if one of the textFields was empty. Here, we are just going to print the error. But actually, we can also make a pop up that asks the user to fill in the fields properly.</p><h4>Wrapping up</h4><p>In this tutorial, we have seen how we can make forms and validate them. We created an object for user which in the <a href="https://medium.com/iecse-hashtag/swift-part-8-passing-data-between-viewcontrollers-using-delegates-80184fca91e6">next</a> tutorial we are going to pass to our ViewController and we will add this user to our tableView using Delegates.</p><h4>Congratulations🎉! You have completed the 7th tutorial!!</h4><p>All of the above-written code is available on <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article7/Users"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ee72f321ac4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-7-making-a-form-with-validation-4ee72f321ac4">Swift Part 7 — Making a form with validation</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Part 5 — Networking with URLSession]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-5-networking-with-urlsession-6b56783f289a?source=rss-757271a2e3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b56783f289a</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Dhruvik Chevli]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:11:35 GMT</pubDate>
            <atom:updated>2020-05-31T08:22:41.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 5 — Networking with URLSession</h3><h4>In this article, we’re going to see how we can fetch data from an API by using URLSession.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kfaF_Oet9WNFipt6xqe-g.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the fifth article of the series <strong>IECSE Crash Course: Development with Swift</strong>. Through the course of 10 articles, we are going to make a small app which will display a set of users that we will fetch from the net. While making the app, we will cover some of the most important topics that every iOS developer must know.</blockquote><p>In the<a href="https://medium.com/iecse-hashtag/swift-part-4-navigationbar-and-codable-6acc41953a1f"> last</a> tutorial, we saw how to make structures for the data that we are going to receive from the API and we have this structure ready in our project. If you haven’t been following the whole course, I suggest you go through the code <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article4/Users">here</a> and clone it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WW2hdAp6E1JXX5bfbKl8g.png" /><figcaption>Struct User</figcaption></figure><p>We’ve made this structure according to what “<a href="https://jsonplaceholder.typicode.com/users">https://jsonplaceholder.typicode.com/users</a>&quot; sends to us. Now we are going to try and get the User data from here and display it on our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJpJ9Q7jvNGc23cyvbJVLw.png" /><figcaption>The json object we receive from our API</figcaption></figure><h3>Networking and REST APIs</h3><p>Whatever data we see in the apps we use comes from the internet. This is where networking and APIs come in. This exchange of data between the device and a server is called networking. <strong><em>REST</em></strong> is basically a type of architecture that allows us to create services and applications that can be used by any device or client that understands HTTP. For example in our case, we will make a get request on <a href="https://jsonplaceholder.typicode.com/users">https://jsonplaceholder.typicode.com/users</a> and this will return to us the data in the form of a JSON Object. Knowing this much is enough for us right now but if you want to understand the <strong><em>REST APIs</em></strong> a little better, give <a href="https://medium.com/@basterrika/lets-understand-what-an-api-is-7072eb091e76">this</a> a read.</p><h3>URLSession</h3><p>Since iOS 7, the default way of making an HTTP Networking Request is by using a class <strong>URLSession</strong>. The URLSession class is actually part of a group of classes that work together to make and respond to HTTP requests.</p><p>URLSession includes a number of core classes. This is how the environment works:</p><ol><li>You use URLSession to create a session. You can think of a session as an open tab or window in your web browser, which groups together many HTTP requests over subsequent website visits.</li><li>The URLSession is used to create URLSessionTask instances, which can fetch and return data to your app, and download and upload files to webservices.</li><li>You configure a session with a URLSessionConfiguration object. This configuration manages caching, cookies, connectivity and credentials.</li><li>To make a request, you create a data task, of class URLSessionDataTask, and you provide it with a URL, and a completion handler. This is a closure that’s executed when the request’s response is returned to your app. (We’ll talk about closures in a while)</li><li>When the completion handler is executed, you can inspect the returned data and take appropriate action, such as loading the data into the TableView, like we will be doing in a while.</li></ol><p>We can think of URLSession as a factory that produces certain URLSessionTask and each task is responsible for a networking request.</p><p>We can make 3 kinds of requests with URLSession:</p><ul><li><strong>Data tasks:</strong> send and receive data with URLSessionDataTask, by using NSData objects. They’re the most common for webservice requests, for example when working with JSON.</li><li><strong>Upload tasks:</strong> send files to a webserver with URLSessionUploadTask. They’re similar to data tasks, but URLSessionUploadTask instances can also upload data in the background (or when an app is suspended).</li><li><strong>Download tasks:</strong> download files from a webserver with URLSessionDownloadTask by directly writing to a temporary file. You can track the progress of file downloads, and pause and resume them.</li></ul><p>We’ll look at the rest of the theory as and when we need it. So, let’s get back to building our app!</p><p>First, we make a new file “<em>Networking.swift</em>”. This file will be a networking layer i.e. this is the file where we will make all the networking calls for out app.</p><p>Let’s set up a few things in this file, before we make our GET request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muuukrMxclvzkVgNKda7gg.png" /></figure><p>When you look at this code the first time, it seems broken. One might wonder how can we make sharedInstance an object of structure <em>Networking , </em>when it itself is inside the struct <em>Networking</em>. And you are not wrong to be thinking that. But what we have written here, is called a <strong>Singleton</strong>. A singleton is an object that should only be created once and then be shared everywhere it has to be used. So, the struct Networking creates an instance of itself as a static variable, which means the only instance of the Networking struct is the one it created: Networking.sharedInstance. This is the only instance of Networking that will be used throughout our app to make networking calls.</p><p>The next line, let session = URLSession.shared, with this we get a reference to URLSession by invoking shared of URLSession class. This returns a shared session object, which again is a singleton.</p><p>In the last line the URL, we are going to make the get request. Before we make the final networking call, we are going to try and understand all the other basics that make understanding the network call very easy.</p><h3>Closures And Completion Handlers</h3><p><strong>Closures</strong> are self-contained blocks of functionality that can be passed around and used in your code. What this means is that you can pass functions as an argument to other functions. The function that you pass may be used at some point of time by the function that it is passed to. These can also be considered as <em>Nested Functions</em>.</p><p><strong>Completion Handlers</strong> can be thought of as the closures that are executed once the function’s body is executed, i.e. Whenever a function with a completion handler finishes (the isFinished property of the function changes to true), the completion handler code is executed. It is very useful when dealing with functions which can take quite a bit of time, such as network calls.</p><h3>@escaping</h3><p>When you define a closure as <strong>@escaping</strong>, you want the closure to be preserved into memory. As you want the closure to be executed once the function with the closure has been executed. Like here, we want the closure to be executed once we have received the JSON data from the API.</p><p>For a better understanding of closures, visit <a href="https://medium.com/@bestiosdevelope/what-do-mean-escaping-and-nonescaping-closures-in-swift-d404d721f39d"><strong>here</strong></a>.</p><p>We’ll understand this better once we look at the code. Let’s have a look at the syntax for making a networking call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSbY7pN0AVheNOE_YqV4sw.png" /></figure><p>Now when we look at the function getUsers, we have defined an escaping closure in this code, ie this gets executed when the getUsers has been executed. The completion handler here returns us<strong><em> Result</em></strong>.</p><p>Let’s take a second and understand what Result means over here. With Swift 5.1, Apple introduced Result type in its library, it was basically used to deal with ambiguity when we are waiting for the data to be received from an API. At this point we do not know whether data was received or if it is going to return an error, this is where <strong><em>Result</em></strong> comes in.</p><p><strong>Result</strong> type is implemented as <em>enum</em>, it has two cases,</p><ol><li><strong><em>.success</em></strong>, this helps you in returning the data that was received.</li><li><strong><em>.failure</em></strong>, this helps you define and return proper errors.</li></ol><p>Here, Result will return an array of Users if the function call was successful or a user defined error if there was a failure.</p><p>Next, let’s try and understand what is happening inside the function.</p><ul><li>guard let UserURL = URL(string: userURL) else { ..} , here the <strong><em>guard statement</em></strong> helps us deal with errors, i.e. if the string could not be converted to a URL, only then the <strong>else</strong> block is executed and this is where we throw an error.</li><li><em>When you use guard else statements, make sure that we return something or exit the scope. As execution cannot be continued if the condition associated with it is false or cannot be executed.</em></li><li>In this, we are just converting our string to a URL. If the string is not converted we throw an error, however this will never happen for us as we know the string that we have defined will work fine.</li><li>It is the next line where we use URLSession and create a <strong>dataTask</strong> with the URL, this is going to return data to us as JSON if it is successful, otherwise, it’ll give us an error. Hence, we try and unwrap this JSON data, and we call this jsonData, if this fails and there is no data to unwrap, we return the Result as “<strong><em>.failure</em></strong>” with the user defined error.</li><li>If the above line did not result in an error, this means that we now have the data that the API sent as JSON, now we need to parse it and return the array of type User as Result “<strong><em>.success</em></strong>”. We do this with the help of JSONDecoder.</li><li>If a failure occurs here, we return the error again.</li><li>Last but not least, we schedule the data task by invoking <strong><em>resume()</em></strong> on the data task. This is often overlooked by developers that are new to URLSession, but your <em>network call will not get executed if resume is not invoked</em>.</li></ul><p>With this, our Network call is done and when we call the function getUsers, we will either get the array of type User or the appropriate error.</p><h3>Let’s see the results</h3><p>Finally, we are going to make a few changes in TableViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-eZNcDp0tOWYrJvZLl76A.png" /></figure><p>Let&#39;s try break down and understand what&#39;s happening here.</p><ol><li><strong><em>Dispatch Queues</em></strong> basically are queues to which our apps submit tasks that have to be carried out. Here, where initially we were defining an empty array, now we pass a closure that checks if the array was set, in case it is then it asks the Main DispatchQueue to reload the tableView so that the newly fetched content can be displayed.</li><li><strong><em>func fetchData</em></strong> is the function where we make the network call and receive either the array of type User or the error.</li><li>We make the function call as “<strong><em>Networking.sharedInstance.getUsers{..}</em></strong><em>”</em>, where we receive the result. The result will always have to be of type [weak self], as the closure we sent was @escaping, we check the type of result with switch case, if its success we set our array Users to the array that is returned by the network call.</li><li>Here, we use <strong>weak self</strong> so that once the Network call is made, our app does not hold any references to Networking as we won’t be needing that class once the data has already been loaded. This basically takes care of memory leaks.</li><li>We call the <strong><em>function fetchData()</em></strong> once the view is loaded in the window.</li></ol><p>Now, if you run the app, you should get the data that we have received.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*8ATMw5_VqcYbg5edH2RMgg.png" /></figure><h4>Wrapping Up</h4><p>In this article, we have learned to fetch data from an API, and display them in our apps. You can continue with the series in the<a href="https://medium.com/iecse-hashtag/swift-part-6-tab-bar-controllers-6a4cf8bc633d"> next</a> article where we play with tab bars and navigation controls.</p><h4>Congratulations 🎉! You have just finished the fifth tutorial!!</h4><p>All of the above-written code is available on <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article5/Users"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b56783f289a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-5-networking-with-urlsession-6b56783f289a">Swift Part 5 — Networking with URLSession</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Part 3 — The Dark Mode]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-3-the-dark-mode-ddf16eb01651?source=rss-757271a2e3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddf16eb01651</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dark-mode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[programmatic]]></category>
            <dc:creator><![CDATA[Dhruvik Chevli]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:10:08 GMT</pubDate>
            <atom:updated>2020-05-31T08:19:42.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 3 — The Dark Mode</h3><blockquote>In this article, we will discuss Dark Mode in iOS. We’re going to try and understand how the Dark Mode works, and what are the best practices while making an app that supports both light and dark modes.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*du75P6kh1BjQ-A1oId0uVw.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the third article of the series <strong>IECSE Crash Course: Development with Swift</strong>. Through the course of 10 articles, we are going to make a small app which will display a set of users that we will fetch from the net. While making the app, we will cover some of the most important topics that every iOS developer must know. You can get the code till the previous article <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article2/Users">here</a>.</blockquote><p>With the release of iOS 13 and Xcode 11, Apple introduced the<strong> Dark Mode</strong>. The Dark Mode adds a darker theme to an iOS device while allowing us to do the same for the apps on that device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*gK2grezwgPrn998GJoPKEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*xLijPcNDXaNLSx1clAC5DA.png" /></figure><p>In their device settings, users can select Dark Mode as their default interface style. As this choice is made for the entire system, it is normal for users to want all the apps to comply with the system preference of their choosing.</p><p>As a developer, you are responsible to develop an app suitable for light as well as dark modes. It might so happen that an app might not look as good in Light UI as it does in Dark UI, or vice-versa. So, it is recommended to test your app in both settings.</p><p>There are two requirements for your app to support Dark Mode :</p><ol><li>It has to be built and released with Xcode 11 or later.</li><li>Only the devices running <strong>iOS 13.0</strong> (or later) support Dark Mode.</li></ol><p>After these are met, you need to switch to Dark Mode in your device settings. The UI for your app will automatically switch the appearance.</p><p>Now, let’s look into the features of how we can use and develop apps that look good in both, light and dark modes.</p><p>To enable dark mode while testing, you will have to first go to <strong>Settings</strong>. Under the <strong>Developer section</strong>, make sure that the <strong>Dark Appearance</strong> option is <strong>on</strong>. Once you do this, all your apps will automatically change their UI appearance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*ZAam6wLaeUmwiQLWzfDuog.png" /></figure><p><em>For a user, an app which does not comply with system-wide preferences might be inconvenient. They might also think that the app is not working. Along with this, it is difficult on the eyes to switch modes for only one app.</em></p><h3>How to manage the colors</h3><p>The colors that work well in a light appearance may be hard to see in a dark appearance and vice versa. The light and dark interfaces use very different color palettes. Apple came up with a solution so that we don’t have to design separate interfaces for different system preferences.</p><p>With Xcode 11 and iOS 13, Apple introduced colors that adapt automatically to the underlying interface style. Instead of using fixed shade colors, it is advised to use system colors, these are the colors that adapt automatically to the system preferences. You can read about them <a href="https://developer.apple.com/documentation/uikit/uicolor/ui_element_colors">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wm0RI3iqtZ8OYAAjfYeJNw.png" /><figcaption>Some System Colors</figcaption></figure><p>Apart from these system colors, with iOS 13, a range of 6 opaque <em>gray colors</em> were also introduced. These also adapt to the system preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7TzZFTW9OQZia0PQoR9hA.png" /><figcaption>The Grays that also adapt colors depending on the appearance</figcaption></figure><h3>Semantic colors</h3><p>When we talk about labels, textfields, and different components, it is obvious that the change of system preference will also affect their visibility. Hence, here, it is advised to use <strong>Semantic</strong> Colors that again change according to the appearance modes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiapMouHgko_VC2vOwUcLQ.png" /><figcaption>The Semantic Colors and their uses</figcaption></figure><p>It is considered good practice to use these colors exactly for what they are intended. This helps in consistency to be maintained among all the apps on the user’s device. You can also refer to <a href="https://www.hackingwithswift.com/example-code/uicolor/how-to-use-semantic-colors-to-help-your-ios-app-adapt-to-dark-mode">these</a> guidelines for the use of semantic colors.</p><h3>Adding Colors manually</h3><p>Along with these system colours, as a developer, you might need to use some additional colours. iOS allows us to define colours manually for light and dark themes such that the respective shade is selected for the preferred theme. The same can be done if you want two different images to be used for different appearance modes.</p><p>Go to the “Assets.xcassets” folder in Xcode for your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ej8WAObuvIS1D1m8jGagaw.png" /></figure><p>Right click and select <em>“New Color Set”</em>. In <em>“Appearances”</em>, select “Any, Light and Dark”. This will allow you to set a color and define how this color would look in different UI modes. Now iOS will put either of these colors depending on the system preference. Also, the color in “Any Appearance” will be used when the device is running below iOS 13.</p><p>This works the same way even when you select “Any and Dark” in “Appearances”. The color in Any Appearance is selected for Light mode and devices below iOS 13. Using this method has its own advantages as it is backwards compatible, because it uses the color set in any appearance for devices running on older versions of iOS.</p><h3>Forcing the app to use a selected UI</h3><p>If we want our app to specifically run on light or dark mode irrespective of the system preferences, what we can do is go to info.plist and add a key “UIUserInterfaceStyle” and set it to “Light” or “Dark”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OuLlxGQOqEGR2XbXTabwfQ.png" /></figure><h4>Wrapping Up</h4><p>Although this is an option, it is advised to build an app which can run on both Appearance modes. In the end, it is alright if our app prefers one of the appearance modes to the other. You can continue with the series in the <a href="https://medium.com/iecse-hashtag/swift-part-4-navigationbar-and-codable-6acc41953a1f">next </a>article where we cover Navigation bars and the Codable Protocol.</p><h4>Congratulations 🎉! You have just completed the third tutorial!</h4><p>All of the above-written code is available on <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article3/Users"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddf16eb01651" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-3-the-dark-mode-ddf16eb01651">Swift Part 3 — The Dark Mode</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Part 1 —  Creating iOS Apps Programmatically]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-1-creating-ios-apps-programmatically-fb32aa71fe34?source=rss-757271a2e3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb32aa71fe34</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Dhruvik Chevli]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:08:57 GMT</pubDate>
            <atom:updated>2020-05-31T08:17:58.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1 — Creating iOS Apps Programmatically!</h3><h4>In this tutorial, I’m going to try and explain all the basics you may need to know to get started with making iOS apps programmatically, i.e. without storyboards.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltCWUKD4Chhtbi6qUw9V3w.png" /></figure><h3>IECSE CRASH COURSE: DEVELOPMENT WITH SWIFT</h3><blockquote>This article is going to be the first article of this ten part series. Through the course of 10 articles, we are going to make a small app which will display a set of users that we will fetch from the net. While making the app, we will cover some of the most important topics that every iOS developer must know.</blockquote><p>By the end of this article, you will have a clear idea about the basics of iOS and how we can start making iOS apps programmatically.</p><p>First of all, let’s create an Xcode project by opening <strong>Xcode</strong> and selecting “<em>Create a new Xcode project</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fihgMJw7PnehJPessJTL8g.png" /><figcaption>Select Single View App</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FWe1SfUoKFJp_fpIpuHRw.png" /><figcaption>Give it a suitable name and save it anywhere</figcaption></figure><p>Once our project has been created on Xcode, we will end up on a screen that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svcoNvCRgCNlVrrk3mXb6Q.png" /></figure><h3>Why Programmatically?</h3><p>When we think about iOS development, there are two approaches to it:</p><ol><li><strong>Using Storyboards:</strong> This is the more visual approach. This feature was introduced with iOS 5. In simple terms, what you do here is drag the various elements that make up the views that we want on our screen. It also helps us design transitions between the different views that we make.</li><li><strong>Programmatically: </strong>This is the approach that we’ll be using. Here, we make our apps with nothing but code, we do not have any visual cues of the app without building it.</li></ol><p>I personally prefer a programmatic approach because it gives you better control over all the elements in your app. Anything that is achievable through a storyboard can be achieved through code. One of the other main advantages is the reusability of code. You can use one function to make your labels throughout your project. Also, when working with other developers, the storyboard approach may give merge conflicts, this problem is also taken care of in a programmatic approach.</p><h3>Removing Main.storyboard and its References</h3><p>Now, before we start with the coding part of it, we need to make a few changes so that our app doesn’t need a storyboard. So first, we will delete the reference to the storyboard <strong>“Main”</strong> from the <em>general settings</em> of our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqPEKEtHjuOG13CvMaRWLw.png" /><figcaption>Make the highlighted textfield blank.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XD1jVFbzCogu2ecFrlLPdw.png" /><figcaption>Delete the Main.storyboard, select “<strong>Move to Trash</strong>”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3YCJ4zHNG758djY0-dOqQ.png" /><figcaption>Delete the reference in info.plist (Select it and press cmd+delete)</figcaption></figure><p>Now that we’re done with these 3 steps, we’re ready to start coding.</p><h3>Creating the Table View</h3><h4>Cocoa Touch</h4><p><strong>Cocoa Touch</strong> is a name given to the collection of UI frameworks available as part of the iOS SDK. For us, CocoaTouch provides us with the implementation of most UI elements that we need. When we make a file for an element using CocoaTouch, we get some pre-written functions that we might need for implementing the respective element. We can change these functions and add new ones as and when we need them.</p><p>First, let’s add a new file with <em>Cocoa Touch Class</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sz7yrreLiRZCKlVgU2bv6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WcEtJosYAD9Z4TRDoOXZQ.png" /><figcaption>In “Subclass of” select “<strong>UITableViewController</strong>”.</figcaption></figure><p>Let the Class be <strong>TableViewController</strong> for now, this will also become the name of the file that will get created.</p><p><em>Delete the “ViewController.swift” file, we won’t be using that.</em></p><h4>App Delegate</h4><p>The <strong>AppDelegate</strong> is one of the default classes that gets created by Xcode in any new project that we create. The App Delegate is considered to be the <strong>entry point</strong> of any app that we make. This class is also responsible for handling the application’s life cycle events, i.e., <em>responding to the app being launched, backgrounded, foregrounded, receiving data</em> and so on.</p><p>Here, we need to create an instance of <strong>UIWindow</strong> which is a subclass of <em>UIView</em>. Every app has exactly one window. This window is created at launch time and is never destroyed or replaced. It is in this window that all our Controllers are contained.</p><p>Now we will set up the code in the AppDelegate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdDrHwQdtBN4wK3mzNo8Nw.png" /></figure><p>For now, we only need to make changes in application(_didFinishLaunchingWithOptions) in this class, the other functions remain the same.</p><p>Now, let’s try to break down what is happening in these lines-</p><ul><li><em>var window: UIWindow?</em>, the question mark means it’s an optional type and that the value can be absent or present; this is similar to a nil value in other languages, but it works for all types not just classes.</li><li>We will talk about the conditional<em> </em><em>if #available(iOS 13.0,*)</em>, when we take a look at the SceneDelegate.</li><li><em>window = UIWindow(…)</em>, this is done to create an instance of UIWindow, we name it window.</li><li>The rootViewController is the ViewController which is displayed as soon as our app is launched.</li><li><em>window?.rootViewController = TableViewController()</em>, this line sets up the rootViewController of our app to TableViewController(), ie this class which will contain our table.</li><li><em>window?.makeKeyAndVisible()</em>, this makes the window that we have created visible and makes it the key.</li></ul><h4>Scene Delegate</h4><p>When you consider the <em>AppDelegat</em>e to be the object that’s responsible for your application’s life cycle, the <strong>SceneDelegate</strong> is responsible for what’s shown on the screen; the scenes or windows. It is the SceneDelegate’s <em>scene(_:willConnectTo:options:)</em>, that creates our initial content view, creates a UIWindow, sets the window’s root view controller and makes the window key. As you can see, this is what we did for the devices that had older versions of iOS in the AppDelegate.</p><p>It was only since iOS 13, that the SceneDelegate class was introduced, before that all the tasks of the SceneDelegate used to be taken care of in the AppDelegate itself (this is exactly what we have done) but with iOS 13.0 SceneDelegate was introduced and all the work involving scenes is done in the <strong><em>SceneDelegate</em></strong> since then. If you want to read more about SceneDelegate, <a href="https://www.donnywals.com/understanding-the-ios-13-scene-delegate/">visit here</a>.</p><p>Now in the <em>scene(_:willConnectTo:options:)</em>, we’ll add code similar to what we added in the AppDelegate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_g3gB85x-8p-0CzqcCRzQ.png" /></figure><p><em>guard let windowScene = (scene as ? UIWindowScene) else {return}</em>, in this line of code we are making an instance of the WindowScene which we swill later embed in the window that we instantiate in the next line.</p><p>Next, we set the window’s root view controller to <strong>TableViewController()</strong> and we declare the window as key and make it visible. Also, make an instance of AppDelegate and set it’s window to the instance of <strong>UIWindow</strong> we just created.</p><blockquote>Window can be thought of as a container in which scenes can be set.</blockquote><p>Now when you build the app, it should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*9yEeAo3N7L4nhi3r7Pbbzg.png" /></figure><p>In the next section, we will work on configuring the TableViewController.</p><h3><strong>The TableViewController</strong></h3><p>Any app consists of several views. Views are what we see on our screens. The table views are the views that help us in displaying lists of data in our applications, the class used for this is UITableViewController.</p><p>UITableViewController is the subclass of <em>UIViewController</em>, it is a convenience class used to manage a table view. It aids in understanding some of the commonly used classes in iOS such as delegates and datasources.</p><p>Coming to our <strong><em>TableViewController.swift</em></strong>, here is a function viewDidLoad(). This is the function that is called once our view has been loaded into the screen. It is also the function where most of our logic will go.</p><p>Now, we are going to initialise the TableViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNcTlSxMO42Mamf-YiMBFg.png" /></figure><p>Here, inside <em>viewDidLoad()</em> we first call, super.viewDidLoad(), as we already know now UITableViewController is a subclass of UIViewController. Even though here, the viewDidLoad() does not do anything, it is good practice to always call super on all the functions that you override because there might be some important initialisations taking place in these functions.</p><p>Next, what we are doing is making a separate function to set up the TableView, this just helps us in keeping the code clean. Let’s take a deeper look into the function setUpTableView().</p><ul><li><em>tableView.translatesAutoresizingMaskIntoConstraints = false, </em>is the command that tells iOS that we are going to use AutoLayout, we’ll be looking at AutoLayout in detail in the next article, but we are going to give the relative positions of all the elements we’re going to be using and restrict iOS in generating Auto Layout constraints on its own.<em> </em><strong><em>Especially when making UI programmatically, always make sure that you use this command.</em></strong></li><li>Next, we need to inform the tableView about the type of cells that we will be using inside of it. That is that t<em>ableView.register(UITableViewCell.self,forCellReuseIdentifier: “Cell”) </em>does, it registers the tableViewCells as the cells that we will be using in our tableView. we will get into details of the reuse identifier in detail in the next section.</li><li>In the next two lines, we make the tableView conform to two protocol methods, what this means is that these give us a blueprint of how the data should be handled by the tableView.</li><li>At last, we set up the height of each cell of the tableView and we make the tableView cells non-selectable and the last line removes the default lines that separate two cells.</li></ul><p>In the next and the last section of the tutorial, now we just have to configure our cells.</p><h3>Setting up the cells</h3><p>Let’s first add the final lines of our code and then try and understand what they do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UD4YxZ10FPHVbVabiJ2m9Q.png" /></figure><p>First, we change the function <em>numberOfSections(..)</em> to return 1, this, as the name suggests, is the number of sections our tableView will have. For now, we are going to keep it one. The function <em>tableView(_numberOfRowsInSection section:Int)</em>, returns the number of cells that we want the section to have. (As we only have one section for now in our tableView).</p><p>It is very important to understand the next function, <em>tableView(_cellForRowAt indexPath:)</em>, this is where our cells are created and initialised.</p><h4>Reusable Cells</h4><p>Suppose our table had 10000 rows, in this case, if we made 10000 cells and we started scrolling towards the bottom of the table, eventually we would run out of memory and our app would crash. Hence what iOS does is, when a cell goes outside the view, i.e. the cell can no longer be seen, the same cell is used and the data inside it is changed accordingly and is again shown as a different cell. Hence, even if we have 10000 rows in our table, we can use very few cells to represent all the rows. This is because of the cells being reusable.</p><p>In the tableView that we made, where we registered the cells we were going to use, we also defined the forReusableIdentifier=”Cell”, now in the function<em> </em><em>tableView(_cellForRowAt indexPath:), </em>we instantiate the cell with,<em>let cell = tableView.dequeueReusableCell(withIdentifier:”Cell”,for: indexPath), </em>here we need to make sure that the identifier we use is the same as what we registered in the tableView.</p><h4>IndexPath</h4><p>Index paths describe an item’s position inside a table view or collection view, storing both its section and its position inside that section. For example, the first row in a table would have section 0, row 0, whereas the eighth row in the fourth section would have section 3, row 7.</p><p>Like for the code we have written, we store the row of the cell we are configuring in<em> </em>a variable<em> t</em>. Next, we use the <em>ternary operator</em>, this operator works with 3 values instead of 2. One of them is a check/conditional that is run, one is the value that is returned if the check is evaluated as true and one more value that is returned if the check is evaluated as false. For us, we check if t is odd, in which case we give the cell a color teal, otherwise the color returned is pink.</p><p>The final part is configuring the tableViewCell, which we will cover in the <a href="https://medium.com/iecse-hashtag/swift-part-2-custom-tableview-cells-43a540e9ed3a">next</a> tutorial about making a custom UITableViewCell.</p><p>The app that we have made until now looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*KHvKXVsGRW4sbXZarhicjA.png" /></figure><h4>Wrapping Up</h4><p>In this article, we’ve looked at how we can get started with making iOS apps programmatically. We’ve looked at some of the very important concepts including AppDelegate, SceneDelegate and we’ve set up our TableViewController so that we can use this going ahead.</p><h4>Congratulations🎉! You have just completed the first tutorial!</h4><p>All of the above-written code is available on <a href="https://github.com/Dhruvik-Chevli/hashtagUsersApp/tree/master/Article1/Users"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb32aa71fe34" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-1-creating-ios-apps-programmatically-fb32aa71fe34">Swift Part 1 —  Creating iOS Apps Programmatically</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>