<?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 Muhammad Ariful Islam on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ariful Islam on Medium]]></description>
        <link>https://medium.com/@arifulislam14?source=rss-d994c18c4b9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A_DsV8mJoUaAFAgPbC24PA.jpeg</url>
            <title>Stories by Muhammad Ariful Islam on Medium</title>
            <link>https://medium.com/@arifulislam14?source=rss-d994c18c4b9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:59:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arifulislam14/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[A Comparative Exploration of Class and Struct in Swift]]></title>
            <link>https://medium.com/@arifulislam14/a-comparative-exploration-of-class-and-struct-in-swift-42e997a13107?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/42e997a13107</guid>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 09:39:57 GMT</pubDate>
            <atom:updated>2023-08-15T17:59:57.728Z</atom:updated>
            <content:encoded><![CDATA[<p>Know the difference, use case of class and struct in swift programming languages</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*FvK5nbuylL35ATQcZ4qy6w.jpeg" /></figure><h3>Overview</h3><p>Class and Structs are complex data types in Swift. You then create an instance of both of them, fill in its values, then you can pass it around in your code. You can also define constants, variables, and functions for them as properties. But there are some differences, use cases &amp; benefits each other and in this article, we will try to figure out those things in the best possible ways.</p><h3>Difference in Type</h3><p>The main difference between Class and Struct is: <strong>Structs are value types &amp; Classes are reference types. </strong>According to the swift official documentation</p><p><em>“</em><strong><em>Reference types</em></strong><em> are not copied when they’re assigned to a variable or constant, or when they’re passed to a function. Rather than a copy, a reference to the same existing instance is used. </em><strong><em>Value type</em></strong><em> is a type whose value is copied when it’s assigned to a variable or constant, or when it’s passed to a function.”</em></p><ul><li><strong>Classes are reference types:</strong> It means that if you assign an instance of the class to a variable, it will hold only the reference to the instance and not the copy. Let&#39;s explain it with an example:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a84a3381eb02efc88d74a9bfe416561d/href">https://medium.com/media/a84a3381eb02efc88d74a9bfe416561d/href</a></iframe><p>Here in Step 01, we create an instance <strong><em>firstPerson</em></strong> of the Person class &amp; assign it to a variable called <strong><em>secondPerson</em></strong>.</p><p>Now <strong><em>secondPerson</em></strong> will only hold the reference to the instance <strong><em>firstPerson</em></strong>. For that, if we change the name property of the <strong><em>secondPerson</em></strong>, it should also affect the name property of the <strong><em>firstPerson</em></strong> also, which is shown in Step 02.</p><p>So<strong> </strong>for<strong> reference</strong> type, a new original instance will be created, and modifying an instance has a <strong>global</strong> effect because the instance is accessible by any reference that points to it.</p><ul><li><strong>Structures are value types:</strong> It means that if you assign an instance of the struct to a variable, it will hold the copy of the instance and not the reference. Let’s explain it with an example</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5507c85ae57ea33ca4df6ea4909c27/href">https://medium.com/media/fd5507c85ae57ea33ca4df6ea4909c27/href</a></iframe><p>Here in Step 01, we create an instance <strong><em>firstFlower</em></strong> of the Flower struct &amp; assign it to a variable called <strong><em>secondFlower</em></strong>.</p><p>Now <strong><em>secondFlower</em></strong> will have a copy of the instance <strong><em>firstFlower</em></strong>. If we change the name property of the <strong><em>secondFlower</em></strong>, it will not affect the name property of the <strong><em>firstFlower</em></strong>, rather it will change it for the own name property which is shown in Step 02.</p><p>For<strong> a value</strong> type, when you assign a new <strong>copy</strong> of data is created and modifying an instance has a <strong>local</strong> effect because the instance is accessible by any reference that points to it.</p><h3>Similarities</h3><p>Both Class and Struct have some things in common</p><ul><li>Define <strong>Property</strong> to store value.</li><li>Define <strong>Methods</strong> to provide functionalities.</li><li>Can <strong>Extend</strong> to add new functionalities.</li><li>Conform to <strong>Protocols </strong>to provide actual implementation of requirements that suit a particular task or piece of functionality.</li><li>Define <strong>Initializer </strong>to specifies an initial value of a data object.</li><li>Define <strong>Subscripts</strong> to provide access to their variables</li></ul><h3>Dissimilarities</h3><p>Only Class has some more capabilities but Struct haven’t</p><ul><li><strong>Inheritance</strong>: Struct methods do not support run-time polymorphism or late binding whether Class methods can. That means Struct methods are <strong>statically dispatched</strong> (just function calls) and Class methods are <strong>dynamically dispatched</strong>.</li></ul><p>Structs are stored on stack memory and take a fixed amount of space if we assigned it to a subclass that had additional data but it hasn’t any room to store the additional data.</p><p>On the other hand, references are typically stored on a heap with a pointer to the object stored on a stack (pointers take the same amount of memory no matter what type they point to).</p><ul><li><strong>Typecasting</strong>: The class has typecasting capabilities to check and interpret the type of a class instance at runtime which is not considerable for Struct.</li><li><strong>De-initializer</strong>: Struct is destroyed when whatever owns it no longer exists. So, if we create a Struct inside a method and the method ends, the Struct is destroyed.</li></ul><p>Classes have complex copying behavior so several copies of the Class can exist in various parts of a program. All the copies point to the same underlying data, so it’s now much harder to tell when the actual Class instance is destroyed. ARC manages the reference count of an object and based on that swift call deinit to destroy the object.</p><ul><li><strong>Reference Count:</strong> Struct is passed by copying. Their members may be pointers to reference-types, but the pointer itself is copied. So for value type, don’t need to worry about reference counting. On the other hand for Class, ARC counts the references for any class object.</li></ul><h3>Memory Allocation</h3><p>Struct is allocated in stack memory (static memory) &amp; class is allocated in heap memory(dynamic memory).</p><p>Stack memory allocation is a temporary memory allocation scheme, determined when the program is compiled where the data members are accessible only if the method that contained them is currently running. It allocates or de-allocates the memory automatically as soon as the corresponding method completes its execution. Stack memory is reserved in LIFO order, very fast and simple to keep track of the stack.</p><p>Variables allocated on the heap have their memory allocated at run time. When we create an object, it is always created in heap and referencing info stored in stack memory. Heap elements have no dependency on each other and are always accessed randomly from anywhere or visible to all threads. That’s why heap memory is not safe as the stack which may lead to memory leak if properly not handled.</p><h3>Choosing between class and struct</h3><p>According to Apple its recommended to use Struct by default because its fast, copying in nature, thread safe etc.</p><p>In some broad picture use Struct when</p><ol><li>Comparing instance data is needed by using ==</li><li>Unique copies with an independent state are required</li><li>The data is used in multiple threads</li></ol><p>Use class when</p><ol><li>Comparing instance identity is needed by using ===</li><li>Shared mutable state is required</li><li>Objective-C interoperability is required</li></ol><p>See the <a href="https://developer.apple.com/documentation/swift/choosing-between-structures-and-classes">link</a> for further details.</p><h3>Conclusion</h3><p>Hope you guys got some idea of Class and Struct, their behavior and use cases. Please check the below link for further clarifications</p><ol><li><a href="https://stackoverflow.com/questions/24217586/structure-vs-class-in-swift-language">https://stackoverflow.com/questions/24217586/structure-vs-class-in-swift-language</a></li><li><a href="https://stackoverflow.com/questions/24232799/why-choose-struct-over-class/66802125#66802125">https://stackoverflow.com/questions/24232799/why-choose-struct-over-class/66802125#66802125</a></li><li><a href="https://developer.apple.com/documentation/swift/choosing-between-structures-and-classes">https://developer.apple.com/documentation/swift/choosing-between-structures-and-classes</a></li></ol><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42e997a13107" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use different Firebase environments for different build configurations in iOS]]></title>
            <link>https://medium.com/@arifulislam14/use-different-firebase-environments-for-different-build-configurations-in-ios-adbbeb5196f?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbbeb5196f</guid>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[firebaseanalytics]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 12:58:05 GMT</pubDate>
            <atom:updated>2022-07-16T05:46:13.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Describe how to set different “GoogleService-Info.plist” files for different build variants in an iOS app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVqAwMcUHqUdQF5u5tuqhw.png" /></figure><h3>Overview</h3><p>Firebase is a platform developed by Google which helps you to understand what your users are doing in your app. Firebase integration to an iOS project is very simple, you have to create an application using the firebase console and add a configuration file (GoogleService-Info) to your project. Sometimes you need to configure different GoogleService-Info files depending on different build variants. We will learn how to do this in simple five steps.</p><blockquote><em>This tutorial is written using </em><strong><em>Swift 5, Xcode 13.3</em></strong></blockquote><h3>Configuration</h3><p>Follow the below steps to configure your project.</p><h4><strong>Step 01: Initial setup</strong></h4><ul><li>Create an Xcode project.</li><li>Install Pod for firebase.</li><li>Write <strong>FirebaseApp.configure() </strong>inside your project <em>AppDelegate</em>’s <em>didFinishLaunchingWithOptions()</em><strong> </strong>to initialize firebase for your project.</li><li>I assume you already have different “GoogleService-Info.plist” files for different build configurations. Don’t add them to your project now, we will add them later.</li></ul><h4><strong>Step 02: Create the folder structure</strong></h4><p>Go to your project root directory from finder and create a folder named <strong>Firebase</strong>.<strong> </strong>Inside<strong> </strong>the<strong> Firebase </strong>folder make two subfolders as<strong> Prod </strong>&amp;<strong> Stg</strong>. Each<strong> </strong>subfolder will have a corresponding “GoogleService-Info.plist” file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoFHwUNpKVUtV-wKvGh5EQ.png" /></figure><h4><strong>Step 03: Add folder reference to the project</strong></h4><p>You manually create a folder on the project root directory but this folder is still unknown to your project. You have to link this folder as a reference to your project. Follow the below video to add the folder as a reference folder to your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5SbsIPnw9h-6ktIboWX11Q.gif" /></figure><p>After adding the folder, your project structure should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*xUi_V5YmW-YQsCSh8cqMfw.png" /></figure><h4><strong>Step 04: Add Run Script</strong></h4><p>Add the below code inside a new run script to your project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f955a23348666d5cf7d3a783feccb1f3/href">https://medium.com/media/f955a23348666d5cf7d3a783feccb1f3/href</a></iframe><p>Click on the P<strong>roject &gt; Build phases. </strong>Click on<strong> “+” </strong>to add a <strong>New Run script phase</strong>. Paste the code there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_uawZuPsoReeqZ_JI_5NBA.gif" /></figure><p>Rename the <strong>Run Script</strong> to <strong>Google Analytics Run Script</strong> which will be more appropriate in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KT8ywIyJs-3I4rih4kGUsA.png" /></figure><p>When adding the script, make sure the below options are enabled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88wT0htByLgr5-7hZKQmFQ.png" /></figure><p>Run your project and confirm that your project is running without any error.</p><h4><strong>Step 05: Verify the configuration</strong></h4><p>We will test our implementation for the <strong>Debug</strong> build variant. If you remember, Inside the <strong>shell script </strong>of the <strong>Google Analytics Run Script </strong>we have echoed some information. We will validate our implementation based on them.</p><p>For that, go to XCode, click on <strong>View &gt; Navigator &gt; reports</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSPCKE4HcFNP6bBdykdHIg.png" /></figure><p>Click on the most recent build from the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmCITtEGupRBTllG9tKUkw.png" /></figure><p>Find the <strong>Project Build target</strong>, and<strong> </strong>verify that<strong> Google Analytics Run Script </strong>executes successfully or not. From this section find out that the right <strong>GooleService-info.plist </strong>file is picked or not on runtime depending on the build variant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szJ2P6SWLG5hU1SDlU-VyA.png" /></figure><h3>Conclusion</h3><p>Now you are able to use different Firebase configuration files for your application environments so that data generated by each version does not get mixed with the others. You can find the demo project <a href="https://github.com/arifparvez14/Medium/tree/master/iOS/FirebaseConfig">here</a>. Check out the below articles to know more about this topic.</p><ol><li><a href="https://medium.com/rocket-fuel/using-multiple-firebase-environments-in-ios-12b204cfa6c0">https://medium.com/rocket-fuel/using-multiple-firebase-environments-in-ios-12b204cfa6c0</a></li><li><a href="https://medium.com/@pablosanchezdev/using-different-firebase-environments-in-an-ios-app-35eb0dd36e7c">https://medium.com/@pablosanchezdev/using-different-firebase-environments-in-an-ios-app-35eb0dd36e7c</a></li></ol><p>I guess now you got some idea of how to set different Firebase environments for different build configurations. <strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbbeb5196f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory management in swift (Part -02)]]></title>
            <link>https://blog.devgenius.io/memory-management-in-swift-part-02-b5b5f9fbb12b?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5b5f9fbb12b</guid>
            <category><![CDATA[automatic-reference-count]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[cars]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Wed, 14 Apr 2021 10:06:19 GMT</pubDate>
            <atom:updated>2021-04-23T16:28:48.655Z</atom:updated>
            <content:encoded><![CDATA[<p>Describe how to manage app memory using Automatic reference counting in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_DcKab9hOQSyXNrIgdRkQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jonassvidras">Jonas Svidras</a> via <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Overview</h3><p>In iOS development, ARC(Automatic reference counting) uses to manage app memory. It tracks the initialized references, relationships between our code and automatically releasing them when the instances are no longer needed. But sometimes the clean-up process interrupted due to some reasoning. In this tutorial, we will learn when ARC can’t free up memory in the case of Delegate and Closure and how to resolve it. If you want to learn the basics of memory management, check out my first part of the memory management tutorial <a href="https://levelup.gitconnected.com/arc-memory-management-in-swift-165fd0329f16">here</a>.</p><blockquote><em>This tutorial is written using </em><strong><em>Swift 5, Xcode 12.4.</em></strong></blockquote><h3>Delegate Retain Cycle</h3><p>We often use the delegate to send data between views. Let consider that we are passing data between <strong>FirstVC</strong> and <strong>SecondVC</strong> using the delegate.</p><p>That’s why we declare a protocol named <strong>SendDataDelegate</strong> and connect <strong>FirstVC</strong> and <strong>SecondVC</strong> through it.</p><pre>protocol SendDataDelegate {}</pre><pre>class FirstVC{<br>    var delegate: SendDataDelegate?</pre><pre>    deinit{<br>        print(&quot;Delegate ref removed from FirstVC&quot;)<br>    }<br>}</pre><pre>class SecondVC: SendDataDelegate {<br>    let vc = FirstVC()    <br>    <br>    init() { <br>        vc.delegate = self<br>    }</pre><pre>    deinit{<br>        print(&quot;Delegate ref removed from SecondVC&quot;)<br>    }<br>}</pre><pre>var secondVC: SecondVC? = SecondVC()</pre><p>We trigger the connection between VCs by creating a reference of <strong>SecondVC</strong>. We write the deinit method in every class to indicate when memory released by ARC.</p><p>At this stage, <strong>FirstVC</strong> and <strong>SecondVC</strong> hold a strong reference to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*Tjd6oLfzcTNGbaHXfjySsw.png" /></figure><p>We expect that if we set the <strong>var secondVC: SecondVC?</strong> as <strong>nil</strong>, hopefully, ARC will do the cleanup process by removing unused references. But wait it’s not. Try it out on your code and check the console output, no deinit method actually called.</p><p>Like I said before, the set object value as nil just removed the reference but not destroyed the object as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*ngz3YCHXZ8c4Yu1mZ_u9FA.png" /></figure><p>All you have to do is just make delegate reference as weak. It will create a weak reference from <strong>FirstVC</strong> to <strong>SecondVC</strong> which resolved the memory retain cycle issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*NsEnfJt296BnLaY5Zj8Z2g.png" /></figure><p>Make the changes, run your code and check your console. ARC is able to clean up your memory as you expected.</p><pre>protocol SendDataDelegate: class {}</pre><pre>class FirstVC{<br>    weak var delegate: SendDataDelegate?</pre><pre>    deinit{<br>        print(&quot;Delegate ref removed from FirstVC&quot;)<br>    }<br>}</pre><pre>class SecondVC: SendDataDelegate {<br>    let vc = FirstVC()    <br>    <br>    init() { <br>        vc.delegate = self<br>    }</pre><pre>    deinit{<br>        print(&quot;Delegate ref removed from SecondVC&quot;)<br>    }<br>}</pre><pre>var secondVC: SecondVC? = SecondVC()<br>secondVC = nil</pre><pre><strong>Console Output: </strong></pre><pre>Delegate ref removed from SecondVC<br>Delegate ref removed from FirstVC</pre><h3>Closure Retain Cycle</h3><p>Let&#39;s assume we have a swift class named <strong>Student</strong> with two property <strong>studentClosure</strong> and <strong>name</strong>. <strong>Student</strong> class has a reference of <strong>studentClosure</strong> as it is a property of the class.</p><p>By creating an object of <strong>Student</strong> we create a reference from closure to <strong>Student</strong> class also.</p><pre>class Student {<br>var studentClosure: (() -&gt; ())?<br>var name: String = &quot;Amit&quot;</pre><pre>    init() {<br>        studentClosure = {<br>        print(&quot;\(self.name) is a student&quot;)<br>    }<br>  }</pre><pre>    deinit{<br>        print(&quot;Student gone&quot;)<br>    }<br>}</pre><pre>var studentObj: Student? = Student()<br>studentObj?.studentClosure!()</pre><p>In this scenario, <strong>Student</strong> class and <strong>studentClosure</strong> both have a vice versa strong relationship with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*tPfKQcGhTv1Mcn7htGzdFA.png" /></figure><p>Now if we set the <strong>studentObj</strong> value as nil we hope ARC will free up memory for us by breaking all the relationship. But unfortunately not, setting nil can’t break retain cycle between <strong>Student</strong> class and closure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*SJWanwUMgI9lL00FJVlL-w.png" /></figure><p>We can resolve memory leaks by using the <strong>weak</strong> keyword as following.</p><pre>init() {<br>    studentClosure = { [weak self] in<br>        guard let obj = self else {<br>        return<br>    }</pre><pre>    print(&quot;\(obj.name) the Developer&quot;)<br>  }<br>}</pre><p>Capturing <strong>weak</strong> inside closure becomes an optional type. A <strong>weak</strong> reference can allow setting a reference object as nil. Now ARC can deallocate our memory as we expected and deinit() methods will call.</p><p>Set the value of <strong>studentObj</strong> as <strong>nil</strong> and check your console.</p><pre>import UIKit<br>class Student {<br>    var studentClosure: (() -&gt; ())?<br>    var name: String = &quot;Amit&quot;<br>    <br>    init() {<br>        studentClosure = { [weak self] in<br>            guard let obj = self else {<br>                return<br>            }<br>            <br>            print(&quot;\(obj.name) the Developer&quot;)<br>        }<br>    }<br>    <br>    deinit{<br>        print(&quot;Student gone&quot;)<br>    }<br>}</pre><pre>var studentObj: Student? = Student()<br>studentObj?.studentClosure!()<br>studentObj = nil</pre><pre><strong>Console Output:</strong></pre><pre>Amit the Developer<br>Student gone</pre><p>You can also capture self inside closure as <strong>unowned</strong> but make sure you know before using it.</p><pre>init() {<br>    bobClosure = { [unowned self] in<br>      print(&quot;\(self.name) the Developer&quot;)<br>    }<br>  }</pre><p>I guess now you got some idea about memory management using Swift programming language. You will find a brief discussion of them on<a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html"> Swift’s official documentation</a>.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5b5f9fbb12b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/memory-management-in-swift-part-02-b5b5f9fbb12b">Memory management in swift (Part -02)</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ARC & Memory management in swift]]></title>
            <link>https://levelup.gitconnected.com/arc-memory-management-in-swift-165fd0329f16?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/165fd0329f16</guid>
            <category><![CDATA[cars]]></category>
            <category><![CDATA[automatic-reference-count]]></category>
            <category><![CDATA[swif]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 04:37:08 GMT</pubDate>
            <atom:updated>2021-04-14T10:12:00.872Z</atom:updated>
            <content:encoded><![CDATA[<h3>Memory management in swift (Part -01)</h3><p>Describe how to manage app memory using Automatic Reference Counting in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAVeH4muYbtwXnjShsRvdQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@tanasovich">Valentine Tanasovich</a> via <a href="https://www.pexels.com/@pixabay">Pexels</a></figcaption></figure><h3>Overview</h3><p>When you developing a mobile application memory is a big concern. Unusual memory access can decrease app performance, crash your app unexpectedly. Luckily Swift uses ARC (Automatic Reference Counting) to manage your app memory. Most of the time ARC cleans up memory by itself but sometimes it can’t due to some relationship. In this tutorial, we will learn how to use ARC for freeing up the memory using Swift.</p><blockquote><em>This tutorial is written using </em><strong><em>Swift 5, Xcode 12.1.</em></strong></blockquote><h3>What is ARC?</h3><p>When we create an instance of a class using init(), ARC allocated some chunk of memory for it. When this instance is no longer been used, the deinit() method is called and ARC deallocates the occupied memory for that object.</p><p>But things are not this simple every time. Sometimes deinit() method not execute and ARC can’t free up memory due to some relationship. You may notice that in iOS development sometimes a variable declared using weak or unowned keywords. Those keywords actually tied up the relationship with a variable and a class. We will learn how to handle them in a smart way and free up unused memory.</p><h3>“strong” Reference and Retain Cycle</h3><p>Let&#39;s say we have a simple class <strong>Student</strong> with a property initializer to initialize its property.</p><pre>class Student {<br>    let studentName: String<br>    init(studentName: String) {<br>        self.studentName = studentName<br>        print(&quot;\(studentName) created&quot;)<br>    }</pre><pre><strong>    </strong>deinit {<br>        print(&quot;Deinit student \(studentName)&quot;)<br>    }<br>}</pre><p>The<strong> student</strong> class also has a deinitializer too. The deinit() method will be called when a property of a class is deinitialized from the memory by ARC.</p><p>Now we create a simple variable <strong>student</strong> of <strong>Student </strong>class. The variable will create a strong reference to the <strong>Student</strong> class and the reference count of the Student class will become 0 to 1.</p><pre>var student: Student? = Student(studentName: “John”)</pre><pre><strong>Console output:</strong><br><em>John created</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*fs5X541jLadMlnyONCx2hA.png" /></figure><p>We can remove the reference by setting the <strong>student</strong> variable value as nil. <strong><em>Note</em></strong> <strong><em>that, by setting the variable as nil we are not deleting the variable rather than deleting the reference only.</em></strong></p><pre>student = nil</pre><pre><strong>Console output:<br></strong><em>Deinit student John</em></pre><p>This statement will remove the relationship of <strong>student</strong> variable with the <strong>Student</strong> class, execute deinit() method and the <strong>Student</strong> class reference count become 0 from 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*eF-VE_eLwYVOWtch5YMdCQ.png" /></figure><p>Now assume that we have two different class as <strong>Student</strong> and <strong>Course</strong></p><pre>class Student {<br>    var course: Course?<br>    let studentName: String<br>    init(studentName: String) {<br>        self.studentName = studentName<br>        print(&quot;\(studentName) created&quot;)<br>    }<br><strong>    </strong>deinit {<br>        print(&quot;Deinit student \(studentName)&quot;)<br>    }<br>}</pre><pre>class Course{<br>    var student: Student?<br>    let courseName: String<br>    init(courseName: String) {<br>        self.courseName = courseName<br>        print(&quot;\(courseName) generated&quot;)<br>    }<br>    deinit {<br>        print(&quot;Deinit course \(courseName)&quot;)<br>    }<br>}</pre><p>We Initialize <strong>Student</strong> &amp; <strong>Course</strong> classes as follow</p><pre>var student: Student? = Student(studentName: “John”)<br>var course: Course? = Course(courseName: “CS-190”)</pre><pre><strong>Console output:<br></strong><em>John created<br>CS-190 generated</em></pre><p>Right now both of the classes have a reference count of 1 because we created two individual references for them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*0iLC01zBcwvwU9V07Zk-Sw.png" /></figure><p>When we set values for the <strong>course</strong> and <strong>student</strong> property inside <strong>Student</strong> and <strong>Course</strong> classes respectively, a strong reference is created between them. The reference count of both classes become 2 from 1.</p><pre>student?.course = course<br>course?.student = student</pre><pre><strong>Console output:<br></strong><em>John created<br>CS-190 generated</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*5bJQQ4fi7Z_nnLHQyIp4Lg.png" /></figure><p>But now if we break the strong reference of <strong>student</strong> and <strong>course</strong> variable as setting them nil, the reference count of <strong>Student</strong> &amp; <strong>Course</strong> will not down to 0 from 2 as we expecting. Both of the class have a reference count of 1 😮</p><pre>course = nil<strong><br></strong>student = nil</pre><pre><strong>Console output:<br></strong><em>John created<br>CS-190 generated</em></pre><p>Check your console output. You will not found anything about Deinitialization because your <strong>deinit() </strong>methods not executed. Though the <strong>course</strong> &amp; <strong>student</strong> are explicitly set as nil but the classes holding the reference of each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*C2yG_MwsipyEgVwUD0QDnw.png" /></figure><p>This situation is known as a <strong>memory leak</strong>. ARC cannot free up your memory because both of the classes have a <strong>strong</strong> retained cycle between them.</p><h3>“weak” Reference to avoid Retain Cycle</h3><p>According to the swift Documentation,</p><blockquote>A weak reference does not keep a stronghold on the instance it refers to, it’s possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference to nil when the instance that it refers to is deallocated.</blockquote><p>the <strong>weak</strong> property doesn’t keep a stronghold so if we set a property as <strong>weak </strong>it will not increase the reference count of that associated class. Time to use <strong>weak</strong> reference, set <strong>course </strong>variable inside<strong> Student</strong> as</p><pre>weak var course: Course?</pre><p>it will affect largely on the relationship between the <strong>Student</strong> &amp; <strong>Course</strong> class. Let&#39;s see how it save us from a memory leak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*bBraMVD1OGMHi9WTMBngig.png" /></figure><p>Currently, the <strong>Student </strong>class has two strong references and the <strong>Course </strong>class has one strong, another weak reference. If we set the <strong>course</strong> variable is <strong>nil, </strong>it<strong> </strong>will resolve the <strong>memory leak</strong> 😲 😲</p><p>Yes, the hack behind that is when we set <strong>course</strong> variable as nil, the strong relationship between <strong>Course</strong> &amp; <strong>Student</strong> class is no more (removed automatically because <strong>course</strong> reference is removed).</p><p>But what about the other weak reference? weak reference will set to <strong>nil</strong> by ARC immediately after the course set as <strong>nil</strong>. That’s the power of weak keyword 😃</p><p>Now set the <strong>course </strong>variable<strong> </strong>as <strong>nil</strong> and see your console out.</p><pre>course = nil</pre><pre><strong>Console output:<br></strong>John created<br>CS-190 generated<br>Deinit course CS-190</pre><p><strong>deinit()</strong> method inside the <strong>Course</strong> class gets called. That means ARC successfully removed the <strong>course</strong> variable from memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*lxCq-tjXYf4D6gm3VXpH-A.png" /></figure><p>See no more retain cycle, no more memory leak. Now you can also set the <strong>student</strong> variable as <strong>nil</strong> if that is no longer needed.</p><h3>“unowned” Reference</h3><p><strong>unowned</strong> is another way to minimize reference count. It is similar to <strong>weak</strong> but there is a slight difference between them. A <strong>weak</strong> reference has to be an optional type. That&#39;s why ARC can set nil to a weak reference when the reference is no longer needed.</p><p><strong>unowned </strong>can’t be optional and expected to always have some value. So ARC can’t set an unknown reference value as nil. Please be aware of using unowned by considering the following facts. According to the swift Documentation,</p><blockquote>Use an unowned reference only when you are sure that the reference always refers to an instance that has not been deallocated.</blockquote><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&#39;s see an example related to <strong>unowned. </strong>We have two class <strong>Students</strong> &amp; <strong>University</strong>. The relationship between classes is slightly different than previous classes. A student might or might not have any university but every university must have students. That’s why we declare <strong>student </strong>variable inside <strong>University </strong>class<strong> </strong>as<strong> unowned </strong>which can’t be optional anymore.</p><pre>class Students {<br>    let studentName: String<br>    var university: University?</pre><pre>    init(studentName: String) {<br>        self.studentName = studentName<br>    }<br>    deinit { <br>        print(“\(studentName) is being deinitialized”) }<br>    }</pre><pre>class University {<br>    let universityName: String<br>    unowned let student: Students</pre><pre>    init(universityName: String, student: Students) {<br>        self.universityName = universityName <br>        self.student = student<br>    }</pre><pre>    deinit {<br>        print(“\(universityName) is being deinitialized”) }<br>    }</pre><pre>var student: Students?<br>student = Students(studentName: “John”)<br>student!.university = University(universityName: “ABC”, student: student!)</pre><p>Right now the relationship between the two class is like the following picture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*2FpJXPe83ObLEss92vdtFA.png" /></figure><p>If we want to free up your memory simply set the <strong>student</strong> variable to <strong>nil</strong>.</p><pre>student = nil</pre><pre><strong>Console output:<br></strong>John is being deinitialized<br>ABC is being deinitialized</pre><p>Check your console, ARC successfully removed the reference of the object from memory, Cool 😎 The output of this will look as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*hRfawoDTiaIwMzMIoj89cQ.png" /></figure><p>But wait when <strong>unowned</strong> will cause a problem? Try to access the <strong>student </strong>property of the <strong>University</strong> class as following after setting the <strong>student</strong> object as <strong>nil</strong>.</p><pre>student = nil<br>university.student //Run time error</pre><p>Based on the definition of <strong>unowned</strong>, it must have a non-nil reference to the object. Since the Owner object has been deallocated, it crashes.</p><p>I guess now you got some idea about memory management using Swift programming language. If you want to learn more, check out my second part of the memory management tutorial <a href="https://medium.com/@arifulislam14/memory-management-in-swift-part-02-b5b5f9fbb12b">here</a>. You will find a brief discussion of them on<a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html"> Swift&#39;s official documentation</a>.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165fd0329f16" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/arc-memory-management-in-swift-165fd0329f16">ARC &amp; Memory management in swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pass data using NSNotification in Swift]]></title>
            <link>https://blog.devgenius.io/pass-data-using-nsnotification-in-swift-1ddc3bbd0d6d?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ddc3bbd0d6d</guid>
            <category><![CDATA[storyboard]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[nsnotification]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 03:00:38 GMT</pubDate>
            <atom:updated>2020-07-02T04:38:19.344Z</atom:updated>
            <content:encoded><![CDATA[<p>Describe how to pass data between view controllers using notification patterns in the Swift programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4c9n0ORtLIgpKk_Lot4ow.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@eduardoequis">Eduardo Sánchez</a> via <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Overview</h3><p>In iOS development, it is very common to share data between different views. We can pass data in different ways. In this tutorial, we will learn how to send data from one view controller to another using NSNotification.</p><blockquote><em>This tutorial is written using </em><strong><em>Swift 5, Xcode 11.4, iOS 13 &amp; Storyboard Interface.</em></strong></blockquote><h3>What is Notification?</h3><p>Notification is a way of notifying when sending data from one view to another. You can compare it with sending a letter using the postbox. Sender posted a letter into the postbox for one or more receivers. Postmaster of the receiver&#39;s area is observing for the letters to come. When the postmaster gets the letter, he/she do some specific work (distribute them to the actual receiver).</p><p>Sending data using notification is exactly similar to this process. Notifications are posted from one view controller. One or more view controllers are observing for that notification. When they notify, they do some specific work. Let&#39;s see how all these things are work together</p><h3>Getting started with a simple project</h3><p>I will use a simple single view app for this tutorial. This app will have only two view controllers, “FirstVC” &amp; “SecondVC”. This is the storyboard interface for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyvd3vCTVi8Vqg5KbtXVUw.png" /></figure><p>Here are the view controller classes for “FirstVC” &amp; “SecondVC”. Our intention is to send notification from the “SecondVC” to “FirstVC” that&#39;s why we set labels in the “FirstVC” as following when view load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FljT3f20D1VaPABV-7DkPA.png" /></figure><p>We just set the views and write some initial codes for our project. In this stage, our app seems like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*6SWQU1Fzrlc5P41UGsOwfg.gif" /></figure><p>That’s our project set up and it&#39;s ready to configure, Cool 😎</p><h3>Work with notification</h3><p>Now we will work with notification. First of all, we will declare a unique key. One view controller will send the notification using that key, another view controller will observing the notification associated with that key and do something when notified. Let&#39;s see how everything works together.</p><h4><strong>1. Set a notification key:</strong></h4><p>For identifying every notification uniquely we need a unique notification key. Key can declare as a variable anywhere inside your module but make sure they are in a separate class or outside of other&#39;s class scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JU0xLqZWuxJTpJCbSxYlgA.png" /></figure><p>Here I declare a variable as “notificationKey” inside “FirstVC.Swift” file and outside of the “FirstVC” class. Using this key we will post and observe notification.</p><h4>2. Set an Observer:</h4><p>We wrote a function for observing the notification. Here <strong>self</strong> refers to who is observing the notification. In our case FirstVC. <strong>#Selector </strong>is what action will perform after notifying. In our case, it will execute the “doWhenNotify” function and set the “notificationTxtLbl” text if “FirstVC” successfully observed that notification. Lastly, the <strong>name</strong> is the unique key for the notification “FirstVC” is observing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZden3kdxxfYG3Mj8NOm9w.png" /></figure><h4>3. Post Notification:</h4><p>We will post notification while tapping on the “submitBtnTap” button inside “SecondVC” as following. We pass “SecondVC” reference as an object while posting this notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RQxkVwEqdd8OIHUmigsmw.png" /></figure><p>If you follow everything according and run the project you should see something like this. Notice that “notificationTxtLbl” inside “FirstVC” text changes as we expected. That&#39;s means we successfully communicated using notification, great 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*CnEl3oxhOWMC5A6vmv83LQ.gif" /></figure><p>That’s the way that how two or more view controllers can talk to each other using notification. But something you have to send some information using notification also. Now we will see how we can do that.</p><p>Generally, we use a dictionary to send data using notification. We put information as key-value pair inside the dictionary and add that dictionary as a parameter while posting notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEXcBxJwXHWwElwHGXR0Lg.png" /></figure><p>In our case, we take a dictionary named “info” and put the text field inputs inside it as a key-value pair. Add that dictionary into the post method as a parameter named “userInfo”.</p><p>Now we will use that “userInfo” parameter in “FirstVC” that sends while posting notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeqfVXmjQgm3U9uK6LAdGw.png" /></figure><p>“userInfo” dictionary has two key, “name” &amp; “age”. We safely unwrap those values for keys and set them into “infoLbl”. That’s how we can pass data using notifications. Now you can set your username, age, and pass them from “SecondVC” to “FirstVC” using notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Zm03_5abaFOiCZ2BD90kzQ.gif" /></figure><h3>Deinitialize notification</h3><p>You can deinitialize notification in many ways. It can be done by <strong>deinit</strong> or view controller lifecycle function (<strong>viewDidDisappear</strong> or <strong>viewWillDissapear</strong>) function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBLAkUkdygkbIkMS0t_5mw.png" /></figure><p>Congratulation 🎉 🎉 🎉 I guess now you know how to work with NSNotification in swift. You will find the project <a href="https://github.com/arifparvez14/Medium/tree/master/iOS/PassDataUsingNotification">here</a>. Check the <a href="https://developer.apple.com/documentation/foundation/nsnotification">Apple Documentation</a> for further details.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ddc3bbd0d6d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/pass-data-using-nsnotification-in-swift-1ddc3bbd0d6d">Pass data using NSNotification in Swift</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access Control in Swift]]></title>
            <link>https://levelup.gitconnected.com/access-control-in-swift-98ad5901a358?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ad5901a358</guid>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[access-control]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 03:42:38 GMT</pubDate>
            <atom:updated>2022-06-13T06:02:59.464Z</atom:updated>
            <content:encoded><![CDATA[<p>A brief discussion of different access control in the Swift programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRCAeCdaFtBrRh_j0d_wQA.jpeg" /><figcaption>Image by<a href="https://unsplash.com/@markusspiske"> Markus Spiske</a> via <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Overview</h3><p>According to the swift official documentation</p><p>“<em>Access control 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.</em>”</p><p>Swift 5 has five access control. They are open, public, internal, fileprivate, and private. Those access controls are defined based on the uses in the module and source file. In this tutorial, we will learn what, where, and how to use access control in swift.</p><h3>1. open (less restrictive)</h3><p>Anything defined with open can be accessed within or without the module. open-access level entities can be accessed from anywhere. That means an open variable can access, an open function can override and an open class can be a subclass inside of a module and outside of a module by importing that module.</p><p>An example is the “<strong>UITableViewCell</strong>” class in the UIKit framework. We can subclass any class as a UITableViewCell class by importing the UIKit module. If you see the definition of <strong>“UITableViewCell”</strong>, you will see open access control before the class definition inside the UIKit module. That’s why we can subclass any class as a UITableViewCell class by importing UIKit.</p><pre>@available(iOS 2.0, *)</pre><pre>open class UITableViewCell : UIView, NSCoding, UIGestureRecognizerDelegate { }</pre><h3>2. public (more restrictive than open)</h3><p>Like open access, public entities also can be accessed within or outside of a module. But there is a major difference between open and public.</p><blockquote>public class can’t be subclassed and public method can’t be overridden outside of the defined module. Must have to subclass or override within the module where they defined.</blockquote><p>Check the example below</p><pre>//module 1</pre><pre>open class X{}<br>open func bar(){}</pre><pre>public class Y{}<br>public func foo(){}</pre><pre>//module 2</pre><pre>class A: X{} // success<br>override func bar(){} // success</pre><pre>class B: Y{} //error<br>override func foo(){} // error</pre><h3>3. internal ( module-level access control)</h3><p>“internal” enable to use of entities anywhere inside the defined module. <strong>“internal” is the default access level. </strong>Normally a module is<strong> </strong>a framework or app which can be used as a single unit.</p><p>Inside a target (module) all the entities are by default internal (If explicitly did not define any access control). It’s defined that way that everything inside the module can be accessed by anyone from anywhere within that module.</p><h3>4. fileprivate( file-level access control)</h3><p>fileprivate entities only can be accessible within a swift file. A swift file can have several classes or structures. All the file private entities inside a swift file can be accessed by all of the classes or structures in that file. Without them, any other classes outside of that file can’t access them. It generally hides the implementation from other source files of the module.</p><pre>//**  ViewController.swift **//</pre><pre>class ViewController: UIViewController {<br>    override func viewDidLoad() {<br>    super.viewDidLoad()</pre><pre>    let a = A()<br>    a.x()<br>    a.z() //error</pre><pre><strong>    </strong>let b = B()<br>    b.Y() // error<br>  }<br>}</pre><pre>class A {</pre><pre>fileprivate func x(){<br>    print(&quot;Inside ViewController file&quot;)<br>  }<br>}</pre><pre><br>//**  SecondViewController.swift **//</pre><pre>class B{</pre><pre>fileprivate func Y(){<br>    print(&quot;Outside ViewController file&quot;)<br>  }<br>}</pre><pre>extension A{<br>    fileprivate func Z(){<br>    print(&quot;Outside ViewController file, extension of A&quot;)<br>  }<br>}</pre><h3>5. private( class-level access control)</h3><p>private is the most used and most restricted access control. The private entities can access only within the class (including extension) they declared. It is generally used to hide the internal implementation or functionality outside of a specific class.</p><pre>// **  ViewController.swift **//</pre><pre>class ViewController: UIViewController {<br>    override func viewDidLoad() {<br>    super.viewDidLoad()<br>    x()<br>    let a = A()<br>    a.Y() // error<br>  }<br>}</pre><pre>extension ViewController{<br>    private func x(){<br>    print(&quot;Inside x&quot;)<br>  }<br>}</pre><pre>class A {<br>    private func Y(){<br>    print(&quot;Inside Y&quot;)<br>  }<br>}</pre><h3>Difference between swift access control</h3><p>Now we will see the difference between those access modifier based on different parameters as a tabular form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*1HWcxEIbXOS6zCvL57Wqmg.png" /></figure><p>Congratulation 🎉 🎉 🎉 I guess now you got some idea about access control in the swift programming language. You will find a brief discussion of them on <a href="https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html">swift official documentation</a>.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ad5901a358" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/access-control-in-swift-98ad5901a358">Access Control in Swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enumerations, Tuples, and Generics in Swift]]></title>
            <link>https://levelup.gitconnected.com/enumerations-tuples-generics-in-swift-c3d51cb0f318?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d51cb0f318</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[enumeration]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[tuples]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 12:28:31 GMT</pubDate>
            <atom:updated>2020-07-02T04:35:47.475Z</atom:updated>
            <content:encoded><![CDATA[<p>A brief discussion on how to uses enum, generics, and tuples in the Swift programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ic9Ou8ZXZeiADVCXpOaKIw.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@negativespace">Negative Space</a> via <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><h3>Overview</h3><p>Like other programming languages, Swift also has special features like enum, tuples, and generics. They have different use cases depending upon different conditions. In this tutorial, we will learn</p><p>What, when, and how to use <strong>enumerations</strong>, <strong>tuples, and generics</strong> in Swift? So let’s get started</p><blockquote><em>This tutorial is written using </em><strong><em>Swift 5 and Xcode 11.4.1.</em></strong></blockquote><h3>1. Enumerations</h3><p>According to swift documentation “<em>An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code</em>.”</p><ul><li><strong>Creating an enum: </strong>You can declare an enum like this in swift</li></ul><pre>enum TimePeriod{<br><strong>    </strong>case morning<br>    case noon<br>    case afternoon<br>    case night<br>}</pre><p>Where the name of this enum is “TimePeriod” and it has four cases as “morning”, “noon”, “afternoon” and “night”.</p><p>We also can declare the cases in a single line like this</p><pre>enum TimePeriod{<br>    case morning, noon, afternoon, night<br>}</pre><ul><li><strong>enum type: </strong>When we define an enum itself define a new type in swift. We can define a variable as this type</li></ul><pre>var presentTime = TimePeriod.morning<br>print(presentTime)   // morning</pre><p>“presentTime” variable is “TimePeriod” enum type and its value is “morning”</p><p>Once it defined that “presentTime” is “TimePeriod” type we can set others value of enum using “.” operation</p><pre>presentTime = .noon<br>presentTime = .afternoon<br>presentTime = .night</pre><ul><li><strong>Matching enum value: </strong>Swift switch statement is a simple and straight forward solution for matching the enum value.</li></ul><pre>switch presentTime {</pre><pre>case .morning:<br>    print(&quot;Foggy morning&quot;)<br>case .noon:<br>    print(&quot;Sunny noon&quot;)<br>case .afternoon:<br>    print(&quot;Cloudy afternon&quot;)<br>case .night:<br>    print(&quot;Rainy night&quot;)</pre><pre>}</pre><ul><li><strong>Iterate enum cases: </strong>To iterate enum cases we have to declare enum as<strong> “CaseIterable”</strong>. In our case, we can declare our “TimePeriod” enum like this.</li></ul><pre>enum TimePeriod: CaseIterable{<br>    case morning<br>    case noon<br>    case afternoon<br>    case night<br>}</pre><p>Now we can get all cases and iterate as follow.</p><pre>let numberOfChoices = TimePeriod.allCases.count<br>print(&quot;\(numberOfChoices) timeperiod available&quot;)</pre><pre>for timeperiod in TimePeriod.allCases{<br>    print(timeperiod)<br>}</pre><ul><li><strong>Raw Value: </strong>We can provide value for every enum case. These values are known as Raw Value. It can provide both implicitly and explicitly. Before that, we have to provide the type of raw value after enum name</li></ul><pre>enum Institute: Int{</pre><pre>case school<br>case colleague<br>case university</pre><pre>}</pre><p>enum Institute will have an integer type of raw value for every case. It can be any type in swift. In this case value for school is 0, colleague 1, and university as 2.</p><p>Raw values of every case can be check like this</p><pre>print(Institute.school.rawValue) //0<br>print(Institute.colleague.rawValue) //1<br>print(Institute.university.rawValue) //2</pre><p>If we want we also can provide explicitly raw value for every case anything we want.</p><pre>enum Institute: Int{</pre><pre>case school = 10<br>case colleague = 12<br>case university = 14</pre><pre>}</pre><p>We also can explicitly provide raw value for the first case. In this case, swift will provide raw values for other cases implicitly</p><pre>enum Institute: Int{</pre><pre>case school = 4<br>case colleague<br>case university</pre><pre>}</pre><p>Here raw value for school is explicitly defined as 4. Swift will provide raw value for colleague as 5 and university as 6 implicitly.</p><p>We can search a case from enum using raw value. If any case present with that corresponding raw value swift will return that case name else it will return nil.</p><pre>var instituteType = Institute(rawValue: 9)</pre><pre>if let value = instituteType2 {</pre><pre>print(value) // nil because we haven&#39;t any case with rawvalue 9</pre><pre>}</pre><p>Lastly, we will see an example of string raw value of cases</p><pre>enum MoveDirection : String {</pre><pre>case forward = &quot;you moved forward&quot;<br>    case back = &quot;you moved backwards&quot;<br>    case left <br>    case right = &quot;you moved to the right&quot;</pre><pre>}</pre><p>In case of string raw value type enum if we didn’t provide the raw value of any cases swift will provide the name of cases as raw value implicitly.</p><pre>print(MoveDirection.forward.rawValue) // you moved forward<br>print(MoveDirection.back.rawValue) // you moved backwards<br>print(MoveDirection.left.rawValue) // left<br>print(MoveDirection.right.rawValue) // you moved to the right</pre><ul><li><strong>Associate values with enum cases: </strong>Sometimes we also have to set associate values with enum cases. In this case, we also have to assign those tuple values for cases when we declare a variable as that enum type.</li></ul><pre>//enum area with associate values with cases</pre><pre>enum Area{<br>    case square(Double,Double)<br>    case cube(Double, Double, Double)<br>}</pre><pre>//define a variable &quot;sampleArea&quot; with assign it a value Area.square with associated tuple value (10,15)</pre><pre>var sampleArea = Area.square(10, 15)</pre><p>Here we also can match the enum value using swift statements. This time we have some associate values with every enum case. Those values easily can extract as variable or constant for use inside the switch statements.</p><pre>switch sampleArea {</pre><pre>case .square(let height, let width):<br>    print(&quot;Square of: \(height), \(width).&quot;)<br>case .cube(let height, let width, let length):<br>    print(&quot;Square of: \(height), \(width), \(length)&quot;)</pre><pre>}</pre><p>If all the associated values are constant or variable then we can simply place var or let before the case name</p><pre>switch sampleArea {</pre><pre>case let .square(height, width):<br>    print(&quot;Square of: \(height), \(width).&quot;)<br>case let .cuve(height, width, length):<br>    print(&quot;Square of: \(height), \(width), \(length)&quot;)</pre><pre>}</pre><h3>2. Tuples:</h3><p>Tuple itself is a type in swift which can have multiple types of comma-separated values wrapped in parenthesis. It normally uses to store multiple type data and return them as a function call.</p><ul><li><strong>Creating a tuple: </strong>Declaring a tuple in swift super simple like this</li></ul><pre>var personInfo = (&quot;John&quot;, 24)</pre><p>Here “personInfo” is a tuple type variable holding a string and integer value. Those values of the tuple can be accessed by the “.” operator. 0 for the first element, 1 for the second element, and so on. We also can assign value for every element after declaration.</p><pre>var name = personInfo.0 // John<br>var age = personInfo.1 // 24</pre><pre>personInfo.0 = &quot;John Doe&quot;<br>personInfo.1 = &quot;30&quot;</pre><ul><li><strong>Named elements of tuples: </strong>We also can declare tuple type variable by providing name explicitly for every element inside it.</li></ul><pre>var person = (firstName: &quot;John&quot;, lastName: &quot;Smith&quot;)<br>var firstName = person2.firstName2 // John<br>var lastName = person2.lastName2 // Smith</pre><p>We can also provide names and assign them to a variable this way</p><pre>let httpSuccess = (200, &quot;Data Found&quot;)<br>let (statusCode, statusMessage) = httpSuccess</pre><pre>print(&quot;Status code \(statusCode)&quot;) // Status code 200</pre><pre>print(&quot;Status message \(statusMessage)&quot;) // Status message Data Found&quot;</pre><p>We also can escape assigning values of tuples while decomposing if we didn’t want that value</p><pre>let httpSuccess = (200, &quot;Data Found&quot;)<br>let (statusCode, _) = httpSuccess</pre><pre>print(&quot;Status code \(statusCode)&quot;) // Status code 200</pre><pre>print(&quot;Status message \(statusMessage)&quot;) // Status message Data Found&quot;</pre><ul><li><strong>The tuple is value type: </strong>One of the important things is tuple is a value type. When use assigns one to another it actually creates a copy of that.</li></ul><pre>var area = (w: 0, h: 0)<br>var subArea = area</pre><pre>subArea.w = 3<br>subArea.h = 5</pre><pre>print(area) // (0, 0)<br>print(subArea) // (3, 5)</pre><ul><li><strong>Multiple assignments of values:</strong></li></ul><p>Tuple has multiple assignments of value</p><pre>var (x, y, z) = (1, 2, 3)</pre><ul><li><strong>Swap two value:</strong></li></ul><p>Swapping two value can be done easily using tuples</p><pre>var x= 5 <br>var y= 4 <br>(y, x) = (x, y)</pre><ul><li><strong>Tuple inside another tuple:</strong></li></ul><p>One tuple inside another one can be described like this</p><pre>let person: (String, (string, Int)) = (&quot;John&quot;, (&quot;Dhaka&quot;, 30))<br>print(person.0) // John<br>print(person.1.0) // Dhaka<br>print(person.1.1) // 30</pre><h3>3. Generics:</h3><p>Generics is one of the most powerful features in swift. It helps to write flexible, reusable functions by writing type independent code. We will see some of the applications of the generics here</p><ul><li><strong>Intro to Generics: </strong>Suppose we will write a function that will take two numbers, add them and return. We will write a function and use that like this</li></ul><pre>func addIntNumbers(num1: Int, num2: Int) -&gt; Int{<br>    return num1 + num2<br>}</pre><pre>let result = addIntNumbers(num1: 10, num2: 20) // 30</pre><p>Now if we want to add two double numbers then we have to write another function for adding them as well</p><pre>func addDoubleNumbers(num1: Double, num2: Double) -&gt; Double{<br>    return num1 + num2<br>}</pre><pre>let result2 = addDoubleNumbers(num1: 13.75, num2: 20) // 33.75</pre><p>For a single operation, we have to write two different functions only for the type difference. Other than that everything is identical.</p><p>Generics can work with any type and can rescue us from this kind of situation to write a reusable function. We can define a function with defining the protocol type</p><pre>func addNumbers&lt;T: Numeric&gt;(a: T, b: T) -&gt; T<br>{<br>    return a + b<br>}</pre><p>Here “T” is numeric type so we can pass any numeric type as an argument when calling this function</p><pre>//Int type argument<br>let value = addNumbers(a: 10, b: 20) // 30</pre><pre>//Double type argument<br>let value2 = addNumbers(a: 10.5, b: 20.4) // 30.9</pre><p>This is the most basic and main reason for using generics but surely we can do a lot more things.</p><p>Congratulation 🎉 🎉 🎉 I think now you know a little about enum, tuples, and generics in Swift, how and where to use them. I recommend you to check the official Apple and swift documentation for further reference.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d51cb0f318" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/enumerations-tuples-generics-in-swift-c3d51cb0f318">Enumerations, Tuples, and Generics in Swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collection Types in Swift]]></title>
            <link>https://medium.com/@arifulislam14/collection-types-in-swift-38e634ef2370?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/38e634ef2370</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[dictionary]]></category>
            <category><![CDATA[set]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Sat, 23 May 2020 14:34:42 GMT</pubDate>
            <atom:updated>2020-07-02T04:34:45.694Z</atom:updated>
            <content:encoded><![CDATA[<p>Uses of collection types known as Array, Sets &amp; Dictionary in Swift programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsS7rQDeGQLw8m5qvCbXrg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@designecologist">Designecologist</a> via <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><h3>Overview</h3><p>Swift programming language has three primary collection types to store and perform the operation on the value. They are Array, Set, and Dictionary. In this tutorial, we will learn</p><p>Uses &amp; different operation of <strong>Array</strong>, <strong>Sets</strong> &amp; <strong>Dictionary</strong> data types in Swift? So let&#39;s get started</p><blockquote><em>This tutorial is written using </em><strong><em>Swift 5 &amp; Xcode 11.4.1.</em></strong></blockquote><h3>1. Array</h3><p>The array is the most common and widely used data type in swift. It is an ordered collection of similar types of data. In this section, we will see the different uses of the array with examples</p><ul><li><strong>Declare an Array: </strong>You can declare an empty Int type array like this</li></ul><pre>var simpleArray = [Int]()</pre><p>The array can be any type in swift. We can also declare with some initial values. Swift is a strongly typed language so we don’t have to tell the type when we declare an array but we can also specify the type</p><pre>var simpleArray = [2,3,4,5]<br>var simpleArray: [Int] = [2,3,4,5]</pre><p>You also can declare an array with some repeated values or using one or more arrays</p><pre>var<strong> </strong>simpleArray = Array(repeating: 1, count: 3) //initialize simpleArray with three ones </pre><pre>var simpleArray = arrayOne + arrayTwo //initialize simpleArray with addign arrayOne &amp; arrayTwo</pre><ul><li><strong>Insert elements into an Array: </strong>We can insert an element at the end of the array or in a valid position.</li></ul><pre>simpleArray.append(12) //append element at the end of array<br>simpleArray += [100.0] //append at the end</pre><pre>simpleArray.insert(12, at: 0) //insert element at 0 position. This position value should be n to n-1 if array have n number of elements.</pre><ul><li><strong>Access Elements of Array: </strong>We can access the element of an array using a subscript <em>s</em>yntax, passing the index value into it. Also swift provided a list of methods to get values and check different parameters.</li></ul><pre>simpleArray[2]  //return second element from array<br>simpleArray.count  // return the number of elements in array<br>simpleArray.isEmpty  // return false if array is empty<br>simpleArray.capacity  // return the number of elements in array</pre><pre>simpleArray.first  //get the first element from array<br>simpleArray.last  //get the last elements from array<br>simpleArray.max()  //get the max element from array<br>simpleArray.min()  //get the min element from array</pre><pre>simpleArray.sorted()  // sort the array<br>simpleArray.reversed()  //reverse an array<br>simpleArray.shuffled()  //shuffle the elements of an array</pre><ul><li><strong>Replace elements of Array: </strong>Array<strong> </strong>value<strong> </strong>can set or replace in a specific index or for a range of the index.</li></ul><pre>simpleArray[2] = 1 // replace the value in second index of array</pre><pre>simpleArray[1...3] = [12, 23, 34] // set first to third position value as 12, 23 &amp;34</pre><ul><li><strong>Remove elements from Array: </strong>Array elements<strong> </strong>can remove from different ways &amp; different positions.</li></ul><pre>simpleArray.removeAll() // remove allelement from array<br>simpleArray.removeFirst() // remove first element from array<br>simpleArray.removeLast() // remove last element from array</pre><pre>simpleArray.remove(at: 2) //remove second element from array</pre><pre>simpleArray.removeLast(1) // remove the second element from the end index of array</pre><pre>simpleArray.removeFirst(2) // remove the thirdelement from the start index of the array</pre><ul><li><strong>Iterate</strong> <strong>over</strong> <strong>the</strong> <strong>array: </strong>Every element of an array can be traverse using loop</li></ul><pre>for i in 0..&lt;simpleArray.count{<br>    print(simpleArray[i])<br>}</pre><pre><strong>or<br></strong>for item in simpleArray{<br>    print(item)<br>}</pre><p>If you need the integer index of each item as well as its value, use the enumerated() method to iterate over the array instead</p><pre>for (index, value) in simpleArray.enumerated() {<br>    print(&quot;Item \(index + 1): \(value)&quot;)<br>}</pre><h3>2. Dictionary</h3><p>A dictionary in swift can hold multiple unordered data in key-value pairs. Each value is associated with a unique key and any value from the dictionary can access with the associated key with it.</p><ul><li><strong>Declare a Dictionary: </strong>You can declare an empty dictionary like this</li></ul><pre>var simpleDictionary = [Int: String]() // an empty &quot;simpleDictionary&quot; with Int type key &amp; String type value</pre><p>The key-value pair of a dictionary can be any type in swift. We can also declare with some initial values. Swift is a strongly typed language so we don’t have to tell the type of key-value pair when we declare a dictionary but we can also specify the type</p><pre>var simpleDictionary = [1: &quot;John&quot;, 2: &quot;Doe&quot;]<br>var simpleDictionary : [Int: String] = [1: &quot;John&quot;, 2: &quot;Doe&quot;]</pre><ul><li><strong>Insert elements into a Dictionary: </strong>We can insert a value into the dictionary using a key. If the key already exists it will replace the previous value for this key elsewhere it will add a new value.</li></ul><pre>simpleDictionary[3] = &quot;Mihalos&quot;  // Add a value &quot;Mihalos&quot; for key &quot;3&quot;</pre><ul><li><strong>Access Elements of Dictionary: </strong>We can access the elements of a dictionary by using the key. Also swift provided a list of methods to get values and check different parameters.</li></ul><pre>simpleDictionary[2] //return the value of second key-value pair in dictionary </pre><pre>simpleDictionary.count // return the number of elements in dictionary</pre><pre>simpleDictionary.isEmpty  // return false if dictionary is </pre><pre>emptysimpleDictionary.capacity  // return the number of elements in dictionary</pre><pre>simpleDictionary.first  //get the first element from dictionary</pre><pre>simpleDictionary.max { a, b in a.value &lt; b.value}  // return key-value pair for maximum value</pre><pre>simpleDictionary.min()  { a, b in a.value &lt; b.value}  // return key-value pair for minimumvalue</pre><pre>simpleDictionary.sorted( by: { $0.0 &lt; $1.0 }) // reurn an sorted array of dictionary</pre><pre>simpleDictionary.reversed()  //return key-value pair in reverse order</pre><pre>simpleDictionary.shuffled()  //shuffle the key-value pair of dictionary</pre><ul><li><strong>Replace elements from a Dictionary: </strong>A value for a key is simply replaced by putting a new value for that key. We also can use “updateValue” method to replace the value for any key. But Remember “updateValue” method returns the previous value as output.</li></ul><pre>simpleDictionary[3] = &quot;Mike&quot;<br>simpleDictionary.updateValue(&quot;Duke&quot;, forKey: 3)<br></pre><ul><li><strong>Remove elements from Dictionary: </strong>Dictionary elements<strong> </strong>can be removed in a different way.</li></ul><pre>simpleDictionary[3] = nil  // remove key-value pair for key &quot;3&quot;<strong><br></strong>simpleDictionary.removeAll() // remove all element from dictionary arraysimpleDictionary.removeAll(keepingCapacity: true) remove all elements with keeping the capacity or not</pre><ul><li><strong>Iterate</strong> <strong>over</strong> <strong>the</strong> <strong>Dictionary: </strong>Every key-value pairs of a dictionary can be traverse using loop</li></ul><pre>for (key, value) in simpleDictionary {<br>    print(key, value)<br>}</pre><p>Instead of key-value pair we also can access only key or value from dictionary like this</p><pre>for key in simpleDictionary.keys{<br>    print(key)<br>}</pre><pre>for value in simpleDictionary.values{<br>    print(value)<br>}</pre><p>We also can get the keys and values of a dictionary as an array.</p><pre>let keys = [Int](simpleDictionary.keys)  // return all the keys as an array<br>let values = [String](simpleDictionary.values)  //return all the values as an array</pre><h3>3. Set</h3><p>Set is an unordered collection of the same type of data. The main characteristic of the set is, set can not have any duplicate elements.</p><ul><li><strong>Declare a Set: </strong>You can declare an empty Int type set like this</li></ul><pre>var simpleSet = Set&lt;Int&gt;()</pre><p>The set can be any type in swift. We can also declare with some initial values. Swift is a strongly typed language so we don’t have to tell the type when we declare a set but we can also specify the type</p><pre>var simpleSet = Set([10, 20, 30, 40, 20])<br>var simpleSet: Set&lt;String&gt; = [&quot;John&quot;, &quot;Doe&quot;, &quot;Hi&quot;, &quot;John&quot;]</pre><p>You also can declare a set with some repeated values but you will get a single value for those repeated value cause set didn’t store any duplicate element.</p><pre>var simpleSet = Set(repeatElement(1, count: 3)) // Initialize set with three ones but set will have only one into it.</pre><ul><li><strong>Insert elements into a set: </strong>We can insert an element at the end of the array or in a valid position.</li></ul><pre>simpleSet.insert(12) // //append element at the end of set</pre><ul><li><strong>Access Elements of a set: </strong>Like array you cannot access set elements using subscript syntax but you can check an element is in the set or not. Also swift provided a list of methods to get values and check different parameters.</li></ul><pre>simpleSet.contains(2)  // check an element is in the set or not<br>simpleSet.count  // return the number of elements in set<br>simpleSet.isEmpty  // return false if set is empty simpleSet.capacity  // return the number of elements in set</pre><pre>simpleSet.first  //get the first element from set<br>simpleSet.max()  //get the max element from set<br>simpleSet.min()  //get the min element from set</pre><pre>simpleSet.sorted()  // sort the set<br>simpleSet.reversed()  // reverse set<br>simpleSet.shuffled() // shuffle set elements</pre><ul><li><strong>Remove elements: </strong>Set<strong> </strong>elements<strong> </strong>can remove from different way &amp; from different positions also.</li></ul><pre>simpleSet.removeFirst() // remove first element from set<br>simpleSet.remove(1)  // remove from a specific index</pre><pre>simpleSet.removeAll()  // remove all elements from set<br>simpleSet.removeAll(keepingCapacity: true)  // remove all elements with keeping the capacity or not</pre><ul><li><strong>Iterate</strong> <strong>over</strong> <strong>the set: </strong>Every element of a set can be traverse using loop</li></ul><pre>for data in simpleSet {<br>    print(data)<br>}</pre><p>The set type didn’t have any order so if you want to traverse in any order you can do it by swift provided methods</p><pre>for data in simpleSet.sorted() {<br>    print(data)<br>}</pre><pre>for data in simpleSet.reversed() {<br>    print(data)<br>}</pre><ul><li><strong>Different set operations: </strong>You also can perform different set operations within two sets and each of those operations will create a new set.</li></ul><pre>simpleSet2.union(simpleSet3).sorted()  // perform union opertion within simpleSet2 &amp; simpleSet3<br>simpleSet2.intersection(simpleSet3) // perform intersection within two set<br>simpleSet2.subtracting(simpleSet3)  // perform subtracting<br>simpleSet2.symmetricDifference(simpleSet3)  // perform symmetricDifference</pre><pre>simpleSet2.isSubset(of: simpleSet3)  // check one set is subset of snother or not <br>simpleSet2.isSuperset(of: simpleSet3)  // check superset or not <br>simpleSet2.isDisjoint(with: simpleSet3)  // check disjoint or not</pre><p>We will summarize by listing some of the main differences between Array, Dictionary, and Set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItajwlqjAoqWKgL11n6w0w.png" /></figure><p>Congratulation 🎉 🎉 🎉 Now you know what are the collection types in Swift, how and where to use them. You will find a brief discussion of them on <a href="https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html">swift official documentation</a>.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38e634ef2370" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ContainerView in swift]]></title>
            <link>https://levelup.gitconnected.com/containerview-in-swift-83da488f4b57?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/83da488f4b57</guid>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[container-view]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Sat, 16 May 2020 18:03:41 GMT</pubDate>
            <atom:updated>2020-07-02T04:33:27.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTRuQRYBPT96UqUAp2syzQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joannakosinska">Joanna Kosinska</a> via <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Overview</h3><p>In iOS development, sometimes we need to show different view elements in a single place of a view controller. It can be done by managing different child view controller (AKA ContainerView) into a parent view controller depending upon different conditions. In this tutorial, we will learn:</p><ol><li>How to configure container views in a view controller?</li><li>How to show different container views by managing them depending on different conditions?</li><li>How to pass information from parent to child view controllers and vice versa using a closure.</li></ol><blockquote><em>This tutorial is written using </em><strong><em>Swift 5, Xcode 11.2, iOS 13 &amp; Storyboard Interface.</em></strong></blockquote><h3>Start with creating a project</h3><p>Create a single view application in Xcode. Take a label for the top of the view controller and an image view at the bottom. Set constrain and take outlets for them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wR00sv4k1Yf8BasVrthi2A.png" /></figure><p>We will take two different container views from the object library and set them as child view controllers of this “View Controller”.</p><p>Drag and drop a container view from the object library into your view controller and place it between the label and image view. Set constrain for that container view. Create a swift file named as “FirstChildVC”. Select that container view from the storyboard, set class and identifier for that container view as “FirstChildVC”. I added the project overview picture after adding the first child view controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ALKgGMQmfHUcp_eOJDd2A.png" /></figure><p>Now drag and drop a button into your “FirstChildVC”. Set name, constrain, and take an action outlet for that. The idea is that when we press this button, it will communicate with “View Controller” and based on that we will do some changes in our “View Controller”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DM3u-gArMUzNrcDb3PycoA.png" /></figure><p>Now drag and drop another container view and set similar constrain as “FirstChildVC”. It will place up to the “FirstChildVC”. Take a swift file as “SecondChildVC”. Set class, an identifier for that container view as “SecondChildVC”. Put a button into it, take an action outlet, and design that button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaiwIK7XwYZbDYzMfJxjag.png" /></figure><p>Container views are connected with our “View Controller” as a segue. So we have to set an identifier for each segue. Set the identifier as the class name of each container view. The below picture shows how to set an identifier for “FirstChildVC”. Don&#39;t forget to set it also for “SecondChildVC”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PR_wJzjT3txHoQaOuvlXg.png" /></figure><p>Our project setup is almost done but just one more thing to do. Added two images related to dark and light themes though my image it not fitted perfectly as theme image but leave it as it is. I named them as “morning” and “night”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfhUj21q-s-4fUHsNHyVZQ.png" /></figure><h3>Connect with the container view</h3><p>First of all, we will do some initial setup for the container views in the view controller. Initially, We will show “FirstChildVC” container view, and hide “SecondChildVC” container view from the “View Controller”. That’s why at the top of the “View Controller” we will set the label as “FirstChildVC” because it is on the screen right now. We also set “morning” image as the image view image. Replace your “viewDidLoad” function with this code:</p><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {</pre><pre><strong>super</strong>.viewDidLoad()</pre><pre>    firstChildVC.layer.borderColor = UIColor.systemBlue.cgColor</pre><pre>    firstChildVC.layer.borderWidth = 1</pre><pre>    secondChildVC.layer.borderColor = UIColor.systemYellow.cgColor</pre><pre>    secondChildVC.layer.borderWidth = 1</pre><pre>    /* Initially FirstChildVC is showing and SecondChildVC is hidden*/</pre><pre>    firstChildVC.isHidden = <strong>false</strong></pre><pre>    secondChildVC.isHidden = <strong>true</strong></pre><pre>    /*Initially Container Name set to FirstChildVC*/</pre><pre>    containerName.text = &quot;FirstChildVC&quot;</pre><pre>    /*Initially imageView image set to morning image*/</pre><pre>    imageView.image = UIImage(named: &quot;morning&quot;)</pre><pre>}</pre><p>Our container view already places into the storyboard and ready to go but we have to connect them from the “View Controller.swift” class also. First of all, Go find the identifier of the container views from the storyboard and put them into different variables in “ViewController.swift” file.</p><pre>static let toFirstChild = &quot;FirstChildVC&quot;</pre><pre>static let toSecondChild = &quot;SecondChildVC&quot;</pre><p>To talk with our container views we have to make connections with them. We will do it using “<strong><em>override</em></strong><em> </em><strong><em>func</em></strong><em> prepare(for segue: UIStoryboardSegue, sender: </em><strong><em>Any</em></strong><em>?</em>)” function. This function takes the identifiers of the container view controllers and makes a connection for them. Write down this block of code into your view controller class.</p><pre><strong>override</strong> <strong>func</strong> prepare(for segue: UIStoryboardSegue, sender: <strong>Any</strong>?) {</pre><pre><strong>if</strong> segue.identifier == ViewController.toFirstChild {</pre><pre><strong>if</strong> <strong>let</strong> firstChildCV = segue.destination <strong>as</strong>? FirstChildVC {</pre><pre>     //Access your child VC elements</pre><pre>   }</pre><pre>}</pre><pre><strong>if</strong> segue.identifier == ViewController.toSecondChild{</pre><pre><strong>if</strong> <strong>let</strong> secondChildCV = segue.destination <strong>as</strong>? SecondChildVC {</pre><pre>     //Access your child VC elements</pre><pre>   }</pre><pre>  }</pre><pre>}</pre><p>Inside the “segue. destination” block you can communicate with your child container view, send, and receive data. Cool 😎 😎 😎</p><h3>Callback function</h3><p>Now we want to notify View controller and do something when container view buttons are pressed. For that, we need a Callback function. The callback function is basically a closure which is used to communicate different view controller and pass data depending on any event happens.</p><p>Declare this callback function in your “FirstChildVC” class.</p><pre><strong>var</strong> showDarkThemeBtnTap : (()-&gt; Void)?</pre><p>And write down this line of code into your “showDarkThemeBtnTapped” button action function</p><pre>showDarkThemeBtnTap?()</pre><p>Do some things for the “SecondChildVC” also, declare a callback function</p><pre><strong>var</strong> showLightThemeBtnTap : (()-&gt; Void)?</pre><p>Similarly to the previous one write this on “showLightThemeBtnTapped” button action</p><pre>showLightThemeBtnTap?()</pre><p>Now from the parent view controller, we have to set an observer to observe the callback function. The bold marked block of code will notify us when the callback function sends events from the child view controller to the parent view controller.</p><pre>if segue.identifier == ViewController.toFirstChild {</pre><pre><strong>     </strong>if let firstChildCV = segue.destination <strong>as?</strong> FirstChildVC {</pre><pre>     firstChildCV.showDarkThemeBtnTap = {</pre><pre>      //Access your child VC elements</pre><pre>       <strong>firstChildCV.showDarkThemeBtnTap = {<br>              //Do action on child class button tap</strong></pre><pre><strong>          }</strong></pre><pre>      }</pre><pre>   }</pre><p>Here inside this block “<em>firstChildCV.showDarkThemeBtnTap = {}” </em>you can do anything depending on button tap action. Basically, here we will show and hide our view controllers, set image for image, and showing the name of the view controller that is on the screen now. Inside this block write those lines of code.</p><pre>firstChildCV.showDarkThemeBtnTap = {</pre><pre>     //show hide view controllers</pre><pre><strong>     </strong>self.firstChildVC.isHidden = true</pre><pre><strong>     </strong>self.secondChildVC.isHidden = false</pre><pre>     //set image for imageview</pre><pre><strong>     </strong>self.imageView.image = UIImage(named: &quot;night&quot;)</pre><pre>     /*Set Container Name*/</pre><pre><strong>     </strong>self.containerName.text = &quot;SecondChildVC</pre><pre>}</pre><p>Similarly, we will set an observer for the second child view controller and write code like this to toggle between container view.</p><pre>secondChildCV.showLightThemeBtnTap = {</pre><pre>     //show hide view controllers</pre><pre><strong>     </strong>self.firstChildVC.isHidden = false</pre><pre><strong>     </strong>self.secondChildVC.isHidden = true</pre><pre>     //set image for imageview</pre><pre><strong>     </strong>self.imageView.image = UIImage(named: &quot;morning&quot;)</pre><pre>     /*Set Container Name*/</pre><pre><strong>     </strong>self.containerName.text = &quot;FirstChildVC&quot;</pre><pre>}</pre><p>It’s time to test what we do so far. Build and run your project and check your program output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*bkVRdmJ96VsXf7W084DXWQ.gif" /></figure><p>Here is the full code snippet of the “View Controller” class.</p><pre><strong>import</strong> UIKit</pre><pre><strong>class</strong> ViewController: UIViewController {</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> containerName: UILabel!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> imageView: UIImageView!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> firstChildVC: UIView!</pre><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> secondChildVC: UIView!</pre><pre><strong>static</strong> <strong>let</strong> toFirstChild = &quot;FirstChildVC&quot;</pre><pre><strong>static</strong> <strong>let</strong> toSecondChild = &quot;SecondChildVC&quot;</pre><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {</pre><pre><strong>super</strong>.viewDidLoad()</pre><pre>    firstChildVC.layer.borderColor = UIColor.systemBlue.cgColor</pre><pre>    firstChildVC.layer.borderWidth = 1</pre><pre>    secondChildVC.layer.borderColor = UIColor.systemYellow.cgColor</pre><pre>    secondChildVC.layer.borderWidth = 1</pre><pre>    /* Initially FirstChildVC is showing and SecondChildVC is hidden*/</pre><pre>    firstChildVC.isHidden = <strong>false</strong></pre><pre>    secondChildVC.isHidden = <strong>true</strong></pre><pre>    /*Initially Container Name set to FirstChildVC*/</pre><pre>    containerName.text = &quot;FirstChildVC&quot;</pre><pre>    /*Initially imageView image set to morning image*/</pre><pre>    imageView.image = UIImage(named: &quot;morning&quot;)</pre><pre>}</pre><pre><strong>override</strong> <strong>func</strong> prepare(for segue: UIStoryboardSegue, sender: <strong>Any</strong>?) {</pre><pre><strong>    if</strong> segue.identifier == ViewController.toFirstChild {</pre><pre><strong>    if</strong> <strong>let</strong> firstChildCV = segue.destination <strong>as</strong>? FirstChildVC {</pre><pre>    firstChildCV.showDarkThemeBtnTap = {</pre><pre>    //Access your child VC elements</pre><pre>    //show hide view controllers</pre><pre><strong>    self</strong>.firstChildVC.isHidden = <strong>true</strong></pre><pre><strong>    self</strong>.secondChildVC.isHidden = <strong>false</strong></pre><pre>    //set image for imageview</pre><pre><strong>    self</strong>.imageView.image = UIImage(named: &quot;night&quot;)</pre><pre>    /*Set Container Name*/</pre><pre><strong>    self</strong>.containerName.text = &quot;SecondChildVC&quot;</pre><pre>    }</pre><pre>  }</pre><pre>}</pre><pre><strong>    if</strong> segue.identifier == ViewController.toSecondChild{</pre><pre><strong>    if</strong> <strong>let</strong> secondChildCV = segue.destination <strong>as</strong>? SecondChildVC {</pre><pre>    //Access your child VC elements</pre><pre>    secondChildCV.showLightThemeBtnTap = {</pre><pre>    //show hide view controllers</pre><pre><strong>    self</strong>.firstChildVC.isHidden = <strong>false</strong></pre><pre><strong>    self</strong>.secondChildVC.isHidden = <strong>true</strong></pre><pre>    //set image for imageview</pre><pre><strong>    self</strong>.imageView.image = UIImage(named: &quot;morning&quot;)</pre><pre>    /*Set Container Name*/</pre><pre><strong>    self</strong>.containerName.text = &quot;FirstChildVC&quot;</pre><pre>    }</pre><pre>   }</pre><pre>  }</pre><pre> }</pre><pre>}</pre><p>Our “FirstChildVC” class</p><pre><strong>import</strong> UIKit</pre><pre><strong>class</strong> FirstChildVC: UIViewController {</pre><pre><strong>var</strong> showDarkThemeBtnTap : (()-&gt; Void)?</pre><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {</pre><pre><strong>super</strong>.viewDidLoad()</pre><pre>}</pre><pre><strong>@IBAction</strong> <strong>func</strong> showDarkThemeBtnTapped(<strong>_</strong> sender: <strong>Any</strong>) {</pre><pre>showDarkThemeBtnTap?()</pre><pre>}</pre><pre>}</pre><p>Code snipped of “SecondChildVC” class</p><pre><strong>import</strong> UIKit</pre><pre><strong>class</strong> SecondChildVC: UIViewController {</pre><pre><strong>var</strong> showLightThemeBtnTap : (()-&gt; Void)?</pre><pre><strong>override</strong> <strong>func</strong> viewDidLoad() {</pre><pre><strong>super</strong>.viewDidLoad()</pre><pre>}</pre><pre><strong>@IBAction</strong> <strong>func</strong> showLightThemeBtnTapped(<strong>_</strong> sender: <strong>Any</strong>) {</pre><pre>showLightThemeBtnTap?()</pre><pre>}</pre><pre>}</pre><p>Congratulations 🎉 🎉 🎉 , now you know how to set container views on a view controller, how to access, and communicate with the container view elements.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83da488f4b57" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/containerview-in-swift-83da488f4b57">ContainerView in swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UINavigation Controller and UINavigationBar in Swift]]></title>
            <link>https://levelup.gitconnected.com/uinavigation-controller-and-uinavigationbar-in-swift-ff3532fd58b6?source=rss-d994c18c4b9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff3532fd58b6</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[uinavigationbar]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Muhammad Ariful Islam]]></dc:creator>
            <pubDate>Sat, 09 May 2020 07:59:55 GMT</pubDate>
            <atom:updated>2020-07-02T04:30:11.064Z</atom:updated>
            <content:encoded><![CDATA[<h3>UINavigationController and UINavigationBar in Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*792WKR_ntFsLIPa0hfSawA.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@unlesbar">Stephan Henning</a> via <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Overview</h3><p>A navigation controller is a container view that can manage the navigation of hierarchical contents. The navigation controller manages the current displaying screen using the navigation stack. Navigation stack can have “n” numbers of view controllers. The bottom-most view controller in that stack is the root view controller and others are child view controller. At a time only one child view controller is visible which is the topmost view controller in the navigation hierarchy. A view controller can add or remove from the stack using push and pop operation.</p><p>In this tutorial, we will learn</p><ol><li>How to embed view controllers into the navigation controller?</li><li>Ways to push, pop from the navigation stack?</li><li>How to use the navigation stack as an array?</li><li>Customize the navigation bar? So let&#39;s get started</li></ol><blockquote>This tutorial is written using <strong>Swift 5, Xcode 11.2, iOS 13 &amp; Storyboard Interface.</strong></blockquote><h3>1. Start with Navigation Controller</h3><p>Create a single view application in Xcode. Add two view controller into your storyboard. Create two different swift files for those view controllers and set identifiers for them. Take a button in each view controller, set constrain for them and customize as you want. Add action outlets for those buttons into the corresponding view controller. In my case, I named the view controllers as “FirstVC” &amp; “SecondVC” and buttons as “Push SecondVC” &amp; “Pop To First”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfVF7ThJ91nSfuW761JCRw.png" /></figure><p>Now embed your “FirstVC” into navigation controller using storyboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5aeT75JBmQdBtLGXtTNFsw.png" /></figure><p>If your storyboard file seems something like this you are ready to go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4P3PapH0FjfkwMZWsp6X6A.png" /></figure><p>You can also embed your “FirstVC” into the navigation controller programmatically in swift. But in this tutorial, we kept this simple and straightforward by using a storyboard.</p><h4>Push and Pop into the navigation stack</h4><p>We will see how to push, pop and pop to root view controller into the navigation stack</p><ul><li><strong><em>Push To Top</em></strong></li></ul><p>When you push a view controller it places into the top of the navigation stack and up to the view controller from where you push. That means if you push <em>“</em>SecondVC” from “FirstVC”, “SecondVC” will place up to the “FirstVC”. If you press back into the “SecondVC” it will redirect you to “FirstVC”.</p><p>In our example, this push operation is done by pressing the “Push SecondVC” button into the “FirstVC”.</p><pre>let storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil)</pre><pre>let vc = storyboard.instantiateViewController(identifier: &quot;SecondVC&quot;)</pre><pre>self.navigationController?.pushViewController(vc, animated: true)</pre><ul><li><strong><em>Pop From Top</em></strong></li></ul><p>Now if we want to remove the topmost view controller from the navigation stack then we have to pop that view controller. In our example now “SecondVC” is the topmost view controller and if we want to remove it from the navigation stack then we will write this block of code in the “popToFirstVC” button action</p><pre>self.navigationController?.popViewController(animated: true)</pre><ul><li><strong><em>Pop To Root View controller</em></strong></li></ul><p>We can push “n” numbers of view controllers into the navigation stack. Sometimes we have to go to the root view controller from any of the view controllers then we can use this block of code to execute it.</p><pre>navigationController?.popToRootViewController(animated: true)</pre><p>You can check it by replacing the codes in the “popToFirstVC” button action in “SecondVC”.</p><h4>Navigation Stack as Array</h4><p>In the navigation controller, child view controllers are stored as order array. We can access view controllers from that array also. Now we will see different uses using this array.</p><ul><li><strong><em>Remove View controller from the array</em></strong></li></ul><p>We can remove view controllers from different positions of the navigation stack array. First of all, we will get all the available view controllers and then we will do the remove operation</p><pre>var navVCArray = self.navigationController?.viewControllers<br>navVCArray?.removeLast() //Remove the last view controller<br>navVCArray?.removeFirst() // Remove the first view controller<br>navVCArray?.removeAll() //Remove all view controllers<br>navVCArray?.remove(at: 0) //Remove at specific position</pre><ul><li><strong><em>Push View controller</em></strong></li></ul><p>As like remove view controller we also can push a new view controller into the navigation stack using <strong>append()</strong>. Suppose we want to remove the last view controller and add a new view controller into the stack then we will do something like this</p><pre>var navVCArray = self.navigationController?.viewControllers<br>navVCArray?.removeLast()</pre><pre>let storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil)<br>let vc = storyboard.instantiateViewController(identifier: &quot;SecondVC&quot;)<br>navVCArray?.append(vc)</pre><h3>2. Customize Navigation Bar</h3><p>When we embed a view controller into the navigation controller from a storyboard or push a view controller, a white area appears at the top of the view controller. That is the navigation bar. We can add title, bar button, and perform lots of customization on that.</p><ul><li>Change “barTintColor”, “tintColor”</li></ul><pre>self.navigationController?.navigationBar.isTranslucent = false</pre><pre>self.navigationController?.navigationBar.barTintColor = .cyan</pre><pre>self.navigationController?.navigationBar.tintColor = .brown</pre><ul><li>Set setBackgroundImage, shadowImage</li></ul><pre>navigationController?.navigationBar.setBackgroundImage(UIImage(named: &quot;Banner2&quot;), for: .default)</pre><pre>navigationController?.navigationBar.shadowImage = UIImage(named: &quot;Banner&quot;)</pre><ul><li>Set Title and customize title color</li></ul><pre>self.navigationItem.title = &quot;First VC&quot;</pre><pre>let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.red]</pre><pre>navigationController?.navigationBar.titleTextAttributes = textAttributes</pre><ul><li>Set an image as navbar title</li></ul><pre><strong>let</strong> logo = UIImage(named: &quot;edit&quot;)</pre><pre><strong>let</strong> imageView = UIImageView(image:logo)</pre><pre><strong>self</strong>.navigationItem.titleView = imageView</pre><ul><li>Clear your navbar background</li></ul><pre>self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)</pre><pre>self.navigationBar.shadowImage = UIImage()</pre><pre>self.navigationBar.isTranslucent = true</pre><pre>self.view.backgroundColor = UIColor.clear</pre><ul><li>Remove your navbar border</li></ul><pre>self.navigationBar.setBackgroundImage(UIImage(), for:.default)</pre><pre>self.navigationBar.shadowImage = UIImage()</pre><pre>self.navigationBar.layoutIfNeeded()</pre><ul><li>Customize the back button. Remove the title of the back button and set the color.</li></ul><pre>navigationItem.backBarButtonItem = UIBarButtonItem(title: &quot;&quot;, style: .plain, target: nil, action: nil)</pre><pre>navigationItem.backBarButtonItem?.tintColor = UIColor.cgLightBlue</pre><ul><li>Add a bar button item: We can add leftBarButtonItem &amp; rightBarButtonItem using system icon, text or custom image. Add a leftBarButtonItem with barButtonSystemItem add</li></ul><pre>navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))</pre><ul><li>Add rightBarButtonItem with “Add” title</li></ul><pre>navigationItem.rightBarButtonItem = UIBarButtonItem(title: &quot;Add&quot;, style: .plain, target: self, action: #selector(addTapped))</pre><ul><li>Create a bar button with own customization</li></ul><pre>let playButton = UIButton(type: .custom)</pre><pre>playButton.setImage(UIImage(named: &quot;plus&quot;), for: .normal)</pre><pre>playButton.addTarget<strong>(</strong>self, action: #selector(playTapped), for: .touchUpInside)</pre><pre>playButton.frame = CGRect(x: 0, y: 0, width: 10, height: 10)</pre><pre>let barButton = UIBarButtonItem(customView: playButton)</pre><ul><li>Add multiple rightBarButtonItem</li></ul><pre>let add = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(addTapped))</pre><pre>let playButton = UIButton(type: .custom)</pre><pre>playButton.setImage(UIImage(named: &quot;plus&quot;), for: .normal)</pre><pre>playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)</pre><pre>playButton.frame = CGRect(x: 0, y: 0, width: 10, height: 10)</pre><pre>let barButton = UIBarButtonItem(customView: playButton)</pre><pre>navigationItem.rightBarButtonItems = [add, barButton]</pre><p>That’s all for today. Please check the apple doc for <a href="https://developer.apple.com/documentation/uikit/uinavigationcontroller">UINavigationController</a> and <a href="https://developer.apple.com/documentation/uikit/uinavigationbar">NavigationBar </a>to do a lot of hacks with them.</p><p><strong>If you found this article useful please share and give some clap</strong> 👏👏👏<br>Check my other articles on <a href="https://medium.com/@arifulislam14">Medium</a> and connect me on <a href="https://www.linkedin.com/in/arifparvez14/">LinkedIn</a>.</p><p>Thank you for reading &amp; Happy coding 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff3532fd58b6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/uinavigation-controller-and-uinavigationbar-in-swift-ff3532fd58b6">UINavigation Controller and UINavigationBar in Swift</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>