<?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 Ayush Singhi on Medium]]></title>
        <description><![CDATA[Stories by Ayush Singhi on Medium]]></description>
        <link>https://medium.com/@ayusinghi96?source=rss-64534c9a74a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7TQdy7WT31TUWz7nytIVsg.jpeg</url>
            <title>Stories by Ayush Singhi on Medium</title>
            <link>https://medium.com/@ayusinghi96?source=rss-64534c9a74a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:28:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayusinghi96/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[Strong, weak, and unowned references — Swift 5 (iOS)]]></title>
            <link>https://ayusinghi96.medium.com/referencing-in-swift-5bd1b3163ec?source=rss-64534c9a74a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd1b3163ec</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-development]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Ayush Singhi]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 15:03:16 GMT</pubDate>
            <atom:updated>2021-04-25T15:03:16.777Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strong, weak, and unowned references — Swift 5 (iOS)</h3><h4>Different referencing types in Swift</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JmP6kbEnr6sH9q8VoKiEg.png" /><figcaption>Source: <a href="https://wallpapercave.com/">https://wallpapercave.com/</a> (Edited)</figcaption></figure><p>Hello there!</p><p>I hope you are doing well! In this article, we shall take a look at how object references are declared in the Swift programming language and what are the different types of referencing techniques that can be used, and how.</p><h3>Referencing in Swift</h3><p>In Swift, only <strong><em>classes</em></strong><em> </em>are declared as referencetype, whereas <strong><em>structs </em></strong>and<strong><em> enums </em></strong>are both value types. So when classes are instantiated, ARC reserves a memory block to store its details and uses this address for reference.<br>According to Swift’s official documentation:</p><blockquote>Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.</blockquote><p>On the other hand, no such references are allocated for structures and enums. They are passed as copies of values. According to Swift’s documentation:</p><blockquote>Structures and enumerations are value types, not reference types, and aren’t stored and passed by reference.</blockquote><h3>Types of references</h3><p>Swift supports three types of references —</p><ol><li>strong</li><li>weak</li><li>unowned</li></ol><h4>Strong reference —</h4><p>Whenever we instantiate a class and assign it to a variable or a constant, a strong reference is created. This reference keeps a stronghold of the instance and does not allow ARC to deallocate it. Thus, keeping it alive. This makes strong very useful for development.</p><p>But even though, s<em>trong</em> might seem useful and robust, it creates a problem of <strong><em>Strong Retain Cycles </em></strong>which are cyclic graphs like structures formed due to interdependency between references.<br>Let’s consider an example involving two classes — Car and Owner, where an owner may have a car and similarly a car may have an owner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IJ0kx7Wxt0GgyydfcWL9w.png" /><figcaption><strong>Car </strong>and <strong>Owner </strong>classes</figcaption></figure><pre><strong>Driver Code -</strong></pre><pre>var owner: Owner? = Owner(name: &quot;Ayush&quot;) // An owner<br>var car: Car? = Car(brand: &quot;Tata&quot;) // A car</pre><pre>owner?.car = car<br>car?.owner = owner</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3Xw1Knsbm9dsoY4602_YQ.png" /><figcaption>Variables <strong>owner </strong>and <strong>car </strong>hold strong references to <strong>Owner </strong>and <strong>Car </strong>instances respectively. Also, both <strong>car </strong>and <strong>owner </strong>hold a strong reference to each other.</figcaption></figure><p>It is evident from the above example that Owner holds a <em>strong</em> reference to a Car instance, while Car holds a <em>strong </em>reference to an Owner instance, hence, creating an internal <em>retain cycle. </em>Let’s see what happens if we try to solve this by breaking the references and assigning nil to the variables.</p><pre>owner = nil // Break the reference<br>car = nil // Break the reference</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EkDFJC2UoRT4bfSYCuFZXw.png" /><figcaption>Strong retain cycle between i<strong>nstance User</strong> and<strong> instance Address</strong></figcaption></figure><p>What we see is that even when the references to Owner and Car instances are broken, the internal retain cycle is not removed and it restricts ARC from deallocating the instances. As a result, they continue to live. The problem here is that this type of memory retention might lead to memory leaks in the application. In order to solve this, Swift developers came up with— weak and unowned.</p><h4>Weak reference —</h4><p>Weak belongs to a different category of references that allows ARC to deallocate an instance even when active references(not <em>strong</em>) exist<em>. </em>So unlike <em>strong, weak </em>references<em> </em>do not restrict ARC from doing its job. Whenever ARC deallocates an instance, it automatically assigns a nil value to all its weak references. Now, since ARC can update the value of <em>weak</em> references at runtime, they must always be declared as a var and optional.</p><p>In the above example of Car and Owner, we saw that a retain cycle was created because of strong references. So let&#39;s modify the Owner class a bit.<br>Since the owner may or may not have a car, we will make car an optional weak variable.</p><pre>// In class Owner, replace &quot;var car: Car?&quot; with</pre><pre>weak var car: Car? // Making car weak</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYkFjc0NClT3F1MFfu59Jw.png" /></figure><p>In the above example, if we now try to break the reference of car by assigning it nil, the owner does not try to retain the instance because it has a weak reference.</p><pre>var car = nil</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cD0oi4ZOp392UqS9gP799w.png" /></figure><p>In this case, no retain cycle is created as car is a weak reference and hence its instance is deallocated, which is evident from the output on the console — the deinit statement of class Car.</p><h4>Unowned reference —</h4><p>Unowned is the third type of reference. Similar to weak , it also allows ARC to deallocate an instance if it has no active strong references to it. But unlike weak, an unowned variable cannot hold nil value which is why ARC does not assign it nil at runtime.</p><p>However, an unowned reference should be used only when one is sure that the other instance will always outlive or has a longer lifetime. Since the unowned instance always outlives the containing instance, it is always expected to have a value. According to Swift’s documentation —</p><blockquote>If you try to access the value of an unowned reference after that instance has been deallocated, you’ll get a runtime error.</blockquote><p>Let’s consider a different example of two entities — Car and Engine. An engine is always attached to a Car and cannot outlive it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4ApjTMcfmh_pXPNdtTiIQ.png" /><figcaption>Notice <strong>Engine </strong>holds an unowned reference to <strong>Car</strong></figcaption></figure><pre><strong>Driver Code -</strong></pre><pre>var car: Car? = Car(brand: &quot;Tata&quot;) // A car<br>car.engine = Engine(type: &quot;v8&quot;, car: car!)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPlrynLPY3XydarlEJ9SUw.png" /></figure><p>Here, var car holds a strong reference to a car, which holds an instance to an Engine object. That contains an unowned car reference, as engine cannot outlive car itself. Hence, no internal retain cycle is formed. If we now destroy the car reference, the engine will be automatically destroyed and memory will be reclaimed by ARC.</p><pre>var car = nil</pre><p>As soon as the above statement is executed, the deinit is executed and prints</p><pre><strong>Car deallocated<br>Engine deallocated</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnCum6ga8O3g2v_4BMiZKg.png" /><figcaption>Instance destroyed as the reference to the <strong>car </strong>is broken.</figcaption></figure><p>Thus, we see what the uses and the objectives of the three types of references in Swift are and how they differ from each other.</p><p>Thank you for following along. I hope this article has been helpful.</p><p>Bye for now! 👋<br>Happy Coding 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd1b3163ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VIP Architecture in iOS]]></title>
            <link>https://ayusinghi96.medium.com/vip-architecture-in-ios-7922b7da7c8e?source=rss-64534c9a74a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7922b7da7c8e</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[vip]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ayush Singhi]]></dc:creator>
            <pubDate>Sat, 27 Mar 2021 17:56:09 GMT</pubDate>
            <atom:updated>2021-03-27T17:56:09.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>An overview of getting started with Clean Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*du1mOnSHkxAIV8AmitXstQ.png" /><figcaption>Source — Self-created😎</figcaption></figure><p>Hello 😎!</p><p>In this article, we are going to discuss how to get started with<em> VIP Architecture in iOS</em>. We shall begin by looking at certain theoretical backgrounds to understand the basic working and data-flow in VIP. Following which we will dive into some real code.</p><p>Topics that shall be covered are —</p><ol><li>Why VIP?</li><li>VIP: View Controller, Interactor, Presenter</li><li>VIP Cycle and Data flow</li><li>Implementing VIP in iOS</li></ol><h3>Why VIP?</h3><p>To begin with, you may have worked with various system architectures such as MVC, MVVM, ReactiveCocoa, or VIPER which have been “good” and did a great job until recently. These architectures have been helpful in building and publishing various apps. However, they have not been “good” in efficiently managing the problems of scalability and maintenance.</p><p>This is due to the underlying issues in the design and data flow patterns of these architectures that make them challenging and nonreliable often leading to <strong>Massive View Controller</strong>. Further, there may be bugs and difficulties in adding new features which makes the use of these architectures more cumbersome.</p><p>Clean VIP Architecture is what offers a solution to the above-mentioned problems.</p><h3>VIP: View Controller, Interactor, Presenter</h3><p>VIP is Uncle Bob’s Clean Architecture. It is one of those system architectures that follow clean architecture guidelines about system design, component design, data flow between different system layers, and others. It consists of three core components:</p><ol><li><strong>ViewController</strong>: It is a UIViewController that we encounter frequently with the mere difference that in VIP it has <em>only</em> two responsibilities, namely, getting user inputs and rendering UI. In addition, it also holds a strong reference to Interactor.</li><li><strong>Interactor</strong>: In VIP, Interactor is a concrete class with the functions of making various API calls and maintaining data and business logic. It holds a strong reference to the Presenter.</li><li><strong>Presenter</strong>: The presenter is also a concrete class that holds a weak reference to Controller. It performs the functions of creating and passing data to ViewController via ViewModels and validating data and actions for ViewController.</li></ol><p>Hence, the responsibilities in VIP are nicely divided into various classes leading to a clear separation of UI and business logic, unlike other architectures.</p><p>Note that a few other entities like — Models and Routers that facilitate navigations and data maintenance have not been broadly discussed here.</p><h3>VIP Cycle and Data flow</h3><p>The VIP cycle and data flow is as follows—</p><p><em>ViewController → Interactor → Presenter → ViewController</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Hrg_EC0nc9y0QPflT8lYew.jpeg" /><figcaption>A basic representation of VIP Cycle and data flow</figcaption></figure><ol><li>ViewController takes user inputs and passes them to Interactor in form of requests.</li><li>Interactor processes these requests (validates and executes them) and passes the response to the Presenter</li><li>Presenter processes these responses (validates and creates ViewModels) and passes them to ViewController to update/render UI.</li></ol><p>From above, it is clear that the data flow in VIP is <em>uni-directional</em>, from View -&gt; Interactor -&gt; Presenter -&gt; View. This way VIP tackles certain problems that arise in bi-directional data flow architectures like MVC, MVVM, and others.</p><h3>VIP in iOS: Implementation</h3><p>Now comes the final step of implementing VIP in an iOS Project.</p><p>For simplicity, the example is restricted to only one view, which displays a list of Movies that have an imdbRating &gt; 8.0 . This is achieved via a UITableView and a set of prefetched movie data stored in a JSON file in the App bundle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*mnTylDJgDsp_61K8IKtNAw.png" /><figcaption>A view of the final app which displays a list of movies</figcaption></figure><h4>Models — Movie.swift</h4><p>In order to display the above data, we will create Movie , a model that will map data for each movie.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/625596210f53119d8973c989db155d3b/href">https://medium.com/media/625596210f53119d8973c989db155d3b/href</a></iframe><h4>Worker — FileReader.swift</h4><p>This is a Worker class that reads data from the static JSON file saved in the App bundle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d53a396d4938c67ccebc2db92265ffc/href">https://medium.com/media/8d53a396d4938c67ccebc2db92265ffc/href</a></iframe><p>FileReader is a Worker that has a static method getMovies(:)to read data from JSON files and send Result in a callback .</p><h4>ViewController — MoviesListController.swift</h4><p>This is a UIViewController class that controls the UI of the App.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfeb002dd6f77d5b62744edc04dbe083/href">https://medium.com/media/bfeb002dd6f77d5b62744edc04dbe083/href</a></iframe><p>Notice that the controller in the above code holds an optional reference of the interactor , which is used to pass user and data requests from the controller to interactor as is evident from the usage of the method viewWillAppear(:) .</p><p>Besides, MoviesListController also has a render(props:) which is the only method responsible for updating the view as is suggested by the theory. This helps in debugging and maintaining update logics for the view.</p><h4>Interactor —MoviesListInteractor.swift</h4><p>The following snippet shows the interactor performing its core responsibilities — getMovies(:) to get data and processMovies(:) to implement business logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc53f586391a7c170330f7948d53e0dc/href">https://medium.com/media/cc53f586391a7c170330f7948d53e0dc/href</a></iframe><p>Here, interactor fetches data for movies , processes it and then triggers an update in the presenter . Hence, passing response from interactor -&gt; presenter</p><h4>Presenter — MoviesListPresenter.swift</h4><p>This section shows the presenter , performing its core responsibility— updating controller with the new data passed to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fe700326b453c75763660aee5fdd464/href">https://medium.com/media/2fe700326b453c75763660aee5fdd464/href</a></iframe><p>It is worth noting how in the method updateView(:) , presenter reads the current state of controllers viewProps and updates only the required data and then triggers the render(:) method that would start the view update. So, passing data from presenter -&gt; view . With this, the VIP cycle which is a uni-directional data flow is completed.</p><h4>Router — Router.swift</h4><p>In VIP, Router is a class facilitating navigation from one view to another. Generally, each view has its own Router but, it is not always necessary as there can be a global Router class that may be divided into various sub-routers whilst maintaining the navigation stack. In the example below, a global Router is created that has its own navigationController .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abfca97f59472c17c87c0ffdec7f0cd7/href">https://medium.com/media/abfca97f59472c17c87c0ffdec7f0cd7/href</a></iframe><p>Observe how the method showMoviesListView() is used to show the Movies list view. This method instantiates the controller, presenter, interactor and passes the reference of one entity to another. This is a very apt representation of the VIP cycle.</p><p>Once all the relations are established, the view is pushed onto the navigation stack which brings us to the end of VIP implementation.</p><p>The only thing left now is to call the startNavigation() to start navigating and presenting views. This can be done either in AppDelegate or SceneDelegate classes. Based on my deploymentTarget i.e. iOS 14.2, I have done that in SceneDelegate .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e422ac98535842222c2699725026225a/href">https://medium.com/media/e422ac98535842222c2699725026225a/href</a></iframe><p>This brings us to the end of the article. All that is left now is to run the App.</p><p>Hope that now you can try and create your own iOS Apps that follow the Clean VIP Architecture and play around with your code in this amazing way whilst noticing the immense scope of VIP.</p><p>If you want the complete source code of the above example, visit the Github repository given below—</p><p><a href="https://github.com/ayusinghi96/VIP">ayusinghi96/VIP</a></p><p>See you soon! Until then,<br>Happy Coding!💻📱</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7922b7da7c8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Lazy” keyword — Swift 5 (iOS)]]></title>
            <link>https://ayusinghi96.medium.com/lazy-keyword-swift-5-ios-eae3dde18a80?source=rss-64534c9a74a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/eae3dde18a80</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios-developer]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-5]]></category>
            <dc:creator><![CDATA[Ayush Singhi]]></dc:creator>
            <pubDate>Sun, 25 Oct 2020 19:56:15 GMT</pubDate>
            <atom:updated>2020-10-25T19:56:15.697Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Lazy” keyword — Swift 5 (iOS)</h3><h4>What is lazy? When to use it? Is it safe?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkFFzvJ9FB9fMlDYNCWqGA.png" /><figcaption>Source — Self😎</figcaption></figure><p>Hello, there!</p><p>Many of you must have seen a <strong><em>lazy</em></strong> keyword in your codebase or may have used it, but what does it mean? What does it do? Is it always safe to do things lazily? Let’s see.</p><p><em>Lazy</em> allows you to do quite a few things—</p><ol><li>Instantiate a code entity — class, struct, etc. without giving initial values to some or all of its members at the time of instantiation.</li><li>Suspend any task until needed.</li><li>Store the computed values and prevent re-computations.</li></ol><h3>Declaring lazy</h3><p>A member can be declared lazy by simply adding a lazy keyword to its signature. A lazy member should always be declared as a var. Apple says —</p><blockquote>You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes.</blockquote><p>And since all constants must have a value at the end of initialization, it is necessary that lazy properties be declared as a var.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*4o2YEQse4wVj4TzHoc9GdA.png" /><figcaption><strong>fullName — </strong>a <strong>lazy </strong>member declared as <strong>var</strong></figcaption></figure><p>Let us now consider an example to understand what is meant by not having a value at the time of instantiation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdFthSU90reaFsqNX5bm0Q.png" /><figcaption>A User class with a simple <strong>lazy </strong>property to simulate a heavy computational task (inefficient)</figcaption></figure><p>In the above example, we have a class <strong>User</strong> with few data members and an initializer <em>init(::)</em>. When we try to create user1 the system gives an error that the property fullName has <em>no value. </em>While at the same time another property heavyComputation is declared as lazy and it does not result in any kind of an error.</p><p>So, it is clear that by declaring properties lazy we can avoid the initialization constraints. This leads us to the other aspect of lazy— Suspension of a task.</p><h3>Suspend task</h3><p>Another good reason to use lazy is to make initialization faster by suspending tasks at the time of initialization. In other words, as devs, we want to be able to instantiate our entity as quickly as possible. So, any heavy-duty task or computations that can be avoided, <em>must</em> be avoided until they are actually needed. Let’s take a look at a few examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3onhSx9FpXvHTEQMT2riw.png" /><figcaption>All the heavy computation is done at the time of initialization</figcaption></figure><p>As is evident from the above example, all the computations are done at the time of initialization. This happens because heavyComputation is declared as a let constant which needs to have a concrete value at the end of initialization. Therefore, it is computed at the same time. But this is not always desirable.</p><p>As we already know at the time of initialization it is <em>not</em> necessary to have a value assigned to alazy property, we can declare heavyComputation as lazy to get the desired result of suspending a task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uz_But_dR3hZDIriRlI_5w.png" /><figcaption>No computations are performed and the <strong>user </strong>is initialized</figcaption></figure><p>It is clear from the above example that unlike beforeheavyComputation is not evaluated at the time of initialization because heavyComputation is now a lazy variable. In fact a value for heavyComputation will not be calculated until the first time it is accessed.</p><h3>Avoid re-computations</h3><p>Based on what we have seen till now one may argue that the above behavior— non-compulsion of values, suspending the task can be easily emulated by using a computed property. This is where we are headed next. This shall become clear from the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YH9YHkq1QFZtHHlkXrA10w.png" /><figcaption><strong>heavyComputation </strong>is a computed property</figcaption></figure><p>It is evident from this example, that computed property can also suspend a task.</p><p>But does this mean that computed property and lazy are similar? No! At first, they may seem similar but they have a very basic difference which makes lazy all the more useful and interesting.</p><p>Let’s try to access our computed property multiple times and see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNRA8-gHK-mRfxJmeIb9vA.png" /><figcaption>Calling the property <strong>heavyComputation </strong>2 times</figcaption></figure><p>What we find above is that when we access the computed property — heavyComputation multiple times, it is actually computed each time it is accessed (<em>here twice</em>).</p><p>Let’s see what happens when we make heavyComputation a lazy property and try to access it as we did above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAMWuExqwgxrZoqmhBAZGQ.png" /><figcaption>A <strong>lazy </strong>property <strong>heavyComputation </strong>is accessed 2 times</figcaption></figure><p>Interestingly, this time the property is computed only <strong><em>once. </em></strong>This means that after the value is computed the first time, it is being saved for future use and is not actually being computed repeatedly unlike the case with <em>computed property.</em></p><p>Hence, on the basis of the above examples, we can easily establish that lazy properties store values and are not computed each time they are accessed. Thus, saving an ample amount of processing power and time.</p><h3>When not to use <em>lazy</em></h3><p>Having understood the working of lazy, it is now imperative that we understand its usage and be cautious while using it.</p><p>Here is the catch, since lazy is calculated only once we cannot use it to compute values that depend on other variables whose values change more frequently. This is because we may end up with the wrong value in the lazy variable if any of the depending values change after its first computation.</p><p>Additionally, lazy is not thread-safe. This means we may end up with different values for the same variable when accessed on different threads. Apple says —</p><blockquote>If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there’s no guarantee that the property will be initialized only once.</blockquote><p>This shows that too much use of lazy may actually give irregular and wrong results. But having said these, there are still times and places where we may want to do things <em>lazily. </em>Since<em> </em>UI always renders on the <em>main </em>thread this makes it a good potential candidate for lazy loading, however, we need to be very careful while doing that. Also, huge computation or builders can be carried out lazily.</p><p>This brings us to the end of this article.</p><p>Thank you for following along. I hope you enjoyed reading it and found it informative. Do share your views about what do you think are the best/worst places to use lazy.</p><p>Happy Coding 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eae3dde18a80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Final” keyword — Swift 5 (iOS)]]></title>
            <link>https://ayusinghi96.medium.com/final-keyword-swift-5-ios-4b3a31717feb?source=rss-64534c9a74a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b3a31717feb</guid>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[performance-enhancement]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ayush Singhi]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 09:26:17 GMT</pubDate>
            <atom:updated>2020-09-26T09:26:17.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Final” keyword — Swift 5 (iOS)</h3><h4>Understanding the Final keyword and decoding the mystery.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Osz5fCJ3R42eueT4IMJsoQ.jpeg" /><figcaption>Source: <a href="https://unsplash.com/@johnschno">https://unsplash.com/@johnschno</a> | Edited: Self</figcaption></figure><p>Okay! Let’s get right at it! For all of us, iOS developers, there comes a time when we encounter <strong><em>Final</em> </strong>in the code. At that time we ask ourselves what does it do? Where to use it? How to use it? When not to use it? And many other questions start popping up in our heads.</p><p>Here, I will try to answer these questions, and hopefully, decode the mystery of final by the end.</p><h4>Implications of using final</h4><ol><li>It prevents <strong><em>overriding</em></strong> and <strong><em>inheritance</em></strong>.</li><li>It <strong><em>increases</em></strong> the runtime performance of the code.</li></ol><p>But what does this mean??? Let’s see!</p><h3>Prevent Inheritance and Overriding</h3><p>Swift like most other object-oriented languages allows a class to inherit from another class and override methods and properties declared in its superclass.</p><p>However, this is not always desirable and ideal. There are many cases where we do not want anyone or any other part of the code to change the implementation of the class — such a class is to be used the way it is and any change is undesirable.</p><p>In such cases, declaring the class as final will prevent it from being subclassed and thus, will prevent member overriding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vmg5NM3N1iOj_zOm_ebuWA.png" /><figcaption>Compiler error occurs when we try to inherit a <strong>final</strong> class</figcaption></figure><p>Similarly, there are cases when we do not want to change the implementations of a few members of the class. In that case, we do not want to override these few members. The way to do so is to declare themfinal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*iW_JppfSzsXnxZ8moviFqg.png" /><figcaption>A <strong>User</strong> class. We want to control the behavior of generateKey() and getChars(:). So, it is declared final to restrict any changes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wuePLbCVPmtOogvbfEgvoQ.png" /><figcaption>A <strong>Consumer</strong> class inherited from the <strong>User</strong> class. As shown a compile-time error occurs when we try to override a final member.</figcaption></figure><p><em>Note — Please ignore edge case handling in User class member functions.</em></p><h3>Enhance Runtime Performance</h3><p>Saving time and avoiding any compiler computation at runtime makes one’s program <strong>efficient</strong> and <strong>fast</strong>. This is what makes finalmore interesting and useful for any programmer like me.</p><p>Swift being an OOP language allows defining class and inheritance. This means there can be classes and subclasses and subclasses may/may not override properties and methods of the base class.</p><p>However, when we look at this from the system’s point of view, every time a class member is referred (no matter from the subclass or the base class), the system must perform the following computations at runtime —</p><ol><li>Check if the class is inherited anywhere in the code or is itself a subclass.</li><li>Check if any of the class members are overridden and the number of times. And what possible implementations are available for the referenced <em>member</em>.</li><li>Get the correct implementation out of the multiple overrides.</li><li>Indirectly call the correct implementation from a pool of implementations.</li></ol><p>These computations increase the <em>expressivity</em> of the language but add to the runtime overhead as they require more <strong><em>time</em></strong> and <strong><em>power </em></strong>per call. This <strong><em>decreases</em></strong> the overall efficiency of the code.</p><p>This entire chain of events of indirectly accessing the referenced member is termed as <strong>Dynamic Dispatch </strong>by Apple. But is it necessary to go through Dynamic Dispatch all the time — NO! The question that naturally arises then is how can one get rid of dynamic dispatch? How to write efficient code?</p><p>The answer is final . When we declare a member final, it not only specifies that it cannot be inherited/overridden but it also notifies the system that — Hey! No other similar entity exists. This ensures that the system need not worry and directly implement the one defined — and this happens at Compile time. Thus, removing the runtime overhead. This is called direct access or <strong>Static Dispatch</strong> — which happens at compile time.</p><p>This means by merely adding the word final, we can shift the entire processing from <strong><em>runtime to compile time. </em></strong>Hence, increasing the runtime efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTdIkuECNHRpA6Aeh6MY7g.png" /><figcaption>A class <strong>User</strong> is defined and is instantiated to create an object, <strong>user</strong>.</figcaption></figure><p>In the above snippet, when User is instantiated, Dynamic dispatched calls are sent —</p><ol><li>to variables — firstName, secondName.</li><li>to methods — init(:), getChars(:), generateKey(:).</li></ol><p>Also, in the above snippet, whenever user is accessed, it is done via Dynamic dispatched calls.</p><p>Here, even though a single User class exists, still Dynamic Dispatch is compulsorily used. This is because the system has no knowledge if a subclass of User exists, or if any member is overridden anywhere. The system can gather this information either by looking up for them (which is dynamic dispatch) or if we explicitly notify it of their non-existence (which is handled by final ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*GgGVboZinJq-Yrpzb51DJg.png" /><figcaption>A class <strong>User</strong> is defined and is instantiated to create an object, <strong>user</strong>.</figcaption></figure><p>So to sum it up — The above snippet shows a general use-case.</p><ol><li>Here the members are declared final to prevent overriding them.</li><li>Declaring them final eliminates runtime overheads and implements a Static Dispatch.</li></ol><p>This is all for now! Thank you for reading. Hope you found it informational.<br>Happy Coding 💻🖥</p><p>Here are some references to let you explore more about the topic —</p><ol><li>Apple blog — <a href="https://developer.apple.com/swift/blog/?id=27">https://developer.apple.com/swift/blog/?id=27</a></li><li>Different dispatches in Swift — <a href="https://heartbeat.fritz.ai/understanding-method-dispatch-in-swift-684801e718bc">https://heartbeat.fritz.ai/understanding-method-dispatch-in-swift-684801e718bc</a></li><li>Swift documentation on final — <a href="https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html">https://docs.swift.org/swift-book/LanguageGuide/Inheritance.html</a> #Preventing Overrides.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b3a31717feb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access Control — Swift 5 (iOS)]]></title>
            <link>https://ayusinghi96.medium.com/access-control-swift-5-ios-130d4f9f81d2?source=rss-64534c9a74a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/130d4f9f81d2</guid>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ayush Singhi]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 09:33:39 GMT</pubDate>
            <atom:updated>2020-09-20T09:33:39.805Z</atom:updated>
            <content:encoded><![CDATA[<h3>Access Control — Swift 5 (iOS)</h3><h4>A way to handle the restrictions on your code.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqWhepr8R-f-lxg-QpX19A.jpeg" /><figcaption>Source: <a href="https://unsplash.com/@tma">https://unsplash.com/@tma</a> | Edited: Self</figcaption></figure><p><strong><em>Access Control</em></strong> enables you to restrict access to parts of your code — functions, class, enumerations, and declarations from other parts of your code. Protecting the code and restricting access to various sections can be very crucial in writing a robust and separated code for your projects. Apple says —</p><blockquote><em>Access control</em> restricts access to parts of your code from code in other source files and modules. This feature enables you to hide the implementation details of your code, and to specify a preferred interface through which that code can be accessed and used.</blockquote><p>Controlling access comes in handier, even more, when writing your <strong><em>Framework</em></strong><em> </em>or <strong><em>Cocoapod</em></strong><em> </em>or <strong><em>swift package</em></strong><em>. </em>Restricting access to various sections of your code using different access specifiers lets you control what the user can — use, modify, inherit, etc. Since you wouldn’t want the user to change parts or logic of your code, so you want to restrict what areas the user can access.</p><p>So to control access Swift 5 provides five access specifiers — open, public, internal, fileprivate, private</p><h3>1. open — least restricted</h3><ul><li>It provides <strong><em>unrestricted access</em></strong> to any code entity — class, enumeration, struct, etc. outside of the parent module.</li><li>It allows <strong><em>inheriting</em></strong> classes outside of the parent modules.</li><li>It allows subclasses to <strong><em>use and</em></strong> <strong><em>override</em></strong> class members, outside the parent module.</li></ul><p><strong>Example</strong> — We can subclass <strong>UIKit</strong> classes outside the module because they are declared openin UIKit by Apple. Also once inherited accessible members can then be overridden from outside the parent module — UIKit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msfceIB4CxNbWFeI6zeP7g.png" /></figure><h3>2. public — some restriction</h3><ul><li>Similar to open it <strong><em>allows access</em></strong> to any code entity outside of the parent module.</li><li>but <strong><em>does not </em></strong>allow <strong>subclassing</strong> or <strong>overriding</strong> any of the members outside the containing module.</li></ul><p>Example — Struct IndexPath is declared public by Apple and it accessible outside its parent module Foundation. <br>But you <strong><em>cannot </em></strong>modify or override any of its implementations outside of Foundation module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebKZ1ShY9xvaH0a8jUfJHA.png" /><figcaption>IndexPath declared <strong>Public </strong>in Foundation module</figcaption></figure><h3>3. internal — default access specifier</h3><ul><li>internal is the <strong><em>default</em></strong> access specifier associated with any code entity.</li><li>code entities — class, enums, etc., to be <strong><em>accessible</em></strong> to code only within the <strong><em>same</em></strong> module.</li><li>code entities from other modules <strong><em>cannot</em></strong> access or use the properties declared as internal.</li></ul><h3>4. fileprivate — less accessible</h3><ul><li>fileprivate allows a code entity to be accessible to all other entities declared <strong><em>only</em></strong> within the same file, and does <strong><em>not</em></strong> allow any access outside the file.</li></ul><p>Example — Below we try to access a variablestate declared in a struct Switch from a class CustomSwitch — a separate entity. When the variable state is declared private then we see an error because the class does not have access to the variable, but when the same variable is declared as fileprivate no error is shown because now variable state can be accessed from any member of the same file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RF-AZOVcss6ojai_diN0EQ.png" /></figure><h3>5. private — least accessible</h3><ul><li>Only the members within the same enclosing type are allowed to access the code marked private.</li><li>Extension of the same Type can access private members if declared in the same file.</li><li>No other entity can access private members in any case from anywhere.</li><li>they are best for hiding code and protecting access to sensitive code blocks.</li></ul><p>Example — An error occurs because a private member — name is not accessible from any entities declared outside its parent’s declaration — Swtich is not related to CustomSwitch and declared separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEDrjh8_PDgHhhDa6f2y3w.png" /></figure><h3>Guiding Force</h3><p>The Access control model is based on structural components like — modules, source files, and other code entities. <br>It is governed by a simple idea — no one can have access to something more restricted than there access levels. Apple says —</p><blockquote>Access levels in Swift follow an overall guiding principle: <em>No entity can be defined in terms of another entity that has a lower (more restrictive) access level.</em></blockquote><p>Which basically means <strong>A </strong>cannot be defined using <strong>B </strong>if B is more restricted than A.</p><h3>Declarations of access specifiers</h3><p>Contol access specifiers can be specified for all most all declarable code entities — class, struct, enumeration, variable, function, constant, typealias, etc.</p><p>The following are a few examples —</p><pre>// <strong><em>open</em></strong><br>open class Switch: UISwitch<br>{<br>  open func toggleSate(to: State) { //TODO: Implemention needed }<br>}</pre><pre>// <strong><em>public<br></em></strong>public class Switch: UISwitch<br>{ <br>  var state: State</pre><pre>public func toggleSate(to: State) {<br>    self.state = state<br>  }<br>}</pre><pre>// <strong><em>internal- by default<br></em></strong>enum Size: String<br>{<br>  case small<br>  case medium <br>  case large <br>}</pre><pre>// explicit <br>internal func changeSize(to: Size)<br>{<br>  ...<br>}</pre><pre>// <strong><em>fileprivate<br></em></strong>public class Switch: UISwitch<br>{<br>  fileprivate typealias Color = UIColor<br>  fileprivate var state: State</pre><pre>fileprivate func toggleSate(to: State) {<br>    self.state = state<br>  }<br>}</pre><pre>// <strong><em>private<br></em></strong>class Switch: UISwitch<br>{<br>  private typealias Color = UIColor<br>  private var state: State<br>}</pre><h3>Access levels and their ordering</h3><p>The ordering of different access controls based on their restriction levels can now be drawn and it will look something like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*eCcOCMaUgmljxL8NeqrK3g.png" /><figcaption>Relative levels of access controls and their level of restrictions</figcaption></figure><ul><li>open is the <em>least</em> restricted access level.</li><li>private is the <em>most</em> restricted access level</li></ul><p>So, to sum up, five access specifiers —</p><ul><li>open — enables a class to be subclassed, and a function or property to be overridden, outside of its module.</li><li>public — reveals a code entity outside of its module.</li><li>internal — default access level, and makes a declaration visible within its parent module.</li><li>fileprivate — makes a declaration visible only within its declaration file.</li><li>private — makes an entity visible only within the same enclosing type.</li></ul><p>My advice would be to start with the most restricted state and then increase accessibility one step at a time. This helps to keep the code robust and maintain the right accesses at the right places.</p><p>I have tried to cover all important points about Access Control, but we are only humans and I may have missed a few nuances here and there. So I would recommend the readers to consider this writeup as a starting point for your understanding and highly recommend you to go through the official documentation of Swift 5, which may now be more relateable after reading this writeup—</p><p><a href="https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html">Access Control - The Swift Programming Language (Swift 5.7)</a></p><p>That&#39;s all from my side! Happy Coding!!</p><h4>Thank you for reading!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=130d4f9f81d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Draw custom shapes with UIBezierPath — iOS]]></title>
            <link>https://ayusinghi96.medium.com/draw-custom-shapes-and-views-with-uiberzierpath-ios-1737f5cb975?source=rss-64534c9a74a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1737f5cb975</guid>
            <category><![CDATA[shapes]]></category>
            <category><![CDATA[uibezierpath]]></category>
            <category><![CDATA[custom-views]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ayush Singhi]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 16:35:33 GMT</pubDate>
            <atom:updated>2020-06-04T12:19:50.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>Draw custom shapes with UIBezierPath — iOS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQUdPASJ4bbhIjb_vpgrBQ.jpeg" /><figcaption>Source — Pintrest.com</figcaption></figure><p>Today we will try to draw custom shapes and views and try to find out more about drawings in iOS (Swift) and how that can be done through CODE.</p><p>For all the frontend developers, one of the most important parts of the development process is the implementation of User Interface. We can create a simple UI with a combination of pre-made graphics and in-built views in the Interface Builder, but this is not enough, there are often cases when devs need to draw custom shaped views programmatically to meet UI requirements, and if we are not able to draw those, it creates a problem.</p><p>This is where UIBezierPath comes in, it’s Apple’s way of helping devs draw on-screen programmatically. It may seem complex at first but it is quite simple to draw custom shapes.</p><p>To make it more familiar, we will draw a custom shaped view and define it in such a way that we can use it like any inbuilt UI element.</p><p>In this write-up we will touch upon the following topics:</p><ol><li><em>Analysis of Custom View</em></li><li><em>UIBezierPath class</em></li><li><em>Drawing view programmatically</em></li><li><em>Use it in your storyboard/code</em></li></ol><p>To begin with, the aim will be to make a custom Card View that will have rounded corners and a button slot in the bottom-center</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*4Tqn9dhF9TZCSIO9SmCWmQ.png" /><figcaption>Final Card View with a button in the custom button slot and rounded corners</figcaption></figure><p>Note that here we are also going to draw round edges programmatically, which can be normally done using cornerRadius property of CAShapeLayer for almost any view. We do this to make concepts clearer by working on common properties, which will be interesting and will give a peek into how Apple might be doing things under the hood!</p><p>When drawing custom views, it is always beneficial to first analyze and divide it into sections that we can easily draw as individual components and later merge them to create a complete view. Once this is done only then should we dive into coding the view. So we will do the same for our custom Card View.</p><h3>Analyzing custom view</h3><p>Before analyzing the view it is important that we understand how the views are drawn on the screen. Consider the screen to be a Cartesian Plane with origin — (0, 0) at the top-left corner of the screen. Along with —</p><ol><li>Positive X-axis is along the width of the screen in the right direction</li><li>Positive Y-axis is along the height of the screen in the downward direction</li><li>Negative X-axis is along the left direction from the left edge of the screen</li><li>Negative Y-axis is in the upward direction from the top edge of the screen</li></ol><p>So for our analysis, we will consider the same with origin — (0, 0) at the top-left corner of the view frame, and positive x in the right direction along the width of the view and positive y in the downward direction along with the height of the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*kgElIu3O2nKrx9_J67Ns6w.png" /><figcaption>Layout guide for the analysis of the view</figcaption></figure><p><strong>Card View — </strong>Width = N, Height = H</p><p><strong>Button Slot — </strong>Width = N/2, Height = 30</p><p>Thus the rectangular frame of our custom UI is from (0,0) to (N, H)</p><p>Broadly there are three types of sections in the UI drawing</p><p>1. Corner Arcs<br>2. Button Slot Arcs<br>3. Straight Lines</p><p>We will now traverse the view starting from the top-right corner and move in the clockwise direction and investigate various sections and define their origin and length.</p><ol><li><strong>Topline</strong> — from (30, 0) to (N-30, 0)</li><li><strong>Top-right arc</strong> — the origin of arc at (N-30, 30) and radius 30</li><li><strong>Right line </strong>— from (N, 30) to (N, H-30–30)</li><li><strong>Bottom-right arc</strong> — the origin of arc at (N-30, H-30–30) and radius 30</li><li><strong>Bottom-right line </strong>— from (N-30, H-30) to (3N/4, H-30)</li><li><strong>Right-buttonSlot arc</strong> — the origin of arc at (3N/4–30, H-30) and radius 30</li><li><strong>Bottom-buttonSlot line</strong> — from (3N/4 –30, H) to (N/4+30, H)</li><li><strong>Left-buttonSlot arc </strong>— the origin of arc at (N/4+30, H-30) and radius 30</li><li><strong>Bottom-left line</strong> — from (N/4, H-30) to (30, H-30)</li><li><strong>Bottom-left arc </strong>— the origin of arc at (30, H-30–30) and radius 30</li><li><strong>Left line </strong>— from (0, H-30–30) to (0, 30)</li><li><strong>Top-left arc </strong>— the origin of arc at (30, 30) and radius 30</li></ol><p>From the above traversal, it is clear that we can divide our card view into 12 individual sections and then combine them to form the complete view.<br>We can do this by using UIBezierPath, where we can create 12 subpaths and later combine them to form the complete CardView.</p><p>Thus it is time to take a deeper look into UIBezierPath</p><h3>UIBezierPath</h3><p>Before we start to code a pre-requisite that needs to be addressed is UIBezierPath class. Apple says-</p><blockquote>A <a href="https://developer.apple.com/documentation/uikit/uibezierpath"><em>UIBezierPath</em></a> object is a wrapper for a <a href="https://developer.apple.com/documentation/coregraphics/cgpath"><em>CGPathRef</em></a> data type. <em>Paths</em> are vector-based shapes that are built using line and curve segments. You can use line segments to create rectangles and polygons, and you can use curve segments to create arcs, circles, and complex curved shapes.</blockquote><p>This is what we need to create vector-based paths. With this class, we can define custom paths that describe any shape, and use those paths to achieve any custom result we want — simple or complex.</p><p>Two different ways this can be done are —</p><ol><li>Using the shape initializers that let us draw pre-defined shapes — init(rect:), init(ovalIn:) etc</li><li>Using methods to add paths of different geometry as subpaths — addLine(to:), addArc(_:), append(:) etc</li></ol><p><strong>Note — </strong>A bezier path cannot stand on its own, it needs a Core Graphics context where it can be rendered. Context can be passed on in different ways. Here we will pass context by subclassing our custom view from UIView.</p><h3>Time to dive into code</h3><p>Since we now have the required knowledge about the UIBezierPath and have done some fair analysis of our card view we are now ready to dive into code and start defining our new custom view. For this</p><ol><li>Start a new Xcode project.</li><li>Define the custom class CardView that will inherit from UIView in ViewController.swift as in the below code snippet.</li><li>Draw a custom shape for the CardView by overriding the draw(_:) method of the UIView class.</li><li>In the draw(_:) method, create a UIBezierPath and add subpaths to it one by one in the same order as discussed in the above analysis.</li></ol><pre>///<br>/// Custom card view class<br>///<br>class CardView : UIView <br>{<br>  // init the view with a rectangular frame<br>  override init(frame: CGRect)<br>  {<br>    super.init(frame: frame)<br>    backgroundColor = UIColor.clear<br>  }</pre><pre>  // init the view by deserialisation<br>  required init?(coder aDecoder: NSCoder) <br>  {<br>    super.init(coder: aDecoder)<br>    backgroundColor = UIColor.clear<br>  }</pre><pre>  /// override the draw(_:) to draw your own view<br>  ///<br>  /// Default implementation - `rectangular view`<br>  ///<br>  override func draw(_ rect: CGRect) <br>  {<br>    // Card view corner radius<br>    let cardRadius = CGFloat(30)<br>    // Button slot arc radius<br>    let buttonSlotRadius = CGFloat(30)<br>    <br>    // Card view frame dimensions<br>    let viewSize = self.bounds.size<br>    // Effective height of the view<br>    let effectiveViewHeight = viewSize.height - buttonSlotRadius</pre><pre>    // Get a path to define and traverse<br>    let path = UIBezierPath()</pre><pre>    // Shift origin to left corner of top straight line<br>    path.move(to: CGPoint(x: cardRadius, y: 0))<br>    <br>    // top line<br>    path.addLine(to: CGPoint(x: viewSize.width - cardRadius, y: 0))</pre><pre>    // top-right corner arc<br>    path.addArc(<br>      withCenter: CGPoint(<br>        x: viewSize.width - cardRadius,<br>        y: cardRadius<br>      ),<br>      radius: cardRadius,<br>      startAngle: CGFloat(Double.pi * 3 / 2),<br>      endAngle: CGFloat(0),<br>      clockwise: true<br>    )</pre><pre>    // right line<br>    path.addLine(<br>      to: CGPoint(x: viewSize.width, y: effectiveViewHeight)<br>    )<br>    <br>    // bottom-right corner arc<br>    path.addArc(<br>      withCenter: CGPoint(<br>        x: viewSize.width - cardRadius,<br>        y: effectiveViewHeight - cardRadius<br>      ),<br>      radius: cardRadius,<br>      startAngle: CGFloat(0),<br>      endAngle: CGFloat(Double.pi / 2),<br>      clockwise: true<br>    )</pre><pre>    // right half of bottom line<br>    path.addLine(<br>      to: CGPoint(x: viewSize.width / 4 * 3, y: effectiveViewHeight)<br>    )</pre><pre>    // button-slot right arc<br>    path.addArc(<br>      withCenter: CGPoint(<br>        x: viewSize.width / 4 * 3 - buttonSlotRadius,<br>        y: effectiveViewHeight<br>      ),<br>      radius: buttonSlotRadius,<br>      startAngle: CGFloat(0),<br>      endAngle: CGFloat(Double.pi / 2),<br>      clockwise: true<br>    )<br>    <br>    // button-slot line<br>    path.addLine(<br>      to: CGPoint(<br>        x: viewSize.width / 4 + buttonSlotRadius,<br>        y: effectiveViewHeight + buttonSlotRadius<br>      )<br>    )</pre><pre>    // button left arc<br>    path.addArc(<br>      withCenter: CGPoint(<br>        x: viewSize.width / 4 + buttonSlotRadius,<br>        y: effectiveViewHeight<br>      ),<br>      radius: buttonSlotRadius,<br>      startAngle: CGFloat(Double.pi / 2),<br>      endAngle: CGFloat(Double.pi),<br>      clockwise: true<br>    )</pre><pre>    // left half of bottom line<br>    path.addLine(<br>      to: CGPoint(x: cardRadius, y: effectiveViewHeight)<br>    )</pre><pre>    // bottom-left corner arc<br>    path.addArc(<br>      withCenter: CGPoint(<br>        x: cardRadius,<br>        y: effectiveViewHeight - cardRadius<br>      ),<br>      radius: cardRadius,<br>      startAngle: CGFloat(Double.pi / 2),<br>      endAngle: CGFloat(Double.pi),<br>      clockwise: true<br>    )</pre><pre>    // left line<br>    path.addLine(to: CGPoint(x: 0, y: cardRadius))</pre><pre>    // top-left corner arc<br>    path.addArc(<br>      withCenter: CGPoint(x: cardRadius, y: cardRadius),<br>      radius: cardRadius,<br>      startAngle: CGFloat(Double.pi),<br>      endAngle: CGFloat(Double.pi / 2 * 3),<br>      clockwise: true<br>    )<br>    <br>    // close path join to origin<br>    path.close()</pre><pre>    // Set the background color of the view<br>    UIColor.gray.set()<br>    path.fill()<br>  }<br>}</pre><p>In the above code snippet, we have used —</p><ol><li><strong>path.move(to:)</strong> — to move to a new position without drawing on the canvas, takes in — a destination point.</li><li><strong>path.addLine(to:)</strong> — to draw a straight line, takes in — a destination point.</li><li><strong>path.addArc(:)</strong> — to draw an arc, takes in — a <strong>center</strong> for the arc, a <strong>radius</strong> of the arc, a <strong>start angle</strong> in radians(π), an <strong>end angle</strong> in radians(π) and a <strong>direction </strong>of translation(clockwise/anti-clockwise).</li><li><strong>path.close()</strong> — to join the current position to the point of origin and close the figure by drawing a straight line(by default).</li></ol><p>Since now we have successfully defined our custom view class — CardView, it is now time to use it.</p><h3>Using the custom view class</h3><p>To use our custom view, for this we will now move to storyboard —</p><ol><li>Open Main.storyboard</li><li>Remove the default NavigationView and UITableViewController and add a new UIViewController to the canvas.</li><li>Make it the Root view by clicking on the Is initial view controller in Attribute Inspector.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZk04UcA77oTk7L727FH_Q.png" /><figcaption>Added a new UIViewController and set it as the initial view controller</figcaption></figure><p>Once that is done we can start adding UI elements into our UIViewController.</p><ol><li>Start by adding a new view — UIView to the canvas and rename it to cardView</li><li>Set the constraints for the UIView as —</li></ol><pre>1. Safe Area.trailing = cardView.trailing + 16 //Trailing constraint<br>2. cardView.centerY = Safe Area.centerY //Vertical constraint<br>3. cardView.leading = Safe Area.leading + 16 //Leading constraint<br>4. cardView.height = 0.5 × height //Height constraint</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPMVz9TxlDw8IFvHswde2Q.png" /><figcaption>Added auto layout constraints to the UIView</figcaption></figure><p>Now we have our view ready and setup</p><p>In the property inspector on the right panel add the class of our UIView to CardView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*_x_OTLdlYn_i4qv0Okz19w.png" /><figcaption>Set the class of the UIView to CardView</figcaption></figure><p>With this, the storyboard setup is done.</p><p>We are Done! And that is all we had to do to make our custom view show on the screen. Now run your app and see our custom view. Similar to this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*dvqX7GfmB7z2Oa5DIM8reA.png" /></figure><h4>Adding a button to the card view</h4><p>To add a UIButton to the view</p><ol><li>Open Main.storyboard file and add a UIButton to the card view</li><li>Set up the constraints for the button as —</li></ol><pre>1. bottom = Button.bottom + 5      //Bottom constraint<br>2. Button.centerX = centerX        //Horizontal constrain<br>3. Button.width = 0.47 × width     //button width constraint<br>4. height = 50                     //button height constraint</pre><p>Change the button appearance by changing the background color/tint color</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VThW9sXOLFDCqGrpaxEUQ.png" /><figcaption>Add button and its constraints</figcaption></figure><p>To make the corners of the button curve, create an IBOutlet of the button.</p><pre>@IBOutlet private weak var button: UIButton!</pre><p>and add the following line to viewDidLoad() in the ViewController class.</p><pre>button.layer.cornerRadius = button.bounds.height / 2</pre><p>This will curve the corner with a radius equal to half the height.</p><p>Run the app, we will have our desired view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*eQaPEg68Dq0FtmtnaBJ38w.png" /><figcaption>Final custom CardView with a button slot</figcaption></figure><p>So our custom Card View is now ready and it looks awesome! We can use it anywhere we want and play around with it to see what more can be done.</p><p>There is so much more to cover, as this is a huge topic but for the time being thank you for following along, I have tried to keep this as informational as possible.</p><p>Suggestions to look for further study and enhancement-</p><ol><li>Modify the CardView class to contain open properties that can be used to customize appearance such as — cornerRadius, backgroundColor, buttonSlotHeight, buttonPadding etc.</li><li>Add the CardView programmatically into the view hierarchy as a subview.</li><li>For reading references — I found this very informational and helpful — <a href="https://developer.apple.com/library/archive/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html">https://developer.apple.com/library/archive/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1737f5cb975" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>