<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Krishna on Medium]]></title>
        <description><![CDATA[Stories by Krishna on Medium]]></description>
        <link>https://medium.com/@krishna-potharaju?source=rss-278bf7b87fe6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yGsKwxvpGCndZp0KBD5I4A.png</url>
            <title>Stories by Krishna on Medium</title>
            <link>https://medium.com/@krishna-potharaju?source=rss-278bf7b87fe6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:57:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishna-potharaju/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Meta iOS Development: The Beginning]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">If there is one thing that I do when working on a task is look for a Solution that helps me with simplifying my work. Doesn&#x2019;t matter if&#x2026;</p><p class="medium-feed-link"><a href="https://krishna-potharaju.medium.com/meta-ios-development-the-beginning-7b12d2697dfc?source=rss-278bf7b87fe6------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://krishna-potharaju.medium.com/meta-ios-development-the-beginning-7b12d2697dfc?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b12d2697dfc</guid>
            <category><![CDATA[ios-learning]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[developer-journey]]></category>
            <category><![CDATA[coursera]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 02:02:16 GMT</pubDate>
            <atom:updated>2024-11-25T02:02:16.312Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Bridging the Gap: How to Create a ChatGPT Telegram Bot with Notion Backup]]></title>
            <link>https://krishna-potharaju.medium.com/bridging-the-gap-how-to-create-a-chatgpt-telegram-bot-with-notion-backup-65c037831fe8?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/65c037831fe8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[notion-api]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 21:00:35 GMT</pubDate>
            <atom:updated>2023-03-19T21:00:35.035Z</atom:updated>
            <content:encoded><![CDATA[<p>ChatGPT changed how we get answers to some of our questions every day. While the initial load on the platform was low, they handled the UI pretty well. But with recent changes to the platform, you may not be able to see your previous queries if you are running on a free plan (until a week ago) and the platform reached its capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WBGmHnFI-EZ0dxLl9nPDw.png" /></figure><p>One simple solution for that would be to take notes of your questions and answers and save them somewhere locally (Notion in my case) for you to access. It does sound pretty simple but to what extent? You don’t want to manually copy and paste every single query and its response, right? At least I don’t. I try to automate my workload as much as possible.</p><p>How did I achieve this? Enter APIs. They offer a very powerful integration. I have yet another problem to solve, Notion API doesn’t offer webhooks that listen to changes made to a database or page i.e. when a new page is added as such or a block is added to a page. While there might be some other simple solutions to this problem, I chose to solve it using a Social Media platform — Telegram. Telegram offers a beautiful API in terms of bots.</p><p>I used Telegram mainly for one reason, I want to take advantage of offline storage. Since Notion is a web-based application, if I am travelling or if my network is down, the App becomes useless to me which is quite annoying if you think about it. Why use Notion in that case you ask? Well, quite frankly it is easy to use and organize.</p><h3><strong>Challenges:</strong></h3><ol><li>I have to find a way to store session history in case I want to continue to chat based on previous queries and responses. You see, on ChatGPT UI when you send a follow-up question, the assistant will read your previous conversations and then provide you with an answer. It needs to know the context of what you are talking about.</li><li>I want to be able to deploy it on a basic server and not think about the insane amount it will cost me in long run.</li><li>Storage - I wanted to log the steps so that I can go back and review if there are any issues with my application. Even though I am developing this for myself, I should have the ability to check what went wrong and fix it before I can scale the application.</li></ol><p>Again, I built this application model for personal use, this application cannot handle having multiple users as of now. I am building a second version of the App to distribute to users. If you are interested in receiving an email once that is ready, please feel free to sign up <a href="https://forms.gle/U2prq6Wg9CBbDNuT7">here</a>.</p><p>I will build the bot to distribute once requests reach 100. I will also minimize the steps you need to set it up before you can begin to chat.</p><h3>Steps I followed to build the Bot.</h3><p>I did the entire project using Python.</p><h4>Telegram</h4><p>First, you need to create a new bot using BotFather on Telegram App. It is very simple to use, telegram did a fantastic job in making everyone&#39;s life easy. You will get a Bot Token, it is very important to keep that token secure as it controls your bot’s behaviour like receiving messages, reading them, sending messages and so on. Review this <a href="https://core.telegram.org/bots/tutorial">page</a> to get started with your bot.</p><h4>ChatGPT</h4><p>ChatGPT is the heart of your bot, which is the main purpose of this bot. To get started, you need to get an API key from OpenAI. Go to this <a href="https://platform.openai.com/account/api-keys">page</a> to get your API key. Save your key somewhere secure as you can retrieve it once you click done.</p><h4>Notion</h4><p>You could use any other Note taking application if you are not a Notion user. The code needs to be modified according to the application you use. But if you are a Notion user, the project that I am sharing works right out of the box. Go to <a href="https://www.notion.so/my-integrations">my integrations</a> page on your browser to create an <strong>internal token</strong> for your Notion workspace. You can use this <a href="https://leeward-washer-506.notion.site/Chat-GPT-62f0a567e33349b4afb2a93c484d6abf">template</a> to duplicate into your workspace. If you plan on changing the column names of your database, remember to update them inside your application code as well.</p><p>Once you have duplicated the page, click on the menu option (three dots) in the upper right corner of the window. Under connections, add the connection (integration) that you created in the previous step to give the integration access to your Notion page.</p><p>Click on the Table and get the view link. Using the link make a note of the database ID.</p><p>Your link will be of format https://www.notion.so/&lt;database_id&gt;?v=&lt;&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWweeNwxfL-sZ1f6dp7rvw.png" /></figure><p>Once you have all the keys, follow the steps as indicated in the GitHub repository to set up your application server. You have all the commands that you need within the bot to get started with your conversations with ChatGPT. Start by sending a /start message.</p><p><a href="https://github.com/kireeti96/ChatGPTNotion.git">GitHub - kireeti96/ChatGPTNotion</a></p><h4>Future Improvements</h4><p>Currently, this is a very basic integration kind of weekend project. I want to improve the functionality of the bot by adding more commands such as a status command to see if there is a conversation going on. Functionality to add a topic name to the Notion page from within the bot. Some text formatting for better reading capability and so on.</p><p>Remember, the current version is not intended to distributing to others (although that should be the case when building a bot).</p><p>Feel free to fork the repo and submit a PR if you see anything that can be improved with this version.</p><p>Thank you for reading. Have a wonderful day and please share your thoughts or suggestions happy to improve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c037831fe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Integrated my iPhone and iPad to Notion using Notion API]]></title>
            <link>https://krishna-potharaju.medium.com/i-integrated-my-iphone-and-ipad-to-notion-using-notion-api-22ed60ca244b?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ed60ca244b</guid>
            <category><![CDATA[notion-integration]]></category>
            <category><![CDATA[notion-api]]></category>
            <category><![CDATA[ios-shortcuts]]></category>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[shortcuts]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 01:30:47 GMT</pubDate>
            <atom:updated>2022-12-14T01:30:47.970Z</atom:updated>
            <content:encoded><![CDATA[<p>You see something interesting, you should learn about that. That is what I grew up listening to. That is why I explore various things that I come across.</p><p>Recently, I started using Notion a tool that is praised by people around the globe. The number of features that Notion offers is incredible. And a few months ago, I saw that Notion released a public API that we can interact with. So, the developer in me thought of exploring it. I started with a very very small project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LzmZ253ezP0HWq0F" /><figcaption>Photo by <a href="https://unsplash.com/@studiopoline?utm_source=medium&amp;utm_medium=referral">Pauline Bernard</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I took advantage of Shortcuts App and Personal Automation available in iPhone and iPad for this project.</p><p>The project is simple, every time, I plug my device into a charger, it writes a new record into Notion database with current battery level and time. Whenever, I unplug it, it will add battery level into another column in the same row along with the timestamp. Sounds easy right?</p><blockquote><strong><em>Notion Setup.</em></strong></blockquote><p>First, let’s get into Battery info database.</p><p>Step 1: You will need to create a database in your workspace. If you would like to use the shortcuts that I created as it is, you can duplicate the Notion Database template from <a href="https://krishnanote.notion.site/8ff99d4fefd94e57b3b983c72ef18de8?v=0eb3d758ea7146229dc72407452bec4c">here</a>. Once the database is created, click on share icon and copy the link to the database and place it in a text editor. The database ID is the one that comes after “/” and ends before “?v”. Copy the value and store it somewhere handy.</p><p>Step 2: You need to create an internal integration from this <a href="https://www.notion.so/my-integrations">page</a>. Store the Internal Integration Token somewhere safe.</p><p>Step 3: Go to the database you created or duplicated earlier and add the connection you created in above step to this database as shown below.</p><figure><img alt="A screenshot of the database template that is used for this project." src="https://cdn-images-1.medium.com/max/1024/1*gm5LiS9mRX7Zqk6yVkwTnQ.png" /></figure><blockquote><strong><em>iPhone/iPad Setup</em></strong></blockquote><p>I have created two shortcuts for this Automation to work. One is used when a charger is connected and the other when charger is disconnected. You can duplicate the below shortcuts and add the values of database ID and the integration token in the shortcuts.</p><ol><li><a href="https://www.icloud.com/shortcuts/127018f02ff34f22b87252d235646e46">Charger Connected</a></li><li><a href="https://www.icloud.com/shortcuts/cb5bf0af72b04677bf76e0df41e012ee">Charger Disconnected</a></li></ol><p>Once I have the shortcuts setup, I used the Personal automation option on my devices to run these Automation when charger is connected/disconnected. One thing you need to do when setting up Personal Automation is turning off “Ask before Running”. I find that quite annoying. An automation is something I would want to run automatically not something that will need my attention to.</p><p>Easy peasy super easy project that you can work on a Sunday if you are interested in exploring Notion API. I am exploring a lot of different APIs that I can integrate my iPhone to. If I succeed, you will know here.</p><p>Thanks for reading, see you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ed60ca244b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of SwiftUI Learning — Day 12]]></title>
            <link>https://krishna-potharaju.medium.com/100-days-of-swiftui-learning-day-12-371a1f0f07dd?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/371a1f0f07dd</guid>
            <category><![CDATA[100daychallenge]]></category>
            <category><![CDATA[learn-swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[hacking-with-swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Thu, 12 May 2022 00:04:01 GMT</pubDate>
            <atom:updated>2022-05-12T00:04:01.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>100 Days of SwiftUI Learning — Day 12</h3><blockquote><strong>Agenda</strong></blockquote><ol><li>Create your own classes</li><li>Class inheritance</li><li>Add initializers for classes</li><li>Copy classes</li><li>Create deinitializer for a class</li><li>Working with variables inside classes</li><li>Summary: Classes</li><li>Checkpoint: 7</li></ol><h4>Create your own classes</h4><p>Structs lets us create custom data types in swift. There is another way to create custom data types called classes. Let us compare them first.</p><blockquote><strong>Common things between classes and structs</strong></blockquote><ol><li>You get to create and name them.</li><li>You can add properties and methods, including property observers and access control.</li><li>You can create custom initializers to configure new instances however you want.</li></ol><blockquote><strong>Key differences</strong></blockquote><ol><li>You can make one class build upon functionality in another class, gaining all its properties and methods as a starting point. If you want to selectively override some methods, you can do that too.</li><li>Because of that first point, Swift won’t automatically generate a memberwise initializer for classes. This means you either need to write your own initializer, or assign default values to all your properties.</li><li>When you copy an instance of a class, both copies share the same data — if you change one copy, the other one also changes.</li><li>When the final copy of a class instance is destroyed, Swift can optionally run a special function called a <em>deinitializer</em>.</li><li>Even if you make a class constant, you can still change its properties as long as they are variables.</li></ol><blockquote><strong>Basic class example</strong></blockquote><pre><strong>class</strong> Game {<br>    <strong>var</strong> score = 0 {<br>        <strong>didSet</strong> {<br>            print(&quot;Score is now \(score)&quot;)<br>        }<br>    }<br>}<br><br><strong>var</strong> newGame = Game()<br>newGame.score += 10</pre><p>For now, it may seem that there is literally no difference between a struct and a class except for the keyword class . We will learn about all 5 differences pointed above in next chapters.</p><h4>Class Inheritance</h4><p>Swift lets us create class by basing them on existing classes which is a process known as <em>inheritance.</em></p><p>Swift gives the child class (new class), access to properties and methods from the parent class.</p><blockquote><strong>Parent Class</strong></blockquote><pre><strong>class</strong> Employee {<br>    <strong>let</strong> hours: Int<br><br>    <strong>init</strong>(hours: Int) {<br>        <strong>self</strong>.hours = hours<br>    }<br>}</pre><blockquote><strong>Child Class</strong></blockquote><p>To create a child class, use a colon after the child class name and then parent class name. (Child Class : Parent Class).</p><pre><strong>class</strong> Developer: Employee {<br>    <strong>func</strong> work() {<br>        print(&quot;I&#39;m writing code for \(hours) hours.&quot;)<br>    }<br>}<br><br><strong>class</strong> Manager: Employee {<br>    <strong>func</strong> work() {<br>        print(&quot;I&#39;m going to meetings for \(hours) hours.&quot;)<br>    }<br>}</pre><p>We can access the property hours of class Employee. Each of these child classes inherit from Employee, but each adds their own customization. That is why, work() behaves differently when you create their instances and class the method.</p><pre><strong>let</strong> robert = Developer(hours: 8)<br><strong>let</strong> joseph = Manager(hours: 10)<br>robert.work()<br>joseph.work()</pre><p>Child classes can inherit methods from parent class. For example, add the following method to the parent class Employee.</p><pre><strong>func</strong> printSummary() {<br>    print(&quot;I work \(hours) hours a day.&quot;)<br>}<br>let novall = Developer(hours: 8)<br>novall.printSummary() // &quot;I work 8 hours a day. <br>novall.work() // I&#39;m writing code 8 hours.</pre><blockquote><strong>override</strong></blockquote><p>If we want to change the functionality of a method in a child class, you should use the keyword override in the child class. Override does two things.</p><ol><li>If you are changing a method, code doesn’t build until you use the keyword override .</li><li>If you are using the keyword for a method that doesn’t exist in parent class, code doesn’t build as you are not overriding anything.</li></ol><p>It is important to remember that swift handles the use of parameters and return values very smart. Remember, how two functions with different parameters are treated differently by swift, a similar concept is applied in classes as well.</p><p>Let me explain it by using an example. If you are creating a method printSummary(place:String) inside a parent class, you don’t have to use the keyword override as you aren’t replacing the parent method. See the below attached screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jZw7ULFwjT5GHO3WpQ8bA.png" /></figure><h4>Add initializers for classes</h4><p>Swift will not generate a member wise initializer for you. You either need to write you own initializer or provide default values for all your parameters.</p><p>Let us see this by using an example.</p><blockquote>Parent Class</blockquote><pre>class Vehicle {<br>    let isElectric : Bool<br>    <br>    init(isElectric:Bool) {<br>        self.isElectric = isElectric<br>    }<br>}</pre><blockquote>Child Class</blockquote><pre><strong>class</strong> Car: Vehicle {<br>    <strong>let</strong> isConvertible: Bool<br><br>    <strong>init</strong>(isConvertible: Bool) {<br>        <strong>self</strong>.isConvertible = isConvertible<br>    }<br>}</pre><p>This is going to be a problem because, we haven’t provided a value for isElectric in child class. Rather than trying to store isElectric ourselves we instead need to pass it and ask super class to run its own initializer.</p><pre><strong>class</strong> Car: Vehicle {<br>    <strong>let</strong> isConvertible: Bool<br><br>    <strong>init</strong>(isElectric: Bool, isConvertible: Bool) {<br>        <strong>self</strong>.isConvertible = isConvertible<br>        <strong>super</strong>.<strong>init</strong>(isElectric: isElectric)<br>    }<br>}<br><strong>let</strong> teslaX = Car(isElectric: true, isConvertible: false)</pre><h4>Copy classes</h4><p>All copies of a class instance share the same data. That means any changes we make to one copy, applies to all other copies. This happens because classes in swift are reference types in swift, which means all copies of a class refer back to same data.</p><pre><strong>class</strong> User {<br>    <strong>var</strong> username = &quot;Anonymous&quot;<br>}<br>var user1 = User()<br>var user2 = user1</pre><p>This property is shared across all copies of the class. Now, let us change the username property value for user2 instance user2.username = &quot;Krishna&quot; . If we try to print the value of username using user1.username it will print “Krishna” and not “Anonymous”.</p><p>If you want to create a <em>unique</em> copy of a class instance — sometimes called a <em>deep copy</em> — you need to handle creating a new instance and copy across all your data safely.</p><p>In our case that’s straightforward:</p><pre><strong>class</strong> User {<br>    <strong>var</strong> username = &quot;Anonymous&quot;</pre><pre>    <strong>func</strong> copy() -&gt; User {<br>        <strong>let</strong> user = User()<br>        user.username = username<br>        <strong>return</strong> user<br>    }<br>}</pre><p>Now we can safely call <strong>copy()</strong> to get an object with the same starting data, but any future changes won’t impact the original.</p><h4>Create deinitializer for a class</h4><ol><li>Just like initializers, you don’t use <strong>func</strong> with deinitializers – they are special.</li><li>Deinitializers can never take parameters or return data, and as a result aren’t even written with parentheses.</li><li>Your deinitializer will automatically be called when the final copy of a class instance is destroyed. That might mean it was created inside a function that is now finishing, for example.</li><li>We never call deinitializers directly; they are handled automatically by the system.</li><li>Structs don’t have deinitializers, because you can’t copy them.</li></ol><p>Exactly <em>when</em> your deinitializers are called depends on what you’re doing, but really it comes down to a concept called <em>scope</em>. When a value <em>exits scope</em> we mean the context it was created in is going away. In the case of structs that means the data is being destroyed, but in the case of classes it means only one copy of the underlying data is going away — there might still be other copies elsewhere. But when the final copy goes away — when the last constant or variable pointing at a class instance is destroyed — then the underlying data is also destroyed, and the memory it was using is returned back to the system.</p><p>To demonstrate this, we could create a class that prints a message when it’s created and destroyed, using an initializer and deinitializer:</p><pre><strong>class</strong> User {<br>    <strong>let</strong> id: Int</pre><pre>    <strong>init</strong>(id: Int) {<br>        <strong>self</strong>.id = id<br>        print(&quot;User \(id): I&#39;m alive!&quot;)<br>    }</pre><pre>    <strong>deinit</strong> {<br>        print(&quot;User \(id): I&#39;m dead!&quot;)<br>    }<br>}</pre><p>Now we can create and destroy instances of that quickly using a loop — if we create a <strong>User</strong> instance inside the loop, it will be destroyed when the loop iteration finishes:</p><pre><strong>for</strong> i <strong>in</strong> 1...3 {<br>    <strong>let</strong> user = User(id: i)<br>    print(&quot;User \(user.id): I&#39;m in control!&quot;)<br>}</pre><p>When that code runs you’ll see it creates and destroys each user individually, with one being destroyed fully before another is even created as the scope of the user is completed.</p><p>For example, if we were adding our <strong>User</strong> instances as they were created, they would only be destroyed when the array is cleared:</p><pre><strong>var</strong> users = [User]()</pre><pre><strong>for</strong> i <strong>in</strong> 1...3 {<br>    <strong>let</strong> user = User(id: i)<br>    print(&quot;User \(user.id): I&#39;m in control!&quot;)<br>    users.append(user)<br>}</pre><pre>print(&quot;Loop is finished!&quot;)<br>users.removeAll()<br>print(&quot;Array is clear!&quot;)</pre><h4>Working with variables insides classes</h4><pre><strong>class</strong> User {<br>    <strong>var</strong> name = &quot;Paul&quot;<br>}<br><br><strong>let</strong> user = User()<br>user.name = &quot;Taylor&quot;<br>print(user.name)</pre><p>That creates a constant <strong>User</strong> instance, but then changes it – it changes the constant value. That’s bad, right?</p><p>Except it doesn’t change the constant value at all. Yes, the data inside the class has changed, but the class instance itself – the object we created – has <em>not</em> changed, and in fact <em>can’t</em> be changed because we made it constant.</p><p>In contrast, what happens if we made both the <strong>user</strong> instance and the <strong>name</strong> property variables? Now we’d be able to change the property, but we’d also be able to change to a wholly new <strong>User</strong> instance if we wanted. To continue the signpost analogy, it would be like turning the signpost to point at wholly different person.</p><p>Try it with this code:</p><pre><strong>class</strong> User {<br>    <strong>var</strong> name = &quot;Paul&quot;<br>}</pre><pre><strong>var</strong> user = User()<br>user.name = &quot;Taylor&quot;<br>user = User()<br>print(user.name)</pre><p>That would end up printing “Paul”, because even though we changed <strong>name</strong> to “Taylor” we then overwrote the whole <strong>user</strong> object with a new one, resetting it back to “Paul”.</p><p>The final variation is having a variable instance and constant properties, which would mean we can create a new <strong>User</strong> if we want, but once it’s done we can’t change its properties.</p><p>So, we end up with four options:</p><ol><li>Constant instance, constant property — a signpost that always points to the same user, who always has the same name.</li><li>Constant instance, variable property — a signpost that always points to the same user, but their name can change.</li><li>Variable instance, constant property — a signpost that can point to different users, but their names never change.</li><li>Variable instance, variable property — a signpost that can point to different users, and those users can also change their names.</li></ol><h4>Summary: Classes</h4><ul><li>Classes have lots of things in common with structs, including the ability to have properties and methods, but there are five key differences between classes and structs.</li><li>First, classes can inherit from other classes, which means they get access to the properties and methods of their parent class. You can optionally override methods in child classes if you want, or mark a class as being <strong>final</strong> to stop others subclassing it.</li><li>Second, Swift doesn’t generate a memberwise initializer for classes, so you need to do it yourself. If a subclass has its own initializer, it must always call the parent class’s initializer at some point.</li><li>Third, if you create a class instance then take copies of it, all those copies point back to the same instance. This means changing some data in one of the copies changes them all.</li><li>Fourth, classes can have deinitializers that run when the last copy of one instance is destroyed.</li><li>Finally, variable properties inside class instances can be changed regardless of whether the instance itself was created as variable.</li></ul><h4>Checkpoint: 7</h4><blockquote><strong>Challenge</strong></blockquote><p>Make a class hierarchy for animals, starting with <strong>Animal</strong> at the top, then <strong>Dog</strong> and <strong>Cat</strong> as subclasses, then <strong>Corgi</strong> and <strong>Poodle</strong> as subclasses of <strong>Dog</strong>, and <strong>Persian</strong> and <strong>Lion</strong> as subclasses of <strong>Cat</strong>.</p><p>But there’s more:</p><ol><li>The <strong>Animal</strong> class should have a <strong>legs</strong> integer property that tracks how many legs the animal has.</li><li>The <strong>Dog</strong> class should have a <strong>speak()</strong> method that prints a generic dog barking string, but each of the subclasses should print something slightly different.</li><li>The <strong>Cat</strong> class should have a matching <strong>speak()</strong> method, again with each subclass printing something different.</li><li>The <strong>Cat</strong> class should have an <strong>isTame</strong> Boolean property, provided using an initializer.</li></ol><blockquote><strong>My Solution</strong></blockquote><pre>import Cocoa</pre><pre>class Animal {<br>    var legs : Int<br>    init(legs:Int){<br>        self.legs = legs<br>    }<br>}</pre><pre>class Dog:Animal {<br>    func speak() {<br>        print(&quot;The dog is barking&quot;)<br>    }<br>}<br>class Corgi : Dog {<br>    override func speak() {<br>        print(&quot;Corgi barks&quot;)<br>    }<br>}<br>class Poodle: Dog {<br>    override func speak() {<br>        print(&quot;Poodle barks&quot;)<br>    }<br>}<br>class Cat:Animal {<br>    let isTame : Bool<br>    func speak(){<br>        print(&quot;Cat says meow&quot;)<br>    }<br>    init(legs: Int,isTame: Bool) {<br>        self.isTame = isTame<br>        super.init(legs: legs)<br>    }<br>}</pre><pre>class Persian: Cat {<br>    override func speak() {<br>        print(&quot;Persian says meow&quot;)<br>    }<br>}<br>class Lion:Cat {<br>    override func speak() {<br>        print(&quot;Lion says meow&quot;)<br>    }<br>}</pre><p><strong><em>That is everything for today. See you tomorrow.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=371a1f0f07dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of SwiftUI Learning — Day 11]]></title>
            <link>https://krishna-potharaju.medium.com/100-days-of-swiftui-learning-day-11-c24012b8073f?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c24012b8073f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[100daychallenge]]></category>
            <category><![CDATA[learn-swift-programming]]></category>
            <category><![CDATA[hacking-with-swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Wed, 11 May 2022 00:02:52 GMT</pubDate>
            <atom:updated>2022-05-11T00:02:52.458Z</atom:updated>
            <content:encoded><![CDATA[<h3>100 Days of SwiftUI Learning — Day 11</h3><blockquote><strong>Agenda</strong></blockquote><ol><li>Limit access to internal data using access control.</li><li>Static properties and methods.</li><li>Summary: Structs</li><li>Checkpoint 6</li></ol><h4>Limit access to internal data using access control</h4><p>The properties of a struct can be accessed externally which creates loopholes in various applications. Let us consider the below example.</p><pre><strong>struct</strong> BankAccount {<br>    <strong>var</strong> funds = 0<br><br>    <strong>mutating</strong> <strong>func</strong> deposit(amount: Int) {<br>        funds += amount<br>    }<br><br>    <strong>mutating</strong> <strong>func</strong> withdraw(amount: Int) -&gt; Bool {<br>        <strong>if</strong> funds &gt; amount {<br>            funds -= amount<br>            <strong>return</strong> true<br>        } <strong>else</strong> {<br>            <strong>return</strong> false<br>        }<br>    }<br>}<br><strong>var</strong> account = BankAccount()<br>account.deposit(amount: 100)<br><strong>let</strong> success = account.withdraw(amount: 200)<br><br><strong>if</strong> success {<br>    print(&quot;Withdrew money successfully&quot;)<br>} <strong>else</strong> {<br>    print(&quot;Failed to get the money&quot;)<br>}</pre><p>In a normal scenario where this properties mean nothing your code does no harm. But, if you are using this say in a banking environment, you could easily access the property funds and get the money directly without the use of methods deposit or withdraw.</p><p>Like this account.funds -=1000 . The property funds can be controlled if you know the name of the instance. To solve this problem, we have to make sure that such properties can only be accessible by the methods inside the struct and cannot be accessed directly. This is where private comes into picture private var funds = 0 . This is called as <em>access control.</em></p><p>Let us look at some access control techniques:</p><ul><li>Use <strong>private</strong> for “don’t let anything outside the struct use this.”</li><li>Use <strong>fileprivate</strong> for “don’t let anything outside the current file use this.”</li><li>Use <strong>public</strong> for “let anyone, anywhere use this.”</li><li><strong>private(set) </strong>used in cases where anyone can read the property but only the methods inside the struct can write to it.</li></ul><p>If you are declaring multiple properties as private, you may need to create your own initializer.</p><h4>Static properties and methods</h4><p>We came across properties and methods that can be used by instances of a struct. But, you can also add properties and methods directly on a struct itself. We do this by using a keyword <strong><em>static</em></strong>.</p><pre><strong>struct</strong> School {<br>    <strong>static</strong> <strong>var</strong> studentCount = 0<br><br>    <strong>static</strong> <strong>func</strong> add(student: String) {<br>        print(&quot;\(student) joined the school.&quot;)<br>        studentCount += 1<br>    }<br>}<br>School.add(student: &quot;Taylor Swift&quot;)<br>print(School.studentCount)</pre><p>This means the property studentCount and method add() don’t exist uniquely on instances of the struct. Also note that even though we writing to the property <em>studentCount</em> using <em>add(), </em>we don’t need to add the keyword <em>mutating.</em></p><p>If you want to mix and match static and non-static properties and methods, there are two rules:</p><ol><li>To access non-static code from static code… you’re out of luck: static properties and methods can’t refer to non-static properties and methods because it just doesn’t make sense — which instance of <strong>School</strong> would you be referring to?</li><li>To access static code from non-static code, always use your type’s name such as <strong>School.studentCount</strong>. You can also use <strong>Self</strong> to refer to the current type.</li></ol><p>Now we have <strong>self</strong> <em>and</em> <strong>Self</strong>, and they mean different things: <strong>self</strong> refers to the current value of the struct, and <strong>Self</strong> refers to the current <em>type</em>.</p><pre><strong>struct</strong> Employee {<br>    <strong>let</strong> username: String<br>    <strong>let</strong> password: String<br><br>    <strong>static</strong> <strong>let</strong> example = Employee(username: &quot;cfederighi&quot;, password: &quot;hairforceone&quot;)<br>}</pre><h4>Summary: Structs</h4><ul><li>You can create your own structs by writing <strong>struct</strong>, giving it a name, then placing the struct’s code inside braces.</li><li>Structs can have variable and constants (known as properties) and functions (known as methods)</li><li>If a method tries to modify properties of its struct, you must mark it as <strong>mutating</strong>.</li><li>You can store properties in memory, or create computed properties that calculate a value every time they are accessed.</li><li>We can attach <strong>didSet</strong> and <strong>willSet</strong> property observers to properties inside a struct, which is helpful when we need to be sure that some code is always executed when the property changes.</li><li>Initializers are a bit like specialized functions, and Swift generates one for all structs using their property names.</li><li>You can create your own custom initializers if you want, but you must always make sure all properties in your struct have a value by the time the initializer finishes, and before you call any other methods.</li><li>We can use access to mark any properties and methods as being available or unavailable externally, as needed.</li><li>It’s possible to attach a property or methods directly to a struct, so you can use them without creating an instance of the struct.</li></ul><h4>Checkpoint 6</h4><blockquote><strong>Challenge</strong></blockquote><p>Create a struct to store information about a car, including its model, number of seats, and current gear, then add a method to change gears up or down. Have a think about variables and access control: what data should be a variable rather than a constant, and what data should be exposed publicly? Should the gear-changing method validate its input somehow?</p><blockquote><strong>Solution #1</strong></blockquote><p>I have chosen the properties to be public. I cannot think of a case where it needs to be public.</p><pre>struct Car {<br>    let model : String<br>    let numOfSeats : Int<br>    var currentGear : Int<br>    <br>    mutating func gearUp() {<br>        if currentGear &lt; 6 {<br>            currentGear += 1<br>        }<br>        else {<br>            print(&quot;Maximum gear reached&quot;)<br>        }<br>    }<br>    <br>    mutating func gearDown() {<br>        if currentGear &lt; 2 {<br>            print(&quot;Minimum gear reached&quot;)<br>        }<br>        else{<br>            currentGear -= 1<br>        }<br>    }<br>}</pre><pre>var mazda = Car(model: &quot;Mazda 3&quot;, numOfSeats: 4, currentGear: 2)<br>print(mazda.currentGear) // Prints 2<br>mazda.gearUp()<br>print(mazda.currentGear) //Prints 3<br>mazda.gearUp()<br>print(mazda.currentGear) // Prints 4</pre><pre>mazda.gearDown()<br>print(mazda.currentGear)//Prints 3</pre><blockquote><strong>Solution #2</strong></blockquote><p>For this solution, I have used private for the property currentGear and also created a custom initializer. Additionally, I have also added didSet{} for currentGear property so that we can print out the updated value every time it’s changed.</p><pre><strong>struct</strong> Car {</pre><pre><strong>let</strong> model : String</pre><pre><strong>let</strong> numOfSeats : Int</pre><pre><strong>private</strong> <strong>var</strong> currentGear : Int {</pre><pre><strong>didSet</strong> {</pre><pre>print(&quot;The gear is changed to \(currentGear)&quot;)</pre><pre>}</pre><pre>}</pre><pre><strong>mutating</strong> <strong>func</strong> gearUp() {</pre><pre><strong>if</strong> currentGear &lt; 6 {</pre><pre>currentGear += 1</pre><pre>}</pre><pre><strong>else</strong> {</pre><pre>print(&quot;Maximum gear reached&quot;)</pre><pre>}</pre><pre>}</pre><pre><strong>mutating</strong> <strong>func</strong> gearDown() {</pre><pre><strong>if</strong> currentGear &lt; 2 {</pre><pre>print(&quot;Minimum gear reached&quot;)</pre><pre>}</pre><pre><strong>else</strong>{</pre><pre>currentGear -= 1</pre><pre>}</pre><pre>}</pre><pre><strong>init</strong>(model: String, numOfSeats: Int) {</pre><pre><strong>self</strong>.model = model</pre><pre><strong>self</strong>.numOfSeats = numOfSeats</pre><pre>currentGear = 1</pre><pre>}</pre><pre>}</pre><pre><strong>var</strong> mazda = Car(model: &quot;Mazda 3&quot;, numOfSeats: 4)</pre><pre>mazda.gearUp()</pre><pre>mazda.gearUp()</pre><pre>mazda.gearDown()</pre><p>It is printed as follows:</p><pre><strong>The gear is changed to 2</strong></pre><pre><strong>The gear is changed to 3</strong></pre><pre><strong>The gear is changed to 2</strong></pre><p><strong><em>That is everything for today. See you tomorrow.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c24012b8073f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of SwiftUI Learning — Day 10]]></title>
            <link>https://krishna-potharaju.medium.com/100-days-of-swiftui-learning-day-10-c0bede19296d?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0bede19296d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[hacking-with-swift]]></category>
            <category><![CDATA[learn-swift-programming]]></category>
            <category><![CDATA[100daychallenge]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Tue, 10 May 2022 04:12:53 GMT</pubDate>
            <atom:updated>2022-05-10T04:12:53.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>100 Days of SwiftUI Learning — Day 10</h3><blockquote><strong>Agenda</strong></blockquote><ol><li>Create Structs</li><li>Compute property values dynamically.</li><li>Taking action when a property changes.</li><li>Create custom initializers</li></ol><h4>Create Structs</h4><p>Structs let us create complex data types with their variables and functions.</p><pre>struct Album {<br>    let title : String<br>    let artist : String<br>    let year : Int<br>    <br>    func printSummary() {<br>        print(&quot;\(title),\(artist),\(year)&quot;)<br>    }<br>}</pre><p>Like other data type names such as Int, Double etc., it is a convention that the name of your struct contains the first letter uppercase and the rest lowercase.</p><p>Since, Album is a data type, you can create variables or constants using it.</p><pre><strong>let</strong> red = Album(title: &quot;Red&quot;, artist: &quot;Taylor Swift&quot;, year: 2012)</pre><pre>print(red.title)</pre><pre>print(red.<strong>self</strong>)//Will print the values of red.</pre><pre>red.printSummary()</pre><p>The values of the variables can be changed by the functions in a struct. Let us take an example of an employee trying to apply for vacation and see if they can apply or not.</p><pre>struct Employee {<br>    let name: String<br>    var vacationDays: Int<br>    <br>    mutating func takeVacation(days:Int) {<br>        if vacationDays &gt; days {<br>            vacationDays -= days<br>        }<br>        else {<br>            print(&quot;Sorry, you don&#39;t have enough vacation days&quot;)<br>        }<br>    }<br>}</pre><p><strong>Note:</strong></p><ol><li>Any function that reads data and manipulates data belonging to a struct should use keyword mutating in front of it.</li><li>When creating a variable with a struct that has a mutating function and you intend to use the function to change the data, remember to create it as var and not let .</li></ol><blockquote><strong>Good to know</strong></blockquote><ol><li>Variables and constants that belong to structs are called properties.</li><li>Functions that belong to structs are called methods.</li><li>When we create a constant or variable out of a struct, we call that an instance.</li><li>When we create instances of structs we do so using an initializer.</li><li>When a struct is created, swift will create a method inside the struct called init() .</li></ol><p>When creating a struct and you assign a value to any property, that value is taken as the default value. Now, when you are creating an instance, you can either provide a value for the property or swift will take the default value.</p><p>For example, when creating the struct Employee, if I mention var vacationDays = 14 , 14 is taken as default value.</p><pre>let kane = Employee(name:&quot;kane&quot;)</pre><pre>let kane = Employee(name:&quot;kane&quot;,vacationDays:14)</pre><p>Both the statements mentioned above represent the same thing.</p><h4>Compute property values dynamically</h4><p>Structs can have two kinds of property.</p><ol><li><strong>Stored property: </strong>It is a variable or constant that holds a piece of data inside an instance of the struct.</li><li><strong>Computed property: </strong>Calculates the value of the property dynamically every time it is accessed.</li></ol><p>Let us take the same example as above. It can be written as follows:</p><pre><strong>struct</strong> Employee {<br>    <strong>let</strong> name: String<br>    <strong>var</strong> vacationRemaining: Int<br>}<br><br><strong>var</strong> archer = Employee(name: &quot;Sterling Archer&quot;, vacationRemaining: 14)<br>archer.vacationRemaining -= 5<br>print(archer.vacationRemaining)<br>archer.vacationRemaining -= 3<br>print(archer.vacationRemaining)</pre><p>This works fine but we are losing the information regarding how many vacation days are allocated initially. This problem is solved as follows.</p><pre><strong>struct</strong> Employee {<br>    <strong>let</strong> name: String<br>    <strong>var</strong> vacationAllocated = 14<br>    <strong>var</strong> vacationTaken = 0<br><br>    <strong>var</strong> vacationRemaining: Int {<br>        vacationAllocated - vacationTaken<br>    }<br>}<br><strong>var</strong> archer = Employee(name: &quot;Sterling Archer&quot;, vacationAllocated: 14)<br>archer.vacationTaken += 4<br>print(archer.vacationRemaining)<br>archer.vacationTaken += 4<br>print(archer.vacationRemaining)</pre><p>Now, rather than making vacationRemaining something we can assign directly, we are calculating every time we access it.</p><p>Even though we are able to change the value of vacationRemaining by the use of other two properties, we cannot write to it. In order to do this swift uses get and set .</p><pre><strong>var</strong> vacationRemaining: Int {<br>    <strong>get</strong> {<br>        vacationAllocated - vacationTaken<br>    }<br><br>    <strong>set</strong> {<br>        vacationAllocated = vacationTaken + newValue<br>    }<br>}<br><strong>var</strong> archer = Employee(name: &quot;Sterling Archer&quot;, vacationAllocated: 14)<br>archer.vacationTaken += 4<br>archer.vacationRemaining = 5<br>print(archer.vacationAllocated)</pre><p>By changing this property, we are now able to get the value of vacationRemaining and also change the value of other property. After running the code, you will notice that the value of vacationAllocated is changed to 9.</p><h4>Taking action when a property changes</h4><p>Swift lets us create property observers, which are special pieces of code that run when properties change.</p><p>They take two forms:</p><ol><li><strong>didSet: </strong>Observer to run when the property just changed.</li><li><strong>willSet: </strong>Observer to run before the property changed.</li></ol><p>Example to demonstrate the need for property observers.</p><pre><strong>struct</strong> Game {<br>    <strong>var</strong> score = 0<br>}<br><br><strong>var</strong> game = Game()<br>game.score += 10<br>print(&quot;Score is now \(game.score)&quot;)<br>game.score -= 3<br>print(&quot;Score is now \(game.score)&quot;)<br>game.score += 1</pre><p>In this block of code, we have created a struct and updating the score a few times and every time the property value is changed, we are printing its new value but not the third time. Which is considered a bug. To fix this, we use didSet .</p><pre><strong>struct</strong> Game {<br>    <strong>var</strong> score = 0 {<br>        <strong>didSet</strong> {<br>            print(&quot;Score is now \(score)&quot;)<br>        }<br>    }<br>}<br><br><strong>var</strong> game = Game()<br>game.score += 10<br>game.score -= 3<br>game.score += 1</pre><p>Now every time the property score is changed, the piece of code inside didSet is executed. Swift also provides us a constant oldValue inside didSet, in case you need to have custom functionality based on what you are changing from.</p><p>Similarly, there is another block of code that can be used when property is changed that is willSet . The piece of code inside this block will be executed before changing the value of the property.</p><pre><strong>struct</strong> App {<br>    <strong>var</strong> contacts = [String]() {<br>        <strong>willSet</strong> {<br>            print(&quot;Current value is: \(contacts)&quot;)<br>            print(&quot;New value will be: \(newValue)&quot;)<br>        }<br><br>        <strong>didSet</strong> {<br>            print(&quot;There are now \(contacts.count) contacts.&quot;)<br>            print(&quot;Old value was \(oldValue)&quot;)<br>        }<br>    }<br>}<br><br><strong>var</strong> app = App()<br>app.contacts.append(&quot;Adrian E&quot;)<br>app.contacts.append(&quot;Allen W&quot;)<br>app.contacts.append(&quot;Ish S&quot;)</pre><p>The following lines are printed when the code is build and executed.</p><pre><strong>Current value is: []</strong></pre><pre><strong>New value will be: [&quot;Adrian E&quot;]</strong></pre><pre><strong>There are now 1 contacts.</strong></pre><pre><strong>Old value was []</strong></pre><pre><strong>Current value is: [&quot;Adrian E&quot;]</strong></pre><pre><strong>New value will be: [&quot;Adrian E&quot;, &quot;Allen W&quot;]</strong></pre><pre><strong>There are now 2 contacts.</strong></pre><pre><strong>Old value was [&quot;Adrian E&quot;]</strong></pre><pre><strong>Current value is: [&quot;Adrian E&quot;, &quot;Allen W&quot;]</strong></pre><pre><strong>New value will be: [&quot;Adrian E&quot;, &quot;Allen W&quot;, &quot;Ish S&quot;]</strong></pre><pre><strong>There are now 3 contacts.</strong></pre><pre><strong>Old value was [&quot;Adrian E&quot;, &quot;Allen W&quot;]</strong></pre><h4>Create custom initializers</h4><blockquote><strong>Default initializer for structs</strong></blockquote><pre><strong>struct</strong> Player {<br>    <strong>let</strong> name: String<br>    <strong>let</strong> number: Int<br>}<br><br><strong>let</strong> player = Player(name: &quot;Megan R&quot;, number: 15)</pre><p>This block of code creates a new Player instance by providing values for its two properties. This is called as <em>memberwise initializer. </em>Which means it accepts each property in the order it was defined.</p><blockquote><strong>Custom initializer</strong></blockquote><p>Note that when we are writing a custom initializer, all properties must be assigned a value by the end.</p><pre><strong>struct</strong> Player {<br>    <strong>let</strong> name: String<br>    <strong>let</strong> number: Int<br><br>    <strong>init</strong>(name: String, number: Int) {<br>        <strong>self</strong>.name = name<br>        <strong>self</strong>.number = number<br>    }<br>}</pre><p>It is same as the previous block of code except, we have written a custom initializer and we can add extra functionality if needed. By the use of self we mean to say that the value of the parameter to the property.</p><p>Since this is a custom initializer, we can be flexible about how to set the values of the properties. For example, we can only mention the name of the player and the number can be picked randomly.</p><pre><strong>struct</strong> Player {<br>    <strong>let</strong> name: String<br>    <strong>let</strong> number: Int<br><br>    <strong>init</strong>(name: String) {<br>        <strong>self</strong>.name = name<br>        number = Int.random(<strong>in</strong>: 1...99)<br>    }<br>}<br><br><strong>let</strong> player = Player(name: &quot;Megan R&quot;)<br>print(player.number)</pre><p><strong><em>That is everything for today’s learning. See you tomorrow.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0bede19296d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of SwiftUI Learning — Day 9]]></title>
            <link>https://krishna-potharaju.medium.com/100-days-of-swiftui-learning-day-9-6a3e2971c3fc?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a3e2971c3fc</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[100daychallenge]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[learn-swift-programming]]></category>
            <category><![CDATA[hacking-with-swift]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Mon, 09 May 2022 00:03:07 GMT</pubDate>
            <atom:updated>2022-05-09T00:03:07.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>100 Days of SwiftUI Learning — Day 9</h3><blockquote><strong>Agenda</strong></blockquote><ol><li>Create and use closures</li><li>Trailing closures and shorthand syntax</li><li>Accept functions as parameters</li><li>Summary: Closures</li><li>Checkpoint 5</li></ol><h4>Create and use closures</h4><blockquote><strong>Create a copy of a function</strong></blockquote><p>When you create a function, you can create a copy of it and assign it to a variable and then call the copy. Example.</p><pre><strong>func</strong> greetUser() {<br>    print(&quot;Hi there!&quot;)<br>}<br><br>greetUser()<br>//Creating a copy of the function greetUser<br><strong>var</strong> greetCopy = greetUser<br>greetCopy()</pre><p>In the above example, the function greetUser() is copied into a variable greetCopy . Note that when you are copying a function, you should not include parentheses. If you do so, you will be calling the function and assigning the return value of that function to the variable.</p><p>Now that you have made a copy of the function and called the copy, you will be printing Hi there! twice, one from the original function and the other from the copy.</p><blockquote><strong>Closures</strong></blockquote><p>You can skip creating a separate function and add functionality directly to a variable or constant.</p><pre>var greeting = {<br>print(&quot;Hi there&quot;)<br>}<br>greeting()</pre><p>This is called a closure expression. A closure is essentially a function that doesn’t take any parameters and doesn’t return a value.</p><blockquote><strong>Closures with Parameters</strong></blockquote><p>Typically in a function, you will add parameters and return data type outside the braces. But when you are writing a closure, everything should be inside the braces including the parameters and return type of the closure.</p><pre><strong>let</strong> sayHello = { (name: String) -&gt; String <strong>in</strong><br>    &quot;Hi \(name)!&quot;<br>}</pre><p>See the keyword in at the end of the first line that indicates the end of parameters and return type. Everything after that is the body of the closure.</p><blockquote><strong>Function types</strong></blockquote><p>Like integers and doubles, functions also have types. Let us look at an example to better understand the concept.</p><pre>var greetCopy: () -&gt; Void = greetUser</pre><p>The above line of code is type annotation for greetCopy which accepts no parameters and doesn’t return any values.</p><p>The breakdown of the code is as follows:</p><ol><li>The empty parentheses indicate that the function takes no parameters.</li><li>The arrow indicates that we are declaring the return type of the function</li><li>Void indicates that the function returns nothing. We can also use () to indicate the term Void.</li></ol><p>It is important to note that only the type of parameters and return value are a part of function type annotation but not the name of the parameters. Take a look at this example.</p><pre><strong>func</strong> getUserData(<strong>for</strong> id: Int) -&gt; String {<br>    <strong>if</strong> id == 1989 {<br>        <strong>return</strong> &quot;Taylor Swift&quot;<br>    } <strong>else</strong> {<br>        <strong>return</strong> &quot;Anonymous&quot;<br>    }<br>}<br><br><strong>let</strong> data: (Int) -&gt; String = getUserData<br><strong>let</strong> user = data(1989)<br>print(user)</pre><p>See, we are using data(1989) to pass the parameter to the function instead of data(for: 1989) . The same rule applies to closures as well.</p><pre><strong>let</strong> sayHello = { (name: String) -&gt; String <strong>in</strong><br>    &quot;Hi \(name)!&quot;<br>}<br>sayHello(&quot;Taylor&quot;)</pre><p>To reiterate, external parameter names only matter when we are calling a function directly, not when we create a closure or when we take a copy of the function first.</p><blockquote><strong>Passing functions into another function</strong></blockquote><p>Functions can be passed as parameters to another functions. To understand the concept, let us look at the example of sorted() method in arrays.</p><p>sorted() accepts parameters as well. One such parameter is sorted(by:) . This gives us control on how we want to sort the array.</p><pre><strong>let</strong> team = [&quot;Gloria&quot;, &quot;Suzanne&quot;, &quot;Piper&quot;, &quot;Tiffany&quot;, &quot;Tasha&quot;]<br><strong>let</strong> sortedTeam = team.sorted()<br>print(sortedTeam)</pre><p>The above piece of code is general use of sorted() method. Now, if you want to place a team member name in the front, swift allows you to do that by passing a custom function as parameter.</p><pre><strong>func</strong> captainFirstSorted(name1: String, name2: String) -&gt; Bool {<br>    <strong>if</strong> name1 == &quot;Suzanne&quot; {<br>        <strong>return</strong> true<br>    } <strong>else</strong> <strong>if</strong> name2 == &quot;Suzanne&quot; {<br>        <strong>return</strong> false<br>    }<br><br>    <strong>return</strong> name1 &lt; name2<br>}</pre><p>The function says how to order two items of the array if one of the two items is “Suzanne”. If “Suzanne” comes first, it returns true means it will be sorted first and the other item is sorted next. If neither of the items is “Suzanne” then they are sorted alphabetically.</p><p>Now that we have written our custom function, we have to pass it as a parameter to sorted() .</p><pre><strong>let</strong> captainFirstTeam = team.sorted(by: captainFirstSorted)<br>print(captainFirstTeam)</pre><p><strong>Note:</strong> sorted() can be passed a function as long as that function accepts two strings as input and returns a Boolean.</p><blockquote><strong>Closure as a parameter to a function</strong></blockquote><p>We have seen two concepts till now, closures and passing functions to another function. Swift lets us combine them both. sorted() just wants a function that will accept two strings and will return a Boolean. It doesn’t care if that function is created by using func or by closures.</p><pre><strong>let</strong> captainFirstTeam = team.sorted(by: { (name1: String, name2: String) -&gt; Bool <strong>in</strong><br>    <strong>if</strong> name1 == &quot;Suzanne&quot; {<br>        <strong>return</strong> true<br>    } <strong>else</strong> <strong>if</strong> name2 == &quot;Suzanne&quot; {<br>        <strong>return</strong> false<br>    }<br><br>    <strong>return</strong> name1 &lt; name2<br>})<br>print(captainFirstTeam)</pre><p>The above code shows how we used closures to pass a custom function as a parameter to sorted() .</p><h4>Trailing closures and shorthand syntax</h4><p>Take another look at the previous piece of code. See how long the first line is where we mention the name of the parameters, their type and return type of the closure.</p><p>In this particular case, we know the purpose of our closure and also what it does. It accepts two strings as parameters and returns a Boolean. If you provide any other parameter types or did not return a Boolean in sorted(by:), your code won’t build. As we know the parameter and return types, we can avoid mentioning them in our code. The modified code looks like this.</p><pre><strong>let</strong> captainFirstTeam = team.sorted(by: { name1, name2 <strong>in</strong></pre><blockquote><strong>Trailing Closure</strong></blockquote><p>We can eliminate the use of (by: and the closing parentheses at the end. This is called as <strong><em>trailing closure syntax.</em></strong></p><pre><strong>let</strong> captainFirstTeam = team.sorted { name1, name2 <strong>in</strong><br>    <strong>if</strong> name1 == &quot;Suzanne&quot; {<br>        <strong>return</strong> true<br>    } <strong>else</strong> <strong>if</strong> name2 == &quot;Suzanne&quot; {<br>        <strong>return</strong> false<br>    }<br><br>    <strong>return</strong> name1 &lt; name2<br>}</pre><blockquote><strong>Shorthand syntax</strong></blockquote><p>By using this syntax, we don’t have to mention parameter names. Instead, swift will provide named values for us: $0 and $1 for the first and second string respectively.</p><pre><strong>let</strong> captainFirstTeam = team.sorted {<br>    <strong>if</strong> $0 == &quot;Suzanne&quot; {<br>        <strong>return</strong> true<br>    } <strong>else</strong> <strong>if</strong> $1 == &quot;Suzanne&quot; {<br>        <strong>return</strong> false<br>    }<br><br>    <strong>return</strong> $0 &lt; $1<br>}</pre><p>Let us take another example that will demonstrate the use of shorthand syntax. Say we are just reversing the order of the array by using a closure, we can do it like this.</p><pre><strong>let</strong> reverseTeam = team.sorted {<br>    <strong>return</strong> $0 &gt; $1<br>}</pre><p>Remember, previously we have discussed about scenarios where we can eliminate the use of keyword return even when we are returning a value. This can be done when your function has only one line of code. It can be applied to closures as well.</p><pre><strong>let</strong> reverseTeam = team.sorted { $0 &gt; $1 }</pre><blockquote><strong>Examples for closures</strong></blockquote><p>The use of filter() in arrays. If you want to filter an array based on the prefix of each item, you can do so by the use of closure.</p><pre><strong>let </strong>team = [&quot;Gloria&quot;, &quot;Suzanne&quot;, &quot;Piper&quot;, &quot;Tiffany&quot;, &quot;Tasha&quot;]<strong><br>let</strong> tOnly = team.filter { $0.hasPrefix(&quot;T&quot;) }<br>print(tOnly)</pre><p>This will print [&quot;Tiffany&quot;,&quot;Tasha&quot;] .</p><p>Transforming every item of an array into uppercased by the use of map() . The map() will let us apply transform to every item of the array and returns a new array.</p><pre><strong>let</strong> uppercaseTeam = team.map { $0.uppercased() }<br>print(uppercaseTeam)</pre><p>This will print [“GLORIA”,SUZANNE”,”PIPER”,”TIFFANY”,”TASHA”].</p><h4>Accept functions as parameters</h4><pre><strong>func</strong> makeArray(size: Int, using generator: () -&gt; Int) -&gt; [Int] {<br>    <strong>var</strong> numbers = [Int]()<br><br>    <strong>for</strong> <strong>_</strong> <strong>in</strong> 0..&lt;size {<br>        <strong>let</strong> newNumber = generator()<br>        numbers.append(newNumber)<br>    }<br><br>    <strong>return</strong> numbers<br>}</pre><p>Let’s break that down…</p><ol><li>The function is called <strong>makeArray()</strong>. It takes two parameters, one of which is the number of integers we want, and also returns an array of integers.</li><li>The second parameter is a function. This accepts no parameters itself, but will return one integer every time it’s called.</li><li>Inside <strong>makeArray()</strong> we create a new empty array of integers, then loop as many times as requested.</li><li>Each time the loop goes around we call the <strong>generator</strong> function that was passed in as a parameter. This will return one new integer, so we put that into the <strong>numbers</strong> array.</li><li>Finally the finished array is returned.</li></ol><blockquote><strong>Using closure to pass generator function as parameter</strong></blockquote><p>The previous code clearly says what is size parameter. But we don’t know the functionality of generator() . That is where closure comes into play.</p><pre><strong>let</strong> rolls = makeArray(size: 50) {<br>    Int.random(<strong>in</strong>: 1...20)<br>}<br><br>print(rolls)</pre><p>The piece of code inside {} acts as the generator function. In this case, we are getting a random number from 1 to 20 and returning that value. Once that value is returned, it is appended to the array numbers .</p><p>The same functionality can be applied by the use of functions.</p><pre><strong>func</strong> generateNumber() -&gt; Int {<br>    Int.random(<strong>in</strong>: 1...20)<br>}<br><br><strong>let</strong> newRolls = makeArray(size: 50, using: generateNumber)<br>print(newRolls)</pre><p>In this case, generateNumber acts as the generator() .</p><blockquote><strong>Multiple functions as parameters</strong></blockquote><p>To better understand this, let us look at the example below.</p><pre><strong>func</strong> doImportantWork(first: () -&gt; Void, second: () -&gt; Void, third: () -&gt; Void) {<br>    print(&quot;About to start first work&quot;)<br>    first()<br>    print(&quot;About to start second work&quot;)<br>    second()<br>    print(&quot;About to start third work&quot;)<br>    third()<br>    print(&quot;Done!&quot;)<br>}<br>doImportantWork {<br>    print(&quot;This is the first work&quot;)<br>} second: {<br>    print(&quot;This is the second work&quot;)<br>} third: {<br>    print(&quot;This is the third work&quot;)<br>}</pre><p>The result can be seen in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SypVcAtxY00VsK9oBTAC9Q.png" /></figure><h4>Summary: Closures</h4><ul><li>You can copy functions in Swift, and they work the same as the original except they lose their external parameter names.</li><li>All functions have types, just like other data types. This includes the parameters they receive along with their return type, which might be <strong>Void</strong> – also known as “nothing”.</li><li>You can create closures directly by assigning to a constant or variable.</li><li>Closures that accept parameters or return a value must declare this <em>inside</em> their braces, followed by the keyword <strong>in</strong>.</li><li>Functions are able to accept other functions as parameters. They must declare up front exactly what data those functions must use, and Swift will ensure the rules are followed.</li><li>In this situation, instead of passing a dedicated function you can also pass a closure — you can make one directly. Swift allows both approaches to work.</li><li>When passing a closure as a function parameter, you don’t need to explicitly write out the types inside your closure if Swift can figure it out automatically. The same is true for the return value — if Swift can figure it out, you don’t need to specify it.</li><li>If one or more of a function’s final parameters are functions, you can use trailing closure syntax.</li><li>You can also use shorthand parameter names such as <strong>$0</strong> and <strong>$1</strong>, but I would recommend doing that only under some conditions.</li><li>You can make your own functions that accept functions as parameters, although in practice it’s much more important to know how to <em>use</em> them than how to <em>create</em> them.</li></ul><h4>Checkpoint 5</h4><blockquote><strong>Challenge</strong></blockquote><pre><strong>let</strong> luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]</pre><p>Your job is to:</p><ol><li>Filter out any numbers that are even</li><li>Sort the array in ascending order</li><li>Map them to strings in the format “7 is a lucky number”</li><li>Print the resulting array, one item per line</li></ol><p>So, your output should be as follows:</p><pre>7 <strong>is</strong> a lucky number<br>15 <strong>is</strong> a lucky number<br>21 <strong>is</strong> a lucky number<br>31 <strong>is</strong> a lucky number<br>33 <strong>is</strong> a lucky number<br>49 <strong>is</strong> a lucky number</pre><blockquote><strong>Solution</strong></blockquote><pre><strong>let</strong> luckyNumbers = [7,4,38,21,16,15,12,33,31,49]</pre><pre>print(luckyNumbers.filter{!$0.isMultiple(of: 2)}.sorted().map{print(&quot;\($0) is a lucky number&quot;)})</pre><p><strong><em>That is everything for today’s learning. See you tomorrow.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a3e2971c3fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of SwiftUI Learning — Day 8]]></title>
            <link>https://krishna-potharaju.medium.com/100-days-of-swiftui-learning-day-8-1e9c3a6230f3?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e9c3a6230f3</guid>
            <category><![CDATA[hacking-with-swift]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[100daychallenge]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[learn-swift-programming]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Sun, 08 May 2022 02:23:02 GMT</pubDate>
            <atom:updated>2022-05-08T02:23:02.669Z</atom:updated>
            <content:encoded><![CDATA[<h3>100 Days of SwiftUI Learning — Day 8</h3><blockquote><strong>Agenda</strong></blockquote><ol><li>Default values for parameters</li><li>Error handling in functions</li><li>Functions recap</li><li>Checkpoint 4</li></ol><h4>Default values for parameters</h4><p>Parameters of functions helps us to customize the outcome of the function by changing parameter values based on the use case. However, there can be cases where you either can’t provide values of all parameters or for some parameters. This will stop your code to build.</p><p>Swift provides us a solution for this problem by allowing us to provide default values. So, when you are calling a function and you did not specify value of a parameter, the default value can be used instead.</p><p>For example.</p><pre><strong>func</strong> printTimesTables(<strong>for</strong> number: Int, end: Int = 12) {<br>    <strong>for</strong> i <strong>in</strong> 1...end {<br>        print(&quot;\(i) x \(number) is \(i * number)&quot;)<br>    }<br>}<br><br>printTimesTables(<strong>for</strong>: 5, end: 20)<br>printTimesTables(<strong>for</strong>: 8)</pre><p>See, in this piece of code, you can either mention the value of end parameter or swift will accept the default value that you have set at the top.</p><blockquote><strong>keepingCapacity</strong></blockquote><p>When an array is created, swift allocates some memory to the array and also gives us flexibility to add new items by increasing the memory as we go. If you no longer need the array, you can remove the contents of the array by using .removeAll(). By doing so, the memory that is allocated to the array will also be removed.</p><p>But sometimes, even though you remove the contents of the array, you might want to retain the memory capacity so that you can add contents to the array again. This can be achieved by kepingCapacity parameter. The parameter takes boolean as value and the default value is set to false. So, if you want to retain memory capacity use .removeAll(keepingCapacity:true) .</p><pre><strong>var</strong> characters = [&quot;Lana&quot;, &quot;Pam&quot;, &quot;Ray&quot;, &quot;Sterling&quot;]<br>print(characters.count)<br>characters.removeAll(keepingCapacity: true)<br>print(characters.count)</pre><p>In this example, all the items in the array characters are removed but the memory allocated to the array is retained.</p><h4>Error handling in functions</h4><p>Handling errors in our swift code happens in 3 steps.</p><ol><li>Telling swift about the possible errors that can happen.</li><li>Writing a function that can flag errors if they happen.</li><li>Calling that function, and handling any errors that might happen.</li></ol><p>The tutorial takes an example of checking users password strength and explains all the steps as we go.</p><blockquote><strong>Defining possible errors</strong></blockquote><pre>enum PasswordError: Error {<br>case short, obvious<br>}</pre><p>Error is an existing type in swift. This says that there are two possible errors short and obvious.</p><blockquote><strong>Writing a function that can flag errors</strong></blockquote><p>For the user to see what kind of error they have made, a function should throw the error. When you throw an error, the function terminates immediately without sending back any value.</p><pre><strong>func</strong> checkPassword(<strong>_</strong> password: String) <strong>throws</strong> -&gt; String {<br>    <strong>if</strong> password.count &lt; 5 {<br>        <strong>throw</strong> PasswordError.short <br>    }<br><br>    <strong>if</strong> password == &quot;12345&quot; {<br>        <strong>throw</strong> PasswordError.obvious <br>    }<br><br>    <strong>if</strong> password.count &lt; 8 {<br>        <strong>return</strong> &quot;OK&quot;<br>    } <strong>else</strong> <strong>if</strong> password.count &lt; 10 {<br>        <strong>return</strong> &quot;Good&quot;<br>    } <strong>else</strong> {<br>        <strong>return</strong> &quot;Excellent&quot;<br>    }<br>}</pre><p>If a function is able to throw errors without handling them itself, it has to be marked throws before the return type. The type of error doesn’t need to be specified and if there are no errors, the function must work normally and return the value in this case a string.</p><blockquote><strong>Calling the function</strong></blockquote><p>Now that we have defined the function that checks for possible errors, we should call the function and handle any errors that the function might throw. In swift programming, it is performed in three steps.</p><ol><li>Starting a block of work that might throw errors, using do .</li><li>Calling one or more throwing functions, using try .</li><li>Handling any thrown errors using catch .</li></ol><p>Let us look how we handle the errors thrown by our checkPassword function.</p><pre><strong>let</strong> string = &quot;12345&quot;<br><br><strong>do</strong> {<br>    <strong>let</strong> result = <strong>try</strong> checkPassword(string)<br>    print(&quot;Password rating: \(result)&quot;)<br>} <strong>catch</strong> {<br>    print(&quot;There was an error.&quot;)<br>}</pre><p>We have given a possible password to our checkPassword function. Now, if there is no error thrown by the function, it should print Password rating: some_value . But the string we provided will be marked as an error by our function and throw the error of value obvious . Since there was an error thrown, the catch block will catch the error and say There was an error. . You can also write a function depending upon your requirement and can execute the function to handle the errors in the catch block.</p><p>Pseudocode for this is as follows:</p><pre><strong>do</strong> {<br>    <strong>try</strong> someRiskyWork()<br>} <strong>catch</strong> {<br>    print(&quot;Handle errors here&quot;)<br>}</pre><p>You must know that when a try block is present it must be followed by one or more catch blocks that will handle the errors. The try block must always be inside a do block.</p><p>Multiple catch blocks can be written to handle different types of errors.</p><pre><strong>let</strong> string = &quot;12345&quot;<br><br><strong>do</strong> {<br>    <strong>let</strong> result = <strong>try</strong> checkPassword(string)<br>    print(&quot;Password rating: \(result)&quot;)<br>} <strong>catch</strong> PasswordError.short {<br>    print(&quot;Please use a longer password.&quot;)<br>} <strong>catch</strong> PasswordError.obvious {<br>    print(&quot;I have the same combination on my luggage!&quot;)<br>} <strong>catch</strong> {<br>    print(&quot;There was an error.&quot;)<br>}</pre><h4>Functions recap</h4><ul><li>Functions let us reuse code easily by carving off chunks of code and giving it a name.</li><li>All functions start with the word <strong>func</strong>, followed by the function’s name. The function’s body is contained inside opening and closing braces.</li><li>We can add parameters to make our functions more flexible — list them out one by one separated by commas: the name of the parameter, then a colon, then the type of the parameter.</li><li>You can control how those parameter names are used externally, either by using a custom external parameter name or by using an underscore to disable the external name for that parameter.</li><li>If you think there are certain parameter values you’ll use repeatedly, you can make them have a default value so your function takes less code to write and does the smart thing by default.</li><li>Functions can return a value if you want, but if you want to return multiple pieces of data from a function you should use a <em>tuple</em>. These hold several named elements, but it’s <em>limited</em> in a way a dictionary is not — you list each element specifically, along with its type.</li><li>Functions can throw errors: you create an enum defining the errors you want to happen, throw those errors inside the function as needed, then use <strong>do</strong>, <strong>try</strong>, and <strong>catch</strong> to handle them at the call site.</li></ul><h4>Checkpoint 4</h4><blockquote><strong>Challenge</strong></blockquote><p>Write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. That sounds easy, but there are some catches:</p><ol><li>You can’t use Swift’s built-in <strong>sqrt()</strong> function or similar – you need to find the square root yourself.</li><li>If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error.</li><li>You should only consider integer square roots — don’t worry about the square root of 3 being 1.732, for example.</li><li>If you can’t find the square root, throw a “no root” error.</li></ol><blockquote><strong>Solution</strong></blockquote><p>We are using brute force method to solve this challenge.</p><pre><strong>import</strong> Cocoa</pre><pre><strong>enum</strong> rootError: Error {</pre><pre><strong>case</strong> noroot, outofbounds</pre><pre>}</pre><pre><strong>func</strong> squareRoot(number: Int) <strong>throws</strong> -&gt; Int {</pre><pre><strong>if</strong> number&lt;1 || number&gt;10000 {</pre><pre><strong>throw</strong> rootError.outofbounds</pre><pre>}</pre><pre><strong>for</strong> i <strong>in</strong> 1...100 {</pre><pre><strong>if</strong> i*i == number {</pre><pre><strong>return</strong> i</pre><pre>}</pre><pre>}</pre><pre><strong>throw</strong> rootError.noroot</pre><pre>}</pre><pre><strong>var</strong> number = 20</pre><pre><strong>do</strong> {</pre><pre><strong>let</strong> result = <strong>try</strong> squareRoot(number: number)</pre><pre>print(&quot;The square root of \(number) is \(result) &quot;)</pre><pre>}</pre><pre><strong>catch</strong> rootError.noroot{</pre><pre>print(&quot;No interger root&quot;)</pre><pre>}</pre><pre><strong>catch</strong> rootError.outofbounds {</pre><pre>print(&quot;The number is out of bounds&quot;)</pre><pre>}</pre><blockquote><strong>That is all for today. See you tomorrow.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e9c3a6230f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of SwiftUI Learning — Day 7]]></title>
            <link>https://krishna-potharaju.medium.com/100-days-of-swiftui-learning-day-7-31c3e490bf7?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/31c3e490bf7</guid>
            <category><![CDATA[learn-swift-programming]]></category>
            <category><![CDATA[hacking-with-swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[100daychallenge]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Sat, 07 May 2022 00:01:07 GMT</pubDate>
            <atom:updated>2022-05-07T00:01:07.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>100 Days of SwiftUI Learning — Day 7</h3><blockquote>Life has two rules: 1.Never quit. 2. Always remember rule #1</blockquote><blockquote><strong>Agenda</strong></blockquote><ol><li>Reuse code with functions</li><li>Return value from functions</li><li>Return multiple values from functions</li><li>Customize parameter labels</li></ol><h4>Reuse code with functions</h4><p>Functions are used so that the block of code can be reused multiple times.</p><p>Syntax:</p><pre>func func_name() {<br>Statements<br>}</pre><p>The function is called as follows func_name() . You can add parameters inside the braces. Look at the following example.</p><pre><strong>func</strong> printTimesTables(number: Int, end: Int) {<br>    <strong>for</strong> i <strong>in</strong> 1...end {<br>        print(&quot;\(i) x \(number) is \(i * number)&quot;)<br>    }<br>}<br>//Calling the function with parameters.<br>printTimesTables(number: 5, end: 20)</pre><h4>Return value from functions</h4><p>You can return a value from within a function. That value can be assigned to a variable or constant out side the function. Here is an example.</p><pre><strong>func</strong> rollDice() -&gt; Int {<br>    <strong>return</strong> Int.random(<strong>in</strong>: 1...6)<br>}<br><br><strong>let</strong> result = rollDice()<br>print(result)</pre><p>Notice how “-&gt; Int” is added after the function name. That indicates what type of data is returned by the function. Because of this you code won’t build if you are not returning any value.</p><p>Additionally, there is another piece of advantage in swift when returning a value. So, you have indicated that your function will return a value of type Int. If your function has only one line of code, swift will return the value of that statement. For example, in our previous illustration we have use return Int.random(in: 1...6) . Since that is the only statement inside the function we can ignore the keyword return.</p><pre><strong>func</strong> rollDice() -&gt; Int {<br>    Int.random(<strong>in</strong>: 1...6)<br>}<br><br><strong>let</strong> result = rollDice()<br>print(result)</pre><h4>Return multiple values from functions</h4><p>If you want to return two or more values from a function, you could use an array. For example.</p><pre><strong>func</strong> getUser() -&gt; [String] {<br>    [&quot;Taylor&quot;, &quot;Swift&quot;]<br>}<br><br><strong>let</strong> user = getUser()<br>print(&quot;Name: \(user[0]) \(user[1])&quot;)</pre><p>However, this solution may not work if the values of the array are rearranged. This can create problems. Alternatively, you can use dictionaries.</p><pre><strong>func</strong> getUser() -&gt; [String: String] {<br>    [<br>        &quot;firstName&quot;: &quot;Taylor&quot;,<br>        &quot;lastName&quot;: &quot;Swift&quot;<br>    ]<br>}<br><br><strong>let</strong> user = getUser()<br>print(&quot;Name: \(user[&quot;firstName&quot;, <strong>default</strong>: &quot;Anonymous&quot;]) \(user[&quot;lastName&quot;, <strong>default</strong>: &quot;Anonymous&quot;])&quot;)</pre><p>This leads to another problem. See even though you have clearly mentioned firstName and lastName, because you are using dictionaries you need to allocated default values for each when printing them. Even though it works, we can have simpler solution. Swift offers tuples as solution.</p><pre><strong>func</strong> getUser() -&gt; (firstName: String, lastName: String) {<br>    (firstName: &quot;Taylor&quot;, lastName: &quot;Swift&quot;)<br>}<br><br><strong>let</strong> user = getUser()<br>print(&quot;Name: \(user.firstName) \(user.lastName)&quot;)</pre><p>Tuples are a collection data type which can take multiple pieces of data, have a fixed size and can have a variety of data types.</p><blockquote><strong>Optimization #1</strong></blockquote><p>Since tuples have a fixed size, when you are returning values by using tuple, you have to use their names again after declaration. Swift will assign the values in order.</p><pre><strong>func</strong> getUser() -&gt; (firstName: String, lastName: String) {<br>    (&quot;Taylor&quot;, &quot;Swift&quot;)<br>}</pre><blockquote><strong>Optimization #2</strong></blockquote><p>Sometimes you will find you are given tuples where the elements don’t have names. In this case, you can access the tuple’s elements using numerical indices starting from 0.</p><pre><strong>func</strong> getUser() -&gt; (String, String) {<br>    (&quot;Taylor&quot;, &quot;Swift&quot;)<br>}<br><br><strong>let</strong> user = getUser()<br>print(&quot;Name: \(user.0) \(user.1)&quot;)</pre><blockquote><strong>Optimization #3</strong></blockquote><p>If a function returns a tuple you can actually pull the tuple apart into individual values if you want to.</p><pre><strong>func</strong> getUser() -&gt; (firstName: String, lastName: String) {<br>    (firstName: &quot;Taylor&quot;, lastName: &quot;Swift&quot;)<br>}<br><br><strong>let</strong> user = getUser()<br><strong>let</strong> firstName = user.firstName<br><strong>let</strong> lastName = user.lastName<br><br>print(&quot;Name: \(firstName) \(lastName)&quot;)</pre><p>You can also eliminate one additional step when using tuples. Instead of assigning the return values to a constant user and then calling individual parts, you can use a tuple instead.</p><pre>let (first, last) = getUser()</pre><p>If you don’t need a part of the tuple from the function, you can say swift to ignore it by using _ in its position. Say for example, you don’t need to know the value of lastName. You can do as follows.</p><pre>let (first, _) = getUser()</pre><h4>Customize parameter labels</h4><p>The name of the parameter inside a function is highly useful when you are calling a funciton.</p><pre><strong>func</strong> hireEmployee(name: String) { }<br><strong>func</strong> hireEmployee(title: String) { }<br><strong>func</strong> hireEmployee(location: String) { }</pre><p>In the above code, all there functions have the same name. But depending on the name of the parameter, swift calls the correct method.</p><p>But using the parameter name when calling it can be annoying and difficult to read sometimes. Take this for example.</p><pre><strong>func</strong> isUppercase(string: String) -&gt; Bool {<br>    string == string.uppercased()<br>}<br><br><strong>let</strong> string = &quot;HELLO, WORLD&quot;<br><strong>let</strong> result = isUppercase(string: string)</pre><p>See the last line where you say string:string. This adds confusion as well. To solve this problem we use _ inside the function to ignore the external parameter label.</p><pre><strong>func</strong> isUppercase(_ string: String) -&gt; Bool {<br>    string == string.uppercased()<br>}<br><br><strong>let</strong> string = &quot;HELLO, WORLD&quot;<br><strong>let</strong> result = isUppercase(string)</pre><p>This looks much better to read.</p><p>The second problem which was discussed on the tutorial is using the correct names that makes sense. Let us look at the example.</p><pre><strong>func</strong> printTimesTables(number: Int) {<br>    <strong>for</strong> i <strong>in</strong> 1...12 {<br>        print(&quot;\(i) x \(number) is \(i * number)&quot;)<br>    }<br>}<br><br>printTimesTables(number: 5)</pre><p>This is quite correct, however, if the parameter label is a little different it makes whole lot of difference when calling the function. The above can be converted into this.</p><pre><strong>func</strong> printTimesTables(<strong>for</strong>: Int) {<br>    <strong>for</strong> i <strong>in</strong> 1...12 {<br>        print(&quot;\(i) x \(<strong>for</strong>) is \(i * <strong>for</strong>)&quot;)<br>    }<br>}<br><br>printTimesTables(<strong>for</strong>: 5)</pre><p>It adds more clarity while reading and calling the function. But “for” is a keyword and cannot be used as a function parameter label. To solve this, we can add a second name for internal use.</p><pre><strong>func</strong> printTimesTables(<strong>for</strong> number: Int) {<br>    <strong>for</strong> i <strong>in</strong> 1...12 {<br>        print(&quot;\(i) x \(number) is \(i * number)&quot;)<br>    }<br>}<br><br>printTimesTables(<strong>for</strong>: 5)</pre><p>The internal name is number. The external name is for. The external name is used to call the function.</p><blockquote><strong>That is all for today’s learning. See you tomorrow.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31c3e490bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Days of SwiftUI Learning — Day 6]]></title>
            <link>https://krishna-potharaju.medium.com/100-days-of-swiftui-learning-day-6-40664a2d902e?source=rss-278bf7b87fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/40664a2d902e</guid>
            <category><![CDATA[100daychallenge]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[learn-swift-programming]]></category>
            <category><![CDATA[hacking-with-swift]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Krishna]]></dc:creator>
            <pubDate>Fri, 06 May 2022 00:02:59 GMT</pubDate>
            <atom:updated>2022-05-06T00:02:59.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>100 Days of SwiftUI Learning — Day 6</h3><blockquote>“Striving for success without hard work is like trying to harvest where you haven’t planted.</blockquote><blockquote><strong>Agenda</strong></blockquote><ol><li>For Loop</li><li>While Loop</li><li>Break and Continue</li><li>Checkpoint 3</li></ol><h4>For Loop</h4><p>Loops can be used to iterate through a collection data type.</p><p>Syntax:</p><pre>for loop_variable in list {<br>Statements<br>}</pre><p>You can use loop_variable to traverse through the list in order. In the below example, we use loop variable “l” to iterate through the array letters.</p><pre>let letters = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</pre><pre>for l in letters {<br>print(l)<br>}</pre><blockquote><strong>Range of numbers</strong></blockquote><p>To print a range of numbers say for example 1 to 12, you can follow the below example.</p><pre>for i in 1...12 {<br>print(i)<br>}</pre><p>loop variable can also be use to perform arithmetic operations.</p><pre>for i in 1...12 {<br>print(i*2)<br>}</pre><p>Instead of using the numbers, you can use constants or variables as well for the range.</p><pre><strong>let</strong> left = 1</pre><pre><strong>let</strong> right = 12</pre><pre><strong>for</strong> i <strong>in</strong> <strong>left</strong>...<strong>right</strong> {</pre><pre>print(i)</pre><pre>}</pre><blockquote><strong>Nested For Loops</strong></blockquote><pre><strong>for</strong> i <strong>in</strong> 1...12 {<br>    print(&quot;The \(i) times table:&quot;)<br><br>    <strong>for</strong> j <strong>in</strong> 1...12 {<br>        print(&quot;  \(j) x \(i) is \(j * i)&quot;)<br>    }<br><br>    print()<br>}</pre><blockquote><strong>Exclude upper limit</strong></blockquote><pre>for i in 1..&lt;5 {<br>print(i)<br>}</pre><p>This code will print only from 1 to 4 and will not run for i=5. This can be very helpful when you are iterating through an array by using the count of items in an array.</p><h4>While Loop</h4><p>While loop will continue to execute the loop body until the condition is false.</p><pre><strong>var</strong> countdown = 10<br><br><strong>while</strong> countdown &gt; 0 {<br>    print(&quot;\(countdown)…&quot;)<br>    countdown -= 1<br>}<br><br>print(&quot;Blast off!&quot;)</pre><p>Unlike in for loop, you will have to control counter manually. So depending upon the case, you will either increase or decrease the counter.</p><h4>Continue and Break</h4><blockquote><strong>Continue</strong></blockquote><p>If you are in a situation where you loop should just skip executing at particular conditions, use Continue.</p><p>Let us take an example where we are printing numbers in range of 1 to 10 but we want to skip 5.</p><pre>for i in 1...10 {<br>if i== 5 {<br>continue}<br>print(i)<br>}</pre><blockquote><strong>Break</strong></blockquote><p>On contrary, if you want to skip rest of the loop iterations after meeting a condition, use break. This will exit the loop.</p><p>Let us consider an example where we are printing numbers from 1 to 10 and want to break the loop after 5.</p><pre>for i in 1...10 {<br>if i== 5 {<br>break}<br>print(i)<br>}</pre><h4>Checkpoint 3</h4><blockquote><strong>Challenge</strong></blockquote><p>The problem is called <em>fizz buzz</em>, and has been used in job interviews, university entrance tests, and more for as long as I can remember. Your goal is to loop from 1 through 100, and for each number:</p><ol><li>If it’s a multiple of 3, print “Fizz”</li><li>If it’s a multiple of 5, print “Buzz”</li><li>If it’s a multiple of 3 <em>and</em> 5, print “FizzBuzz”</li><li>Otherwise, just print the number.</li></ol><blockquote><strong>Solution</strong></blockquote><pre><strong>for</strong> i <strong>in</strong> 1...100 {</pre><pre><strong>if</strong> i.isMultiple(of: 3) &amp;&amp; i.isMultiple(of: 5){</pre><pre>print(&quot;FizzBuzz&quot;)</pre><pre>}</pre><pre><strong>else</strong> <strong>if</strong> i.isMultiple(of: 3) {</pre><pre>print(&quot;Fizz&quot;)</pre><pre>}</pre><pre><strong>else</strong> <strong>if</strong> i.isMultiple(of: 5) {</pre><pre>print(&quot;Buzz&quot;)</pre><pre>}</pre><pre><strong>else</strong> {</pre><pre>print(i)</pre><pre>}</pre><pre>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40664a2d902e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>