<?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[Hashtag by IECSE - Medium]]></title>
        <description><![CDATA[A blog about all things technical brought to you by IECSE, the official Computer Science club of MIT, Manipal. Find out more at: https://iecsemanipal.com - Medium]]></description>
        <link>https://medium.com/iecse-hashtag?source=rss----91439e9ef940---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Hashtag by IECSE - Medium</title>
            <link>https://medium.com/iecse-hashtag?source=rss----91439e9ef940---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:18:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/iecse-hashtag" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter for Web in 2022: A Deep Dive]]></title>
            <link>https://medium.com/iecse-hashtag/flutter-for-web-in-2022-a-deep-dive-96cf1b5695a9?source=rss----91439e9ef940---4</link>
            <guid isPermaLink="false">https://medium.com/p/96cf1b5695a9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Divyansh Kulshreshtha]]></dc:creator>
            <pubDate>Tue, 25 Jan 2022 13:31:35 GMT</pubDate>
            <atom:updated>2022-01-25T13:54:32.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RelbYvNeEeWEPm2xGd-URQ.jpeg" /></figure><p>Cross-platform development has been the trend over the last few years. With the amazing advantages that it offers, no doubt the developer community is enthusiastic about cross-platform. Google dived into this market with its up and coming UI framework - <em>Flutter</em><br>But, wouldn’t life be easier if this “cross-platform” support got extended to Web as well? Flutter’s solution to this is <em>Flutter for Web</em></p><h3><strong>Introduction: the whats and the whys</strong></h3><p><em>Flutter </em>is a Google UI library designed to help developers create native, performant, and appealing mobile apps. Flutter’s ambition, however, is to create user interfaces for every screen, not just for mobile apps.</p><p>Flutter’s web support provides the same mobile and web experiences. You can now create apps for web in addition to iOS and Android, thanks to the <em>mobility </em>of Dart, the power of the web platform, and the <em>flexibility </em>of the Flutter framework. Because it is the same Flutter framework and the web is merely another device target for your project, you can compile pre-existing Flutter code written in Dart into a web experience.</p><p>Here, we will analyze the current state of Flutter web (competing with SPA frameworks such as React, Angular, and Vue), the desktop (competing with Electron and Qt), and hopefully embedded devices and more in the future with a little extra effort.</p><h3><strong>But..how does it work?</strong></h3><p>Flutter (Mobile) has its own rendering engine, Skia, which offers the Software Development Kit (SDK) complete control over every pixel of the screen, with precision and speed.</p><p>Flutter Web (FW) builds its HTML components and uses the entire screen as a canvas, allowing it complete control over every pixel. This is created using HTML/CSS and Javascript, which are both mainstream web technologies. As a result, you can use all of Flutter’s capabilities, such as animations and routing, without writing any additional source code.</p><p>Adding web compatibility to Flutter included building Flutter’s fundamental graphics layer on top of conventional browser APIs and compiling Dart to JavaScript rather than the ARM machine code used in mobile apps. Flutter may provide a portable, high-quality, and performant user experience across modern browsers by combining DOM, Canvas, and WebAssembly.</p><h3><strong>Specifics that matter: Pros and Cons</strong></h3><p>Okay, so Is this just another framework trying to bring down the <em>Reacts </em>and <em>Angulars </em>of the web market? Well, yes and no. Let’s have a look at what Flutter Web brings to the table and touch upon the downside of the same.</p><p><strong>Pros: </strong><br>1. Access to essentially the same widgets that are available for Flutter for mobile.</p><p>2. Pretty much all of the existing famous libraries that work on mobile are also available for the web.</p><blockquote>60.04% packages of pub.dev are web-compatible</blockquote><p>3. Significant reduction in the code development time inclusive of all three platforms.</p><p>4. <em>Customization: </em>it also offers you the option to develop a customized version for the web depending on the core OS of the system — just like it does for Android and iOS.</p><p>Okay, does this mean that Flutter Web, with its shiny<em> </em>advantages, is <em>the</em> ideal tool to build cross-platform apps, including apps for the web?<br>Not entirely, Flutter web also comes with some severe <strong><em>drawbacks</em>:</strong></p><ol><li>The most important thing holding it back is its SEO capabilities. Flutter Web is <strong>not </strong>SEO-friendly.</li><li>No ability to modify generated HTML, CSS, and JavaScript code.</li></ol><blockquote>Flutter web is not SEO-friendly. Lack of SEO is preventing the framework from being used for large-scale business products.</blockquote><h3><strong>Performance and Rendering:</strong></h3><p>Flutter offers you the option to choose between 2 renderers:<br>1. HTML Renderer<br>2. Canvas Kit</p><p><em>HTML </em>renderer optimises download size over raw performance.</p><p><em>Canvaskit </em>prioritises performance and pixel-perfect consistency while taking a hit on the download size, making your app run a bit slowly. Canvaskit renders a total file size of more than 400% than the original file size, but at the same time, increases the performance by leaps and bounds.</p><p><em>PS:</em> the default renderer is the <em>auto</em> mode which prioritizes HTML for mobile browsers and CanvasKit for desktop browsers.</p><p>If you want to test the renderers individually:</p><p><strong>HTML</strong></p><pre>flutter run -d chrome — web-renderer html</pre><p><strong>CanvasKit:</strong></p><pre>flutter run -d chrome — web-renderer canvaskit</pre><p>The flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*wkMX_iGTHUDnyQ0d" /><figcaption>Source: Flutter Web Documentation</figcaption></figure><h3>Initializing and running the web app</h3><p><strong>Steps to initialize for the web:<br></strong>All projects created on Flutter 2.0 and up have built-in support for flutter web.<br>You can initialize and run your flutter web project by</p><pre>flutter create app_name<br>flutter devices</pre><p>The devices command should at least list out:</p><pre>1 connected device:<br>Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150</pre><p>Then to run your app on chrome:</p><pre>flutter run -d chrome</pre><p>To add web support to an existing project created using a previous version of Flutter, run the following command from your project’s directory:</p><pre>flutter create .</pre><h3><strong>Folder Structure</strong></h3><p>Running the <em>flutter create . </em>command creates a folder called — “web” and populates it with the necessary files for the app to run on the web! It’s that simple!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*mm1uKX5a5YsSnCgm" /><figcaption>Folder structure of a web project</figcaption></figure><blockquote>By the way, if you are wondering, no, you can’t edit the index.html or the rendered javascript files.</blockquote><h3><strong>Demo:</strong></h3><p>Here’s a comparison of what a very simple To-Do list app would look like on your phone vs on the web</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YX3Iy_uB5pwETfZpUqNrmw.png" /><figcaption>Web vs Android app</figcaption></figure><p>Code: <a href="https://github.com/geekyprawins/Todo-List-App">https://github.com/geekyprawins/Todo-List-App</a></p><h3>Conclusion:</h3><p>At its current stage, using flutter web for all of your web development needs is doubtful, but it’s useful and efficient if you want to build:</p><ul><li>Progressive Web Apps (PWAs) that can be integrated with a user’s already built environment.</li><li>Organization’s internal applications like dashboards</li><li>A web counterpart to your already existing Flutter mobile app. You can use <strong>existing logic and UI elements to output web apps faster than other web frameworks</strong>. The web version of your app doesn’t have to implement all features the mobile one does.</li></ul><p>Flutter Web allows you to build highly performant and interactive web apps. However,<strong> </strong>it is not made for static web pages.</p><blockquote>Flutter web is <strong>ideal for single-page interactive apps with animations and heavy UI elements</strong>. If you need SEO in your website, forget flutter web (at least in its current state)</blockquote><p>In the case of static web pages with a lot of dense text, a more classic web development approach might bring better results, faster load times, and easier maintenance.</p><blockquote>All in all, flutter web is a great competitor to all the frameworks present in the market. As mentioned above, it has its pros and cons, but it’s not quite at the level of becoming a standard yet.</blockquote><p>Authors:<br>1. <a href="https://twitter.com/divyanshkul"><em>Divyansh Kulshreshtha</em></a><em><br></em>2.<em> </em><a href="https://github.com/geekyprawins"><em>Praveen Varma</em></a></p><p>Editor: <br><a href="https://github.com/prakharb10"><em>Prakhar Bhatnagar</em></a></p><p>Featured Image:<br><a href="https://github.com/Hackerbone"><em>S Sitaraman</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96cf1b5695a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/flutter-for-web-in-2022-a-deep-dive-96cf1b5695a9">Flutter for Web in 2022: A Deep Dive</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[Programming in R: A Case Study]]></title>
            <link>https://medium.com/iecse-hashtag/programming-in-r-a-case-study-c1a469e5e68?source=rss----91439e9ef940---4</link>
            <guid isPermaLink="false">https://medium.com/p/c1a469e5e68</guid>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[ggplot2]]></category>
            <dc:creator><![CDATA[Khushee Kapoor]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 17:53:10 GMT</pubDate>
            <atom:updated>2021-10-05T17:53:10.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ygs1wbeRXAKWcIuwuuw0EA.png" /></figure><p>This introductory tutorial walks you through the basic statistical features available in R and how to use them. The tutorial gives you hands-on learning using the Palmer Penguins dataset.</p><h4><strong>What is R?</strong></h4><p>R is a programming language that is used in the statistical and numerical analysis of complex datasets. R provides multiple libraries, which makes data analysis and graphical representation amazingly easy to achieve.</p><p>Software programmers, statisticians, data scientists, and data miners are using R to develop statistical software.</p><h4><strong>Prerequisites for the Tutorial</strong></h4><p>There are no prerequisites required as such, but basic programming knowledge in any language will help you understand Exploratory Data Analysis (EDA) and Data Visualization. And if you have dealt with Python before, then a lot of things would look similar.</p><h4><strong>How is R different from Python?</strong></h4><p>R has more data analysis and visualization libraries than Python, and they are much easier to implement and understand.</p><p>R is built by statisticians and leans heavily into statistical models and specialized analytics. Data scientists use R for deep statistical analysis, supported by just a few lines of code and beautiful data visualizations. For example, you might use R for customer behavior analysis or genomics research.</p><p>The visualizations in R are much more pleasing to the eye, making it easier to comprehend the dataset. It has unmatched libraries like dplyr and dbplyr for Data Wrangling, ggplot2 for Data Visualization, mlr3 and caret for Machine Learning, tidyverse for General Data Science Tasks, etc. All these libraries and many more can be used for unmatched data exploration and experimentation.</p><p>Even though Python is widely used for its wide range of purposes because developers can use Python for production and deployment, R scores higher from a statistical analysis point of view.</p><h4><strong>What will I learn at the end of the Tutorial?</strong></h4><p>We are very sure that you will get a good understanding of the packages and libraries in R, and you will also be able to analyze any of your custom datasets using R.</p><h3>Palmer Penguins: A Case Study</h3><figure><img alt="Palmer Penguins" src="https://cdn-images-1.medium.com/max/1024/1*oM0r7tPdJTFWrlgVh5UniQ.png" /></figure><p>Now that we are familiar with R, let’s try coding some basic commands on one of R’s most popular datasets — Palmer Penguins. We urge you to code along with us to experience the power of R.</p><p>To begin, we need to load the Palmer Penguins dataset in the environment.</p><p>To install any package in an R environment, we follow the syntax:</p><blockquote>install.packages(“package name”)</blockquote><p>This is a <strong>one-time step</strong>. Once the package is installed on your system, you only need to load it in the environment before using it. To <strong>load</strong> a package, we use the syntax:</p><blockquote>library(package name)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/823fbebd6d5bc7e4812cda9d6dbd72ac/href">https://medium.com/media/823fbebd6d5bc7e4812cda9d6dbd72ac/href</a></iframe><p>Take note that the # symbol denotes a comment, which we insert in the code to make it more readable.</p><h4>Basic Exploratory Data Analysis</h4><p>Now that the Palmer Penguins package is all loaded and set to be manipulated, let’s get to know it! Remember that the name of the dataset in this package is ‘penguins’.</p><p>The conventional way to start any dataset analysis is to view its first few rows. This gives us an idea of how the dataset is built without overloading the environment with an enormous number of rows. To do this, we use the function:</p><blockquote>head(name of the dataset)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/575a55dae1c004e6823fe393d58f80d2/href">https://medium.com/media/575a55dae1c004e6823fe393d58f80d2/href</a></iframe><figure><img alt="Default Head Function" src="https://cdn-images-1.medium.com/max/868/1*VRMQPR_pQYU9_b4Z_57l5g.png" /></figure><p>By default, the head() function displays the <strong>first 6 rows</strong> of the dataset. However, if we want to view more/ fewer rows, we can specify the number of rows in the parentheses as such:</p><blockquote>head(name of the dataset, number of rows)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5d63831947b84767f23e0b853ca5f55/href">https://medium.com/media/c5d63831947b84767f23e0b853ca5f55/href</a></iframe><figure><img alt="Custom Head Function" src="https://cdn-images-1.medium.com/max/876/1*vEk2XIPWT7RvwomKXXGCDQ.png" /></figure><p>Similarly, we can also view the last few rows of the dataset using the function:</p><blockquote>tail(name of the dataset)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a94d306735dae6f8badc11033985bdf2/href">https://medium.com/media/a94d306735dae6f8badc11033985bdf2/href</a></iframe><figure><img alt="Default Tail Function" src="https://cdn-images-1.medium.com/max/858/1*4vXsQiId4X5iVptcUR8Gsw.png" /></figure><p>Just like the head() function, by default, the tail() function displays the <strong>last 6 rows</strong>. However, we can tailor the function to our needs and display as many number of rows we want by adding a parameter:</p><blockquote>tail(name of the dataset, number of rows)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2571848c07d9fa291c54cd05ff5d4f7a/href">https://medium.com/media/2571848c07d9fa291c54cd05ff5d4f7a/href</a></iframe><figure><img alt="Custom Tail Function" src="https://cdn-images-1.medium.com/max/877/1*JSbKHHff4V3L8khd0yvZfg.png" /></figure><p>To know the dimensions of the dataset, we use the <strong>dim() function</strong>. The syntax of the function is:</p><blockquote>dim(name of the dataset)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9891aab51d63f445849e3abef9cd7e30/href">https://medium.com/media/9891aab51d63f445849e3abef9cd7e30/href</a></iframe><figure><img alt="Dimensions" src="https://cdn-images-1.medium.com/max/72/1*NkxH0xUDHriIZ0GURai4FQ.png" /></figure><p>Here we can see that our dataset has 344 data points and 8 features, namely- species, island, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, sex, and year. Also, we can see that the columns- species, island, and sex have the data type factor &lt;fct&gt; (which means categorical data), the columns- bill_length_mm, and bill_depth_mm have the data type double &lt;dbl&gt; (which means numbers with decimals), and the columns — flipper_length_mm, body_mass_g, and year have the data type int &lt;int&gt;(which means numbers without a decimal point).</p><p>A simpler way to know all these details is by using the <strong>str() — structure function</strong>. The syntax of the str() function is as follows:</p><blockquote>str(name of the dataset)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/241b6a5728b87ec4a7d3f3bff3835c8b/href">https://medium.com/media/241b6a5728b87ec4a7d3f3bff3835c8b/href</a></iframe><figure><img alt="Structure Function" src="https://cdn-images-1.medium.com/max/903/1*nT-zTveOZdWb9-nctnrobg.png" /></figure><p>Using the str() function, we get to know the dimensions of the dataset, the data type of the columns, and the first few values as well.</p><p>Here, we also get <strong>deeper insights</strong>, such as the different ‘levels’ or ‘classes’ or ‘categories’ in the columns with the factor data type, for example- the column sex has two levels- female and male, the column species has three levels- Adelie, Chinstrap and Gentoo.</p><p>Awesome! Now that we are introduced to the Palmer Penguins dataset, let’s apply some functions that will help us measure some stats about the dataset.</p><p>We are using the library ‘<strong>tidyverse’</strong>. Like any other package, we first install the package in our system (reminder: one-time step only) and then load it in the environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a0f68fabb4738ed32b5201cb616fe8e/href">https://medium.com/media/3a0f68fabb4738ed32b5201cb616fe8e/href</a></iframe><p>Before we begin, let’s see a handy operator — <strong>%&gt;%, the pipe operator</strong>. This operator builds a pipe of functions, which are performed one after the other, using the result of the previous functions. Note, the pipe operator must be at the end of each line.</p><p>To start, we will use the <strong>count() function</strong>. This function is generally applied to columns having the factor data type. It returns the count of each level in a column. The syntax is as follows:</p><p><em>dataset name %&gt;%</em></p><blockquote>count(name of the column)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45ec6887c35d421a7e1a044b38ad7f29/href">https://medium.com/media/45ec6887c35d421a7e1a044b38ad7f29/href</a></iframe><figure><img alt="Count Function" src="https://cdn-images-1.medium.com/max/182/1*CIt3D7RXDD4z4nc643XM4w.png" /></figure><p>As we can see, the count() function returns the count of each species in the column. There are 152 penguins of the ‘Adelie’ species, 68 penguins of the ‘Chinstrap’ species, and 124 penguins of the ‘Gentoo’ species.</p><p>Next, we use the <strong>summarize() function</strong> that returns a particular value after performing an operation. The syntax is:</p><p><em>dataset name %&gt;%</em></p><blockquote>summarize(new column = function(column name))</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ad15c140af556143b3de71ee7659357/href">https://medium.com/media/5ad15c140af556143b3de71ee7659357/href</a></iframe><figure><img alt="Summarize Function" src="https://cdn-images-1.medium.com/max/156/1*VZ4_eMS2km6Ra6-yiJcQ3A.png" /></figure><p>This function returns the average of the body mass of the penguins as a new column called avg_body_mass. We use the <strong>mean()</strong> function to calculate the average. We can also use <strong>median()</strong> and <strong>getmode() </strong>functions to get the column’s median and mode, respectively. The statement <strong>na.rm=TRUE</strong> ignores any null values in the column which might cause a calculation error.</p><p>Let’s add another function to the pipe. Now, we are going to find the average of the body mass group-wise. The summary() function remains the same, but before that, we add in the <strong>group_by() function</strong>.</p><p>The group_by() function groups the dataset by the levels of a factor column and then applies the next functions group/factor-wise. The syntax of the group_by() function:</p><p><em>dataset name %&gt;%</em></p><blockquote>group_by(column name) %&gt;%</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b50d9c502debdbc24865193440f0ebf6/href">https://medium.com/media/b50d9c502debdbc24865193440f0ebf6/href</a></iframe><figure><img alt="Group By Function" src="https://cdn-images-1.medium.com/max/236/1*txBsphw7GWUqKgihZdg_bQ.png" /></figure><p>Unlike the previous result, here we see that the summarize() function has calculated the mean for each level of the species separately and stored it in the avg_body_mass column.</p><p>Now, what if we want to filter out only those penguins who have body mass less than the average of their species? The <strong>filter() function</strong> comes to our rescue!</p><p>In the pipe, we add in the filter() function after the group_by() function. The syntax for the filter() function is as follows:</p><p><em>dataset name %&gt;%</em></p><blockquote>filter(condition)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27cc48f9c49dcb0a548b6b3695d83326/href">https://medium.com/media/27cc48f9c49dcb0a548b6b3695d83326/href</a></iframe><figure><img alt="Filter Function" src="https://cdn-images-1.medium.com/max/910/1*6IE7s_SlLJFgrUSugV8hng.png" /></figure><p>Here, we see the penguins who have body mass less than the average body mass of their species. Recollect, we have used the mean() function and the na.rm=TRUE statement for calculation. We use the relational operator ‘&lt;’ or less than to build the condition. We can also use conditions like ‘&gt;’ or greater than, ‘&gt;=’ or greater than or equal to, ‘&lt;=’ or less than or equal to, ‘==’ or equal to, to build the conditions. The ‘!’ represents the not operator and reverses the condition.</p><p>Moving on, if we want to arrange the penguins who have less body mass than the average of their species, in a particular order, we use the <strong>arrange() function</strong>, using the syntax:</p><p><em>dataset name %&gt;%</em></p><blockquote>arrange(column name)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bda8d587fbe9a6f0541180d8e441b46/href">https://medium.com/media/0bda8d587fbe9a6f0541180d8e441b46/href</a></iframe><figure><img alt="Arrange Function" src="https://cdn-images-1.medium.com/max/879/1*5lKWl8um124acOWWMlg2uw.png" /></figure><p>Here, we see that the penguins having body mass less than the average of their species are sorted in descending order by their body mass. By default, the arrange function sorts the dataset in ascending order. However, because we have added the <strong>desc() parameter</strong>, our dataset is arranged in descending order.</p><p>Yay! We have explored our dataset and various statistical measures of it.</p><p>Let’s proceed to visualize our data using the library <strong>‘ggplot2’</strong>. Like before, we first install the package in our system (reminder: this is a one-time step) and then load the package in the environment</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdcb7edcfb31e4fcf034d47e4e935423/href">https://medium.com/media/cdcb7edcfb31e4fcf034d47e4e935423/href</a></iframe><p>The basic syntax to make any plot using ggplot2 is as follows:</p><p><em>ggplot(dataset, aes(x=..,y=..) +</em></p><blockquote>geom_shape</blockquote><p>Here, aes stands for the aesthetics of the plot and the word geom stands for the geometric object. Note that the shape after geom changes for every kind of plot we make. Also, take care that the ‘+’ operator is placed at the end of each line.</p><p>To begin with, we will make a basic scatter plot. A <strong>scatter plot</strong> plots every individual data point in the dataset using shapes on a graph. The syntax for it is as follows:</p><p><em>gglot(dataset, aes(x=..,y=..) +</em></p><blockquote>geom_point ()</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083d0899b055a7e826900f1782039067/href">https://medium.com/media/083d0899b055a7e826900f1782039067/href</a></iframe><figure><img alt="Scatter Plot" src="https://cdn-images-1.medium.com/max/616/1*NpOFE2V3dRtr7gHXHUso9Q.png" /></figure><p>The above plot represents the variation of body mass with respect to the flipper length of the penguin. Note that passing the values of both x and y is compulsory in a scatter plot.</p><p>Next, we will plot a <strong>line graph</strong>. A line graph plots every point in the dataset on the graph and joins it with its consequent and subsequent data points in the dataset using a line. The syntax to plot a line graph is as follows:</p><p><em>ggplot(dataset, aes(x=..,y=..,) +</em></p><blockquote>geom_line ()</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83452cca04ece81a9a9b441b50e2dcd4/href">https://medium.com/media/83452cca04ece81a9a9b441b50e2dcd4/href</a></iframe><figure><img alt="Line Graph" src="https://cdn-images-1.medium.com/max/614/1*shFjcNNvi-1CJbtWUuBbAQ.png" /></figure><p>The line graph above represents the variation of body mass with respect to the flipper length of a penguin. Like a scatter plot, passing both the values of x and y is compulsory in a line graph.</p><p>Moving on, we will plot a <strong>bar graph</strong>. In a bar graph, every data point is represented by a bar whose length is proportional to the value they represent. To build a bar graph, we use the following syntax:</p><p><em>ggplot(dataset, aes(x=..)) +</em></p><blockquote>geom_bar ()</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37d142caf5a6822222c4a35c92a6477/href">https://medium.com/media/c37d142caf5a6822222c4a35c92a6477/href</a></iframe><figure><img alt="Bar Plot" src="https://cdn-images-1.medium.com/max/598/1*dIz74N4BxUvvovS78stYTQ.png" /></figure><p>As we can see, the bar graph we have plotted represents the number of penguins having a particular body mass. Unlike the scatter and line plots, we have to pass only x to the bar graph function, and by default, the y-axis will represent the count of the x-axis variable.</p><p>Similar to the bar graph, a <strong>histogram</strong> plots bars but for data points grouped in bins. The bins are continuous number ranges.</p><p>To make a histogram, we use the syntax:</p><p><em>ggplot(dataset, aes(x=..,)) +</em></p><blockquote>geom_histogram ()</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4422fa129a55817ed9fbea6f61834bc/href">https://medium.com/media/b4422fa129a55817ed9fbea6f61834bc/href</a></iframe><figure><img alt="Histogram" src="https://cdn-images-1.medium.com/max/623/1*MnSv2Vuo5-Yw9-BWH0j4HA.png" /></figure><p>Referring to the above plot, we can see that the system has grouped the body mass of penguins into ranges and then plotted bars with length proportional to the count of penguins having body mass in that range. Like a bar graph, we only have to pass the x variable, and by default the y axis measures the count of the x axis variables.</p><p>The difference between a bar plot and a histogram is that bar plots work with both, the categorical and numeric data types, whereas histograms work only with the numeric data type.</p><p>All these plots convey a lot of information, but they look a little boring, don’t they? Let’s make them more visually appealing!</p><p>To add in a dash of colour, we include the <strong>colour parameter</strong> in the aesthetics parenthesis. The colour parameter highlights the points on the basis of the levels of a factor column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00799a753b8d63307c7bd257e961702c/href">https://medium.com/media/00799a753b8d63307c7bd257e961702c/href</a></iframe><figure><img alt="Colour Parameter" src="https://cdn-images-1.medium.com/max/597/1*J8CyTUlzR7eEqFZumOWqRw.png" /></figure><p>Here, the points are highlighted based on the species of penguins. R also provides a legend to make sense of the colours used. In this case, the data related to the Adelie penguins are orange in colour, the Chinstrap are green and the Gentoo are blue.</p><p>Similarly, we can change the size of the points on the basis of the levels of a factor column. Just add the <strong>size parameter</strong> in aesthetics parenthesis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3a1a0ef2b260c005a42ca62330a76d4/href">https://medium.com/media/b3a1a0ef2b260c005a42ca62330a76d4/href</a></iframe><figure><img alt="Size Parameter" src="https://cdn-images-1.medium.com/max/594/1*EABpULSDrXDEvs_pIwJrrQ.png" /></figure><p>In this case, we see that along with the size, the different species of penguins can be separated on the basis of the size of points. The Adelie penguins have small sized points, the Chinstrap penguins have medium sized points and the Gentoo penguins have big sized points.</p><p>If we want to go even further, we can change the shape of the point on the basis of levels of the factor column. To do this, we add the <strong>shape parameter</strong> in the aesthetics parenthesis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd59b3119c80d5198e235853a7e3662d/href">https://medium.com/media/cd59b3119c80d5198e235853a7e3662d/href</a></iframe><figure><img alt="Shape Parameter" src="https://cdn-images-1.medium.com/max/593/1*muSvLIzvDPRHoex8zCpyJQ.png" /></figure><p>Here, the three species of penguins are very clearly distinguished on the basis of colour, size and shape. Notice, the legend updates itself accordingly.</p><p>To make the graph more readable, we will add in some text. The different ways we can insert text are:</p><ul><li><strong>Title</strong>: Appears at the top left of the plot in a big font size.</li><li><strong>Subtitle</strong>: Appears at the top left of the plot beneath the Title in a small font size.</li><li><strong>Caption</strong>: Appears as a note at the bottom right of the plot in a small font size.</li><li><strong>X</strong>: Appears as the label of the x-axis, in a medium font size.</li><li><strong>Y</strong>: Appears as the label of the y-axis, in a medium font size.</li></ul><p>The text is added in the labs() function as follows:</p><p><em>ggplot(dataset, aes(x=..,y=..) +</em></p><p><em>geom_point () +</em></p><blockquote>labs(title=.., subtitle=.., caption=.., x=.., y=..)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d12df7414f51136191be334ac155ff06/href">https://medium.com/media/d12df7414f51136191be334ac155ff06/href</a></iframe><figure><img alt="Labelled Visualization" src="https://cdn-images-1.medium.com/max/596/1*YBaWdvek2378_NKhbRm8LA.png" /></figure><h4>A sneak into Advanced Exploratory Data Analysis</h4><p>Dimensionality is a curse. Often we need to drop some columns to avoid overfitting of models which leads to decrease in accuracy.</p><p>To do this, there are two ways:</p><ul><li>By indices</li><li>By labels</li></ul><p>To select columns on the basis of <strong>indices</strong>, we use [..,..] to access them in the dataset. The syntax is as follows:</p><blockquote>dataset [row indices, column indices]</blockquote><p>If we want to include all of the rows or all of the columns, we leave the space blank. If we want to access only specific columns, we put in the index/ range of indices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eaf7477b27299b69a7b76a87466f256/href">https://medium.com/media/0eaf7477b27299b69a7b76a87466f256/href</a></iframe><figure><img alt="Dropping Column by Indices" src="https://cdn-images-1.medium.com/max/568/1*-Zjag7pe86rab2Dy_8vKdQ.png" /></figure><p>Here, we have left the indices of rows empty, meaning we want to include all rows in the new dataset. Also, we want columns with indices 3, 4, 5, and 6. So we have put the expression 3:6 which generates the required series.</p><p><strong><em>Caution: The changes we have made are not permanent. These functions provide a copy of the dataset with the filters applied. To make the changes in the original dataset, we assign the original dataset to the changed dataset.</em></strong></p><p>Similarly, if we want to drop rows, we will put in the indices before the comma. Here, we have also used the ‘-’ operator which <strong>omits</strong> the mentioned rows and retains the others. Also notice that we have kept the indices of columns empty, hence, we retain all the columns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9388d7e36b9cce8f510344b94b4fb2e/href">https://medium.com/media/b9388d7e36b9cce8f510344b94b4fb2e/href</a></iframe><figure><img alt="Dropping Rows by Indices" src="https://cdn-images-1.medium.com/max/865/1*e88Egux4rdGjvgKAWBRVXQ.png" /></figure><p>We can see that the number of rows have reduced by 3 (344 to 341).</p><p>If we want to access the columns by their names, we use the <strong>select() function</strong>. This comes in the ‘tidyverse’ package. The syntax is as follows:</p><blockquote>select(dataset name, column names)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/441bb32e90e29f3268afa3181450eb86/href">https://medium.com/media/441bb32e90e29f3268afa3181450eb86/href</a></iframe><figure><img alt="Dropping Columns by Name" src="https://cdn-images-1.medium.com/max/735/1*fmTLiyxsC6d1PQ6tRJnJSw.png" /></figure><p>In this case, we do not want the columns sex and year. To do this, we have made a vector of column names using the c() or concat function and put a ‘-’ sign in front of the vector to omit those rows.</p><p>Another major problem in datasets is the presence of null values. To count the number of null values, we use the <strong>function sum(is.na(..))</strong> as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea0ef80d13f56fde4b1892200195098/href">https://medium.com/media/eea0ef80d13f56fde4b1892200195098/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/35/1*jgD9Jg_p79Fc-cHEqFj82g.png" /></figure><p>From above, we can see that the dataset has 19 null values in total.</p><p>To remove these values, we use the <strong>na.omit(..) function</strong> as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41f7614ad8da8e5ce46e66030513d337/href">https://medium.com/media/41f7614ad8da8e5ce46e66030513d337/href</a></iframe><figure><img alt="Dropping Missing Values" src="https://cdn-images-1.medium.com/max/863/1*DKif_kY9zpwrtfjSxDgMxQ.png" /></figure><p>Here, we can see that 11 rows were removed (as the number of rows dropped from 344 to 333). This means that some rows had multiple null values.</p><p>In the real world, we remove columns on the basis of correlation. To know which columns are highly correlated, we will plot a correlation heatmap. However, correlation can only be calculated between numeric columns. So, let’s select only the numeric columns from the dataset and make the change permanent.</p><p>To do this, we have used the <strong>select_if()</strong> and <strong>is.numeric</strong> functions. The select_if() function is a part of the ‘tidyverse’ package and subsets the column based on a condition. The is.numeric function checks whether a column is of the numeric data type. The syntax of the select_if() function is:</p><blockquote>select_if(dataset name, condition)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2c06d12eea10b7880b79cfe5cb0e5c2/href">https://medium.com/media/f2c06d12eea10b7880b79cfe5cb0e5c2/href</a></iframe><figure><img alt="Select If Function" src="https://cdn-images-1.medium.com/max/634/1*OgP2uabtJwaWufI31rPJ9g.png" /></figure><p>As we can see, the penguins dataset has only numeric columns, viz. bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, and year.</p><p>Note: just by typing the name of the dataset, we can have a preview of the dataset.</p><p>To avoid any calculation error, let’s drop rows with missing values, and make it permanent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/001ea6e3da45541d1686ff41fa0fe17d/href">https://medium.com/media/001ea6e3da45541d1686ff41fa0fe17d/href</a></iframe><figure><img alt="Dropped Missing Values" src="https://cdn-images-1.medium.com/max/34/1*Z6F04NehpYCwsVSMDglgJg.png" /></figure><p>As we can see, there are no missing values in the dataset.</p><p>All set now! Let’s plot the correlation heatmap.</p><p>We will be using the <strong>cor() function</strong> to calculate the correlation between the columns in the dataset. Let’s store this in a variable called corr.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bbbea7dc681065d32b6966515d7069f/href">https://medium.com/media/1bbbea7dc681065d32b6966515d7069f/href</a></iframe><p>To plot the correlation heatmap, we need to install the <strong>‘corrplot’</strong> library. Before you see the next code snippet, write your own code! Let’s test your learning.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b5493f21aa6b4d408fd40d93daadb8f/href">https://medium.com/media/2b5493f21aa6b4d408fd40d93daadb8f/href</a></iframe><p>Now let’s plot the <strong>heatmap</strong>. The syntax is rather simple:</p><blockquote>corrplot(correlation between columns)</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36fe3470b5c9d008cd05252383bf026c/href">https://medium.com/media/36fe3470b5c9d008cd05252383bf026c/href</a></iframe><figure><img alt="Correlation Heatmap" src="https://cdn-images-1.medium.com/max/665/1*ERRdQekNtViqh9MbCThlcQ.png" /></figure><p>Ta-da! As we can see, flipper_length_mm is highly correlated with bill_lenght_mm and body_mass_g. That means, we will have to drop it to improve the accuracy of our model. Nuh-uh, you’ll have to write the code for this one!</p><p>Psst. scroll up for the cheat code!</p><p>Congratulations! You can now perform basic statistical operations on datasets and make beautiful visualizations using R. At this point, we encourage you to explore further and move forward in your journey to become an R expert. Here are some resources that might help:</p><p><a href="https://cran.r-project.org/doc/manuals/R-intro.pdf">https://cran.r-project.org/doc/manuals/R-intro.pdf</a></p><p><a href="https://www.tidyverse.org/">https://www.tidyverse.org/</a></p><p><a href="https://ggplot2.tidyverse.org/reference/">https://ggplot2.tidyverse.org/reference/</a></p><p><strong><em>Special thanks to Lajith Puthuchery and Nishant Dash for their valuable contributions to the article.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1a469e5e68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/programming-in-r-a-case-study-c1a469e5e68">Programming in R: A Case Study</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 10 — Storing data using Disk]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-10-storing-data-using-disk-8d1d31022ba9?source=rss----91439e9ef940---4</link>
            <guid isPermaLink="false">https://medium.com/p/8d1d31022ba9</guid>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Nitigya Kapoor]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:15:39 GMT</pubDate>
            <atom:updated>2020-06-03T16:41:02.052Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 10 — Storing data using Disk</h3><h4>In this tutorial, we will be learning about storing data using Disks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQcaalKKYVkZ2zKPxWKVSQ.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the last article of the series <strong>IECSE Crash Course: Development with Swift</strong>. Through the course of 10 articles, we have made 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/Article9/Users">here</a>.</blockquote><p>For storing data will be using <strong>Disks</strong>, which provides powerful and simple file management.</p><p>To install Disks we need to use CocoaPods, that is a dependency manager for Swift and Objective-C Cocoa projects.</p><h3><strong>Setting up Disks</strong></h3><p>Open up your terminal and follow along with these commands.</p><p>Firstly, we need to install cocoapods.</p><pre>sudo gem install cocoapods</pre><p>Then, we need to do create a Podfile.</p><pre>pod init</pre><p>Open up the PodFile you just created, and inside we need to add the dependency for Disk.</p><pre>platform :ios, ‘9.0’<br>target ‘Users’ do<br>use_frameworks!<br>supports_swift_versions ‘&lt; 5.0’ # configure this for your project</pre><pre>pod ‘Disk’, ‘~&gt; 0.6.4’</pre><pre>end.</pre><p>After this, we need to install all the dependencies in your project.</p><pre>pod install</pre><p>Make sure to always open the Xcode workspace instead of the project file when building your project.</p><h3><strong>Disk</strong></h3><p>As Disks uses codeable protocol, we don’t need to worry about encoding or decoding, this just makes working with structs easier.</p><p>Disks follow <a href="https://developer.apple.com/icloud/documentation/data-storage/index.html">iOS Data Storage Guidelines</a> and allow us to save data in some predefined directories.</p><h4>Documents Directory — .documents</h4><p>We use this to store data that is user-generated and doesn’t change at all, data saved inside this will automatically backed-up by iCloud.</p><h4>Caches Directory — .caches</h4><p>Data that can be downloaded again or regenerated should be stored in this directory.</p><p>For example, in our app, we are fetching some data using a network call, so every time we open our app, it calls that request every time, we can cache this data to avoid this call again and again.</p><h4>Application Support Directory — .applicationSupport</h4><p>In general, this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files, configuration files, templates and modified versions of resources loaded from the app bundle.</p><h4>Temporary Directory — .temporary</h4><p>Data that is used only temporarily should be stored. Although these files are not backed up to iCloud and we need to remove these files as soon as we are done with them, that they do not continue to consume space on the user’s device.</p><h3><strong>Caching Data</strong></h3><p>We can save data by using .save() method.</p><pre>try? Disk.save(data, to: .caches, as: “files.json”)</pre><p>Here, data can be an UIImage or even JSON. We will be storing data in the cache directory and we need to give a filename in this case: files.json.</p><p>We will save/cache the data after we receive it from the network call.</p><p>Let’s look at <em>Networking.sw</em>ift. But first, we need to import Disk in our Swift file. We can do that by using the import statement at the top of the file.</p><pre>import Disk</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWKyChl2_7Sv0OWkKhv1cA.png" /><figcaption>Saving the data</figcaption></figure><p>After we receive the jsonData we will save that before we encode the data , as mentioned earlier , Disk takes care of encoding/decoding so we don’t need to worry about that, we will save data as <em>users.json.</em></p><p>Next, we need to change the way we load data inside our tableview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKWFT7LPB_lD5ckU0VRWkQ.png" /><figcaption>Retrieving the data</figcaption></figure><p>First, we need to retrieve the data stored as<em> users.json</em> from .caches , we put a try which will go inside the catch block, in case, we run into any error while retrieving the data. Errors can be caused if the cache expires so we need to fetchData from a network call.</p><p>After this, we need to call <em>reloadData() </em>which reloads the rows and sections of the table view.</p><p>Further Reading :</p><p><a href="https://cocoapods.org/pods/Disk">Disk</a></p><h4>Congratulations🎉! You have just completed all the tutorialsl!</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><h4><strong>Summing up everything</strong></h4><p>Now the series finally comes to an end. Thank you for reading up our articles and we hope that you learned something along the way.</p><p>Our journey so far :<br>First, we learned about programmatic UI’s and using TableView’s and building custom TableView Cells. After that, we learned about color themes and Dark Mode. We set up our NavigationBar and learn about how to handle JSON in Swift along the way. Then, came the most crucial part of development that is networking and we also set up the TabBar in our app. We learned about handling data in iOS using delegates and doing form data validation along with UIAlertControllers. Finally, we finished the series with some lessons on caching in Swift using Disks.</p><p>If you would like to learn more about iOS development using Swift.</p><ul><li><a href="https://www.raywenderlich.com/ios/paths/learn">iOS and SwiftUI for Beginners</a></li><li><a href="https://www.hackingwithswift.com/100">The 100 Days of Swift</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d1d31022ba9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-10-storing-data-using-disk-8d1d31022ba9">Swift Part 10 — Storing data using Disk</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 9 — Working with UIAlertController]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-9-working-with-uialertcontroller-c0726a84eb56?source=rss----91439e9ef940---4</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----91439e9ef940---4</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----91439e9ef940---4</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 6 — Tab Bar Controllers]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-6-tab-bar-controllers-6a4cf8bc633d?source=rss----91439e9ef940---4</link>
            <guid isPermaLink="false">https://medium.com/p/6a4cf8bc633d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Nitigya Kapoor]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:12:13 GMT</pubDate>
            <atom:updated>2020-05-31T08:23:50.334Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 6 — Tab Bar Controllers</h3><h4>In this tutorial, we will learn how to make tab bar and navigate between screen using navigation controllers.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBy6caPlXamK83Ojnibayg.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the sixth 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/Article5/Users"> here</a>.</blockquote><p>Starting off, let’s make a new file using Command + N save it as <em>TabBarController.swif</em>t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QtQW9V1x5N8iNHiJWlCXg.png" /><figcaption>Creating a new file</figcaption></figure><p>Add this code here, we need to make this a subclass of UITabBarController.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c45c352c1a92bcb95b062a6a74559cd/href">https://medium.com/media/3c45c352c1a92bcb95b062a6a74559cd/href</a></iframe><p>A tab bar controller, of class UITabBarController, is a <em>container view controller</em>. We typically group together 3–5 together for better organisation. We switch from views by tapping the tab bar items in the bottom bar.</p><p>Let’s add a function to setup the tabs. In the previous article, we embedded the table view inside the navigation controller and the code was placed in SceneDelegate.swift. Now, we will shift that part from SceneDelegate.swift to TabBarController.swift.</p><p>We should call the function from viewDidLoad().</p><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {<br>    <strong>super</strong>.viewDidLoad()<br>    setupTabs()<br>    //more code to come <br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b224276b52c515ca14adc793df4b7fd/href">https://medium.com/media/0b224276b52c515ca14adc793df4b7fd/href</a></iframe><p>Let’s look at how we setup tabs.</p><p>We are making 2 tab bar items — one will have the tableview inside the navigation controller and other will be our sample screen, that we made earlier.</p><p>The 2 view controllers are assigned to the viewControllersproperty of tabBarController by making use of an <a href="https://learnappmaking.com/array-swift-how-to/">array</a>.</p><p>Every view controller that’s embedded in a tab bar controller has a corresponding <em>tab bar item</em>. This tab bar item, of class UITabBarItem, determines what attributes are displayed in the tab bar, such as an icon and a title.</p><p>Let’s look at different ways we can intialise UITabBarItem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkdCgqXbrESNr1Aw-mVy_A.png" /><figcaption><a href="https://developer.apple.com/documentation/uikit/uitabbaritem">Source</a></figcaption></figure><p>Tag here is an integer which identifies each TaBar item in our application, (think of it as an index of an array).</p><p>Let’s make a function to setup the TabBar properties.</p><pre><strong>fileprivate</strong> <strong>func</strong> setupLayout(){ <br>    tabBar.isTranslucent = <strong>true<br>    </strong>tabBar.barTintColor = UIColor.systemGroupedBackground<br>}</pre><p>The barTintColor applies background color to our TabBar , we have to set isTranslucent to false or else, this color is made to translucent by default.</p><p>We have done a really simple setup where we can have custom background images and do much more with the TabBar.</p><p>We need to call this function inside viewDidLoad()</p><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {<br>    <strong>super</strong>.viewDidLoad()<br>    setupLayout()<br>    setupTabs()<br>}</pre><p>Now, we need to load our MasterTabBarController inside the <em>SceneDelegate.swift.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/159742e2c2843621b5a82e73a71dc526/href">https://medium.com/media/159742e2c2843621b5a82e73a71dc526/href</a></iframe><p>On building <em>( command + R )</em> your app, we should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*f6I7U5wRikDwxN-0P1fOXQ.png" /><figcaption>Final App</figcaption></figure><h4>Wrapping Up</h4><p>In this article, we have segmented our app into two tabs and learnt how to navigate between them. You can continue with the series in the <a href="https://medium.com/iecse-hashtag/swift-part-7-making-a-form-with-validation-4ee72f321ac4">next</a> article where we create a form and learn to validate the data we receive.</p><h4>Congratulations🎉! You have just completed the sixth 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=6a4cf8bc633d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-6-tab-bar-controllers-6a4cf8bc633d">Swift Part 6 — Tab Bar Controllers</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----91439e9ef940---4</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:36 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 4 — NavigationBar and Codable]]></title>
            <link>https://medium.com/iecse-hashtag/swift-part-4-navigationbar-and-codable-6acc41953a1f?source=rss----91439e9ef940---4</link>
            <guid isPermaLink="false">https://medium.com/p/6acc41953a1f</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programmatic]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Nitigya Kapoor]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:10:47 GMT</pubDate>
            <atom:updated>2020-05-31T08:20:55.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 4 — NavigationBar and Codable</h3><h4>In this tutorial, we will learn about NavigationBar and Codable protocol.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqywFdn9jT3e2ZyS4CTmXg.png" /></figure><h3>IECSE Crash Course: Development with Swift</h3><blockquote>This article is going to be the fourth 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/Article3/Users">here</a>.</blockquote><p>In the <a href="https://medium.com/iecse-hashtag/swift-part-3-the-dark-mode-ddf16eb01651">previous</a> article, we learned about the Dark Mode, now, we are going to add a <strong>TitleBar</strong> on top.</p><p>This would mean embedding our TableView inside a <strong>navigation controller. </strong>The navigation controller manages the currently displayed screens using the navigation stack. At the bottom of this stack is the root view controller and at the top is the view controller currently displayed. You use methods to push and pop view controllers on and of the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*5zqaBQFbjEgE-urbTxLH8Q.png" /></figure><p>Firstly change the <em>SceneDelegate.swift, </em>we add a navigationController then we put the rootViewController as our tableview.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/621ba737950c22a633b22cdb55e0225b/href">https://medium.com/media/621ba737950c22a633b22cdb55e0225b/href</a></iframe><p>You could now see a navigation bar at the top , but it feels empty right now. Let’s add a title , we will do that inside the viewDidLoad() in TableViewController.swift.</p><pre>self.title = “Users”</pre><p>Your app should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*KLvNJ05te-4hY5XcakZYgg.png" /><figcaption>Added a navigation title</figcaption></figure><p>We can add items in our NavigationBar, let’s add a navigationItem on the left side.</p><p>Inside the setupTableView(), we create an UIBarButtonItem to be added in the navigationBar.</p><pre><strong>let</strong> add = UIBarButtonItem(barButtonSystemItem: .add, target: <strong>self</strong>, action: <strong>#selector</strong>(goToSecondScreen))</pre><p>We need target and action to do something when we click on the item. Here, target refers to which object the method called is on, which is self, and action is the method to be called.</p><p>Let’s make the goToSecondScreen() function. Firstly, we need to make another UIView which we will present on the click of the item.</p><p>Make a new file using Command + N save it as SampleScreen<em>.swif</em>t.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc2ba9e1fd25921a3f5c8ffaea8d22b3/href">https://medium.com/media/bc2ba9e1fd25921a3f5c8ffaea8d22b3/href</a></iframe><p>Here, we create an instance of SampleScreen and we present that screen over our current context.</p><pre><strong>@objc</strong> <strong>func</strong> goToSecondScreen(){<br>    <strong>let</strong> sampleScreen = SampleScreen()<br>    <strong>self</strong>.navigationController?.present(sampleScreen, animated: <strong>true</strong>)<br>}</pre><p>Now, we need to make add this item inside our navigationBar.</p><pre><strong>self</strong>.navigationItem.rightBarButtonItem = add</pre><p><strong>Codeable</strong></p><p>Introduced in <em>Swift 4</em>, this lets us perform parsing to/from JSON or other serialized formats. When it comes to parsing, there are two things we need to look at first- encoding and decoding.</p><p>Now, let&#39;s define a structure that conforms to the codable protocols. It combines the two protocols which are decodable and encodable into one.</p><p>The compiler will attempt to automatically synthesize the code required to encode or decode an instance of this struct.</p><pre>struct User: Codable { <br>     var name: String <br>     var username : String <br>}</pre><p>Now, we are can use JSONEncoder() and JsonDecoder() on an instance of this structure.</p><p><strong>JSONEncoder</strong></p><p>First, we create an instance of User and JsonEncoder(), and then, put a try so, we can catch any JSON error that might have in encoding the structure.</p><pre>do {<br>   let user = User(name:&quot;nitigya&quot; , username: &quot;itsnitigya&quot;)<br>   let encoder = JSONEncoder()<br>   let data = try encoder.encode(user)<br>} catch let jsonError {<br>    print(&quot;Something Went Wrong&quot;)<br>}</pre><p><strong>JSONDecoder</strong></p><p>Next, we create an instance of JSONDecoder(), then create a new user from the previous JSON that we encoded.</p><pre>do {<br>   let decoder = JSONDecoder() <br>   let user2 = try decoder.decode(User.self, from: data)<br>} catch let jsonError {<br>    print(&quot;Something Went Wrong&quot;)<br>}</pre><p>These protocols really come in handy when we are working with REST Api’s as these use lightweight formats to exchange information like JSON, XML. Over the next articles, we will deal with network calls, so let me define a concrete process of receiving data from such calls.</p><p>First, we create a struct of the data that we are receiving.</p><p>Let’s look at this <a href="https://jsonplaceholder.typicode.com/users">API</a> — for example, here we are receiving four things.</p><p>Looking at the result of the API in <em>Postman</em>, we will make a structure according to the JSON received.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnACzfiR3tkrZjuTc2pooA.png" /><figcaption>JSON Structure</figcaption></figure><p>We make User struct with the id, name, username, website.</p><p>Now, address and company are a key to another JSON, so we make another structure according to that as well.</p><p>We also conform the structure to the decodable protocol, so we can decode the incoming JSON to objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66d4e2cc745ba7e98bf3f357a7c8604f/href">https://medium.com/media/66d4e2cc745ba7e98bf3f357a7c8604f/href</a></iframe><p>Next, let’s get the data using some function. For now, let’s assume we are getting data from a network call. We will learn about this in the next article.</p><pre>let data = someNetworkCall()</pre><p>Now, we decode this data from JSON.</p><pre>let users = try JSONDecoder().decode([User].self, from: data!)</pre><p>Finally, we have an array of objects of type Post and to print each element of the array, we can use a simple for-each loop.</p><pre>users.forEach({ (user) in<br>    print(user) <br>})</pre><h4>Wrapping Up</h4><p>In this article, we have implemented a Nagivation Bar, introduced encoding and decoding and also gotten a brief overview of an API and it’s structure. You can continue with the series in the <a href="https://medium.com/iecse-hashtag/swift-part-5-networking-with-urlsession-6b56783f289a">next </a>article where we learn how to fetch data from an API.</p><h4>Congratulations🎉! You have just completed the fourth 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=6acc41953a1f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/swift-part-4-navigationbar-and-codable-6acc41953a1f">Swift Part 4 — NavigationBar and Codable</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----91439e9ef940---4</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>
    </channel>
</rss>