<?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 Ajaya Mati on Medium]]></title>
        <description><![CDATA[Stories by Ajaya Mati on Medium]]></description>
        <link>https://medium.com/@ajayamati?source=rss-fe5027dcd53a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wUjXrwAMuJExUMbEgKlphA.jpeg</url>
            <title>Stories by Ajaya Mati on Medium</title>
            <link>https://medium.com/@ajayamati?source=rss-fe5027dcd53a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:06:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajayamati/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[Understanding data flow in SwiftUI 5]]></title>
            <link>https://ajayamati.medium.com/understanding-data-model-in-swiftui-5-9dc9ef17462a?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dc9ef17462a</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 14:41:12 GMT</pubDate>
            <atom:updated>2024-01-22T16:32:41.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEaYV5btDCyv5bF8tw2_bQ.png" /><figcaption>SwiftUI</figcaption></figure><p>Apple introduced <strong>SwiftUI</strong> for the first time on 3 June 2019, and the team has constantly been improving the syntax quality and performance optimization ever since.</p><p>Each release shows a drastic<em>(but really good)</em> change in syntax structure and fundamentals. With the release of SwiftUI 5, it completely took apart its reactive foundation by replacing <strong>Combine</strong> with the new <strong>Observation</strong> framework.</p><p>The changes I’m going to mention are supported only on iOS17+. So You probably don’t have to worry about changing your existing code to update with new changes as previous syntaxes are also supported.</p><p>Prior to <strong>SwiftUI 5</strong> we had @StateObject, @ObservedObject and to able to uplift them we had to conform to ObservableObject by our custom class. But <strong>SwiftUI 5 </strong>introduced @Observable&amp; @Bindable simplifying the way we handle reactive class instances.</p><p>Now to handle the data model in a View we just need to explore</p><ol><li>@State</li><li>@Binding</li><li>@Observable</li><li>@Bindable</li></ol><h3>1. @State</h3><p><strong>@State</strong> tells that the view <strong>owns</strong> the instance or variable as the single source of truth. All the <strong>SwiftUI</strong> <strong>Views</strong> are <strong>struct </strong>and so are <strong>immutable</strong>, and <strong>@State</strong> provides us the privilege to read and write the instance as a side-effect to other events .</p><pre>struct ContentView: View {<br>    @State private var isPlaying: Bool = false<br>    <br>    var body: some View {<br>        Text(&quot;Hello World&quot;)<br>        Button(isPlaying ? &quot;Pause&quot; : &quot;Play&quot;) { // Read the state.<br>            isPlaying.toggle()<br>        }<br>    }<br>}</pre><p>In the above example, we created a <strong>@State</strong> isPlaying: Booland initialize it with false . We make @<strong>State</strong> as private as the <strong>View</strong> owns that property and only that <strong>View</strong> should initialize it.</p><p>We can access its wrapped value by directly referring to it as a shortcut provided by default with SwiftUI as done here isPlaying ? “Pause” : “Play” . And we are also able to mutate it by assigning a new value, which would have been <strong>impossible</strong> without <strong>@State</strong>. <strong><em>(Try to mutate isPlaying without the @State annotation).</em></strong></p><h3>2. @Binding</h3><p>Binding also creates a two-way connection to read and write the View properties, but it doesn’t own that property by itself but the value of the <strong>@Binding</strong> comes from the SuperView.</p><pre>struct ContentView: View {<br>    @State private var isPlaying: Bool = true<br>    <br>    var body: some View {<br>        Text(&quot;Hello World&quot;)<br>        ButtonView(isPlaying: $isPlaying)<br>    }<br>}<br><br>struct ButtonView: View {<br>    @Binding var isPlaying: Bool<br>    var body: some View {<br>        Button(isPlaying ? &quot;Pause&quot; : &quot;Play&quot;) { // Read the state.<br>            isPlaying.toggle()<br>        }<br>    }<br>}</pre><p>Here we can see <strong>ButtonView</strong> holds a binding to isPlaying from the source <strong>ContentView</strong>.</p><p>The <strong>dollar sign</strong> <strong>($) </strong>before isPlaying in ButtonView(isPlaying: $isPlaying) is a shortcut to access the projected value of the isPlaying <strong>@State</strong> from the <strong>ContentView</strong>. The projected value of a <strong>@State</strong> gives us an instance of type<strong>Binding&lt;Value&gt;</strong>.</p><p>In the ButtonView we are able to read and write just like we did with <strong>@State</strong> variable on the first example.</p><p>So we can safely say that the only difference between a <strong>@Binding</strong> and a <strong>@State</strong> is that <strong>@State</strong> is the single source of truth that stores the original value &amp; <strong>@Binding</strong> connects a property to a source of truth stored elsewhere.</p><p>But both provide a two-way connection to read and write.</p><h3>3. @Observable</h3><p><strong>@Observable</strong> was introduced in <strong>SwiftUI 5</strong> as part of the Swift <strong>Observation</strong> framework that replaces <strong>Combine’s</strong> <strong>ObservableObject</strong> protocol and provides us with a simpler way to handle reactiveness for class instance properties using the existing data flow primitives like <a href="https://developer.apple.com/documentation/swiftui/state">State</a> and <a href="https://developer.apple.com/documentation/swiftui/environment">Environment</a> instead of object-based equivalents such as <a href="https://developer.apple.com/documentation/swiftui/stateobject">StateObject</a> and <a href="https://developer.apple.com/documentation/swiftui/environmentobject">EnvironmentObject</a>.</p><p>It’s only applicable to classes. Structs don&#39;t need it as struct instances can directly be used inside a view as they are immutable and don’t need property observation.</p><pre>@Observable class ContentViewModel {<br>    var isPlaying: Bool = false<br>}<br><br>struct ContentView: View {<br>    private var viewModel: ContentViewModel = ContentViewModel()<br>    <br>    var body: some View {<br>        Text(&quot;\(viewModel.isPlaying ? &quot;playing&quot;: &quot;not playing&quot;)&quot;)<br>    }<br>}<br></pre><p>Unlike <strong>ObservableObject</strong> earlier to <strong>SwfitUI 5</strong>, <strong>@Observable</strong>don’t need to write <strong>@Publish</strong> in front of the properties to make them reactive as instances of a <strong>@Observable</strong> by default publish changes, even if they are not marked by <strong>@State</strong> or <strong>@Enviroment</strong> inside a SwiftUI View.</p><p>The <strong>@Observable</strong> adds <strong>@ObservationTracked</strong> by default to its members and makes them reactive. For properties that do not want to be observed, they need to be annotated with <strong>@ObservationIgnored</strong> in front of them.</p><p>We can use <strong>@State</strong> or <strong>@Binding</strong> to mark them as the state variable for that view if needed for two-way connection same as we do with struct instances.</p><pre>struct ContentView: View {<br>    @State private var viewModel: ContentViewModel = ContentViewModel()<br>    <br>    var body: some View {<br>        Text(&quot;Hello World&quot;)<br>        ButtonView(isPlaying: $viewModel.isPlaying)<br>    }<br>}</pre><p>Just like struct instances with <strong>@State</strong>, we can use the <strong>dollar sign ($)</strong> to access the projected value, which is <strong>Binding&lt;Value&gt;</strong>, of that <strong>@Observable .</strong></p><h3>4. @Bindable</h3><p><strong>@Bindable</strong> is used with <strong>@Observable</strong> instances that help us create <strong>@Binding</strong>.</p><pre>struct ContentView: View {<br>    @Bindable private var viewModel: ContentViewModel = ContentViewModel()<br>    <br>    var body: some View {<br>        Text(&quot;Hello World&quot;)<br>        ButtonView(isPlaying: $viewModel.isPlaying)<br>    }<br>}</pre><p>I’ve seen so many blogs on <strong>Binding vs Bindable</strong>. But they have very different functionality and one doesn’t replace the other.</p><p>With <strong>@Observable</strong> we get the one-way read access that can publish changes over time. For two-way read &amp; write access we need <strong>@Binding</strong>.</p><p>To create <strong>@Binding</strong>-s we can use <strong>@State</strong> or <strong>@Bindable</strong>. The difference between <strong>@State</strong> and <strong>@Bindable</strong>is <strong>@State</strong> owns the instance and <strong>can mutate</strong> it. But for <strong>@Bindable</strong>, it may or may not own the instance but <strong>cannot mutate</strong> it directly but can only provide <strong>@Binding</strong>-s for its member and those <strong>@Binding</strong>-s are mutable.</p><p><strong>Dollar sign ($)</strong> to access the projected value, and accessing members gives us <strong>@Binding</strong> to that member.</p><p>Check out this example to understand more.</p><pre>@Observable<br>class Book: Identifiable {<br>    var title = &quot;Sample Book Title&quot;<br>    var isAvailable = true<br>}<br><br>struct LibraryView: View {<br>    @State private var books = [Book(), Book(), Book()]<br><br>    var body: some View {<br>        List(books) { book in<br>            @Bindable var book = book<br>            TextField(&quot;Title&quot;, text: $book.title)<br>        }<br>    }<br>}</pre><p>In the above example @Bindable var book = book makes the book instance <strong>Bindable</strong> so it can provide a binding $book.title.</p><h3>Summing Up</h3><ol><li><strong>@State</strong> : Owns the property &amp; makes the property mutable, two-way connection for read &amp; write</li><li><strong>@Binding</strong>: Doesn’t own the property but can mutate it, two-way connection for read &amp; write</li><li><strong>@Observable</strong>: make class instances reactive i.e class instance’s member variables publish changes over time, one-way connection for read only</li><li><strong>@Bindable</strong>: May or may not own the property but can’t mutate, helps <strong>Observables </strong>to create <strong>Binding</strong> for their member variables.</li></ol><h3>References</h3><ol><li><a href="https://developer.apple.com/documentation/swiftui/model-data">https://developer.apple.com/documentation/swiftui/model-data</a></li><li><a href="https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app">https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app</a></li><li><a href="https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro">https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dc9ef17462a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Swift (Part 2)]]></title>
            <link>https://ajayamati.medium.com/multithreading-part-2-issues-and-countermeasures-ce9b03b45509?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9b03b45509</guid>
            <category><![CDATA[data-race]]></category>
            <category><![CDATA[deadlock]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 15:54:03 GMT</pubDate>
            <atom:updated>2024-06-07T19:10:36.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gV6btEyCA71Hkdy6" /><figcaption>Photo by <a href="https://unsplash.com/@emtm17?utm_source=medium&amp;utm_medium=referral">Marissa&amp;Eric</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a multithreaded environment, we get the power of parallel computing by tapping into every core of the CPU. As stated “With great power comes great responsibility”, we need to take care of a few things to ensure the correctness of our program.</p><p>In my previous article, We talked about the definition and usefulness of Multi-threaded programming. We also used GCD’s own DispatchQueue and DispatchGroup. In this article, we will discuss the issues we might get into in a multithreaded environment.</p><blockquote>If you have yet to go through my previous article I recommend reading that once using the following <a href="https://medium.com/@ajayamati/multi-threading-in-swift-3f4c9c4769c5">link</a>.</blockquote><h4>1. Deadlock</h4><p>When a thread gets blocked and has to wait indefinitely to get unblocked, we get a Deadlock. It can cause hangs and crashes in our application.</p><p>One of the key causes of deadlock can be the use of shared resources from multiple threads.</p><p>Take an example where 2 resources are there and two different threads need these two resources to complete their execution.</p><p>In a situation where these two threads are running in parallel, there may be a case when both of the threads can acquire one resource by themselves.</p><p>Now both the threads will never be able to complete their execution because they will be waiting for another resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GCpqWSCLgakcjnOZpKvUA.png" /></figure><p>Rather a simple example is mentioned below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa1cfe7c8979558c474cfb8508454d93/href">https://medium.com/media/aa1cfe7c8979558c474cfb8508454d93/href</a></iframe><p>Every sync operation blocks the current thread, and will only get unblocked right after the sync block gets executed successfully.</p><p>So in the above example our, “Hey” gets printed from the main thread and after that, the main thread gets blocked and waits for the completion of the sync block. But again we are trying to print (“Reader”) from the main thread only, and this operation will never be able to execute as our main thread is already blocked. And this leads to a deadlock. The application will crash and will get a bad access error.</p><blockquote>Read more about deadlock <a href="https://www.geeksforgeeks.org/introduction-of-deadlock-in-operating-system/">here</a>.</blockquote><h4>2. Race Condition</h4><p>The order of events/executions is essential to verify the currentness of a program. When dealing with multiple threads one has to ensure the order of events/executions remains the same we expect it to be.</p><p>Take this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1772ce797362e7d6e8bdca3a678fcb92/href">https://medium.com/media/1772ce797362e7d6e8bdca3a678fcb92/href</a></iframe><p>In the class, Name we have a member setFullName which takes two arguments, firstName and lastName . Then we concurrently update an instance name by calling the method.</p><p>Now, one should expect to get <em>Hi i</em>and <em>Hello i</em> (same suffix) in the console. But if you run this piece of code, you’ll see a very interesting outcome. The result might be different for every time we execute it. The suffix integer of Hi and Hello might be different.</p><p>Why is it happening? We are parallelly updating the firstName and lastName from different threads.</p><p>Consider two Thread thread1 and thread2 . Now we call the method from both of the threads parallelly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/524b21c00b7385066cd86dfea9d60bfc/href">https://medium.com/media/524b21c00b7385066cd86dfea9d60bfc/href</a></iframe><p>Here we see the two events updating firstName and updating lastName order matters.</p><p>The above situation is called Race Condition. To avoid race conditions, any operation on a shared resource must be executed atomically.</p><pre>self.firstName = first<br>self.lastName = last</pre><p>These two statements are our critical section, and the execution of a critical section must be atomic.</p><p>Atomicity refers to the execution of a set of statements as a single unit. No other thread will be able to interfere in between. i.e executing the section of statements on only one thread at a single time.</p><p>Atomicity can be achieved using a locking mechanism or a counting semaphore.</p><blockquote>For more on Race condition checkout <a href="https://www.avanderlee.com/swift/race-condition-vs-data-race/">this</a> link.</blockquote><h4>3. Data Race</h4><p><strong>Data Race </strong>or <strong>Access Race </strong>happens when two or more threads try to <strong><em>access</em></strong> a shared mutable resource while one of the threads is <strong><em>writing </em></strong>to it.</p><p>Mutating a memory location while accessing it from a different thread gives a <strong>Thread 7: EXC_BAD_ACCESS (code=1, address=0x10) </strong>error.</p><p>The below scenario is an example of a <strong>Data Race</strong>. Here we are concurrently accessing and updating the <strong>“aKey” </strong>key-value of the Dictionary from multiple threads.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4271a57661d29f0c53017b3081ac9bbc/href">https://medium.com/media/4271a57661d29f0c53017b3081ac9bbc/href</a></iframe><p>The dictionary is our shared resource here. If you try to run this piece of code you’ll end with a crash.</p><p><strong>Data races</strong> happen with all types of resources. Here I took the example of a <strong>Dictionary</strong>, but it also happens with <strong>String</strong>, <strong>Array</strong> and even with <strong>Int</strong>, <strong>Double</strong>.</p><p>You are probably wondering why the <em>Race Condition example</em> didn’t give any error/crash. There also we were mutating the firstName &amp; lastName from multiple places. Read more about this swift value type thread safety <a href="https://forums.swift.org/t/understanding-swifts-value-type-thread-safety/41406"><strong>here</strong></a>.</p><blockquote><strong>Race Condition</strong> is about the data integrity/validation &amp; <strong>Data Race</strong> is about safely accessing shared resources across multiple threads. Both together makes up thread safety.</blockquote><p>To check for thread safety issues in a real application, enable the thread sanitizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5kPBSf0iDU9PxpF3V2zWA.png" /></figure><h4>4. Priority Inversion</h4><p>When a low-priority task delays the execution of a high-priority task, we get priority inversion. This happens when a low-priority thread gets hold of resources or locks a critical section which is also needed by a high-priority thread.</p><p>In an ideal scenario, the high-priority tasks should be able to finish using the resource/critical section before the low-priority tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c5b87e6e8aef8621d2f2c49181c0a2b/href">https://medium.com/media/4c5b87e6e8aef8621d2f2c49181c0a2b/href</a></iframe><p>In the above example, both operations are happening in parallel to each other as they are async operations. But you’ll see that our high-priority utilityQueue tasks are getting done before the backgroundQueue tasks despite the relative order of calling. The output is expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCbbWpJeq0yi0SLinSsGZg.png" /></figure><p>Now if we add a third statement trying to do a task in <strong>sync</strong> with starterQueue from the backgroundQueue , we’ll end up with a different rather unexpected output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/034542eb488b139ad671ebeaf32d236c/href">https://medium.com/media/034542eb488b139ad671ebeaf32d236c/href</a></iframe><p>You can see our most of the higher priority tasks are done in the last after the low priority tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N3acNlGPNdC_9tK0bQuTJg.png" /></figure><p>To understand why it’s happening, we have to understand what GCD does under the hood while a <strong>low-priority task</strong> blocks a <strong>high-priority task</strong> (through sync block or mutex lock). It temporarily raises the <strong>qos</strong>(Quality of Service)<strong> </strong>of the thread containing the low-priority task.</p><p>So in the above example, you can see backgroundQueue <strong>qos </strong>temporarily<strong> </strong>raised to userInteractive as the containing starterQueue has a <strong>qos</strong> of the same, because of the sync operation.</p><p>Again if we changed the example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a22d3f993123f6ca0c3990be8d51759f/href">https://medium.com/media/a22d3f993123f6ca0c3990be8d51759f/href</a></iframe><p>We can see that task 0(backgroundQueue) ends first in comparison to<br>task 1 (utilityQueue) because of <strong>inversion in priority</strong>. But after the sync block, the operations work in order of their priority<br> i.e. task 3 (utilityQueue) then task 2(backgroundQueue).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8T_2lYGEmMmx52eI2U5eg.png" /></figure><h3>Summing Up</h3><p>In this article, we learned about the issue in a multithreaded environment.</p><p>I highly recommend you to go through these links for a better and broader understanding.</p><ol><li><a href="https://www.avanderlee.com/swift/deadlocks-detecting-solving/">https://www.avanderlee.com/swift/deadlocks-detecting-solving/</a></li><li><a href="https://www.geeksforgeeks.org/introduction-of-deadlock-in-operating-system/">https://www.geeksforgeeks.org/introduction-of-deadlock-in-operating-system/</a></li><li><a href="https://forums.swift.org/t/understanding-swifts-value-type-thread-safety/41406">https://forums.swift.org/t/understanding-swifts-value-type-thread-safety/41406</a></li><li><a href="https://www.avanderlee.com/swift/race-condition-vs-data-race/">https://www.avanderlee.com/swift/race-condition-vs-data-race/</a></li><li><a href="https://www.avanderlee.com/swift/thread-sanitizer-data-races/">https://www.avanderlee.com/swift/thread-sanitizer-data-races/</a></li></ol><p><a href="https://ajayamati.medium.com/multi-threading-in-swift-3f4c9c4769c5">Multi-Threading in Swift(Part-1)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9b03b45509" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Class vs. Struct]]></title>
            <link>https://ajayamati.medium.com/swift-class-vs-struct-674f27abac37?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/674f27abac37</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[class-vs-struct]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 11:28:39 GMT</pubDate>
            <atom:updated>2023-09-20T13:51:14.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4tkYowVZiade4FCdUYhXg.png" /></figure><p>This article discusses the differences between classes and structs in Swift. If you want to read about when and how to use these both I highly recommend you to go through <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/classesandstructures/">swift official documentation</a>.</p><h4>1. Reference &amp; Value type</h4><p>Structs are value types whereas classes are reference types, i.e. every class instance can have multiple references.</p><p>To handle these multiple references ARC comes into play. To read more about ARC, you can refer to the below article.</p><p><a href="https://ajayamati.medium.com/arc-in-swift-strong-vs-weak-vs-unowned-c3a4ab87d1bf">ARC in Swift(Strong vs Weak vs Unowned)</a></p><h4>2. De-init</h4><p>As <strong>class</strong> <strong>instances</strong> can have multiple references and won’t get <strong>de-allocated</strong> till the reference count is <strong>zero</strong>, we developer may need to do some cleanup when it happens. To get this call back we have a deinit function for classes.</p><p>Whereas <strong>struct</strong> <strong>instances</strong> get de-allocated when the instance gets out of the scope of its executing block. So we won&#39;t need an extra callback and because of that swift doesn&#39;t have a <strong>deinit</strong> for <strong>structs. </strong><em>(It does have other reasons too)</em></p><h4>3. mutable vs immutable</h4><p><strong>Structs</strong> are truly <strong>immutable</strong>. That means every mutation copies every single member variable.</p><p>To see this in action we took the below example.</p><pre>struct C {<br>    var q: Int<br>    init() {<br>        self.q = 0<br>        print(&quot;c is being initialized&quot;)<br>    }<br>}<br><br>class B {<br>    var c: C {<br>        didSet {<br>            print(&quot;c updated&quot;)<br>        }<br>    }<br>    <br>    init(c: C) {<br>        self.c = c<br>        print(&quot;B is intialized&quot;)<br>    }<br>}<br><br>var b = B(c: C())<br>b.c.q = 6<br><br>// prints <br>// c is being initalized<br>// B is intialized<br>// c updated</pre><p>Even though the actual modification of the value in memory likely happens <strong><em>in-place</em></strong>, at a semantic level the entire <strong>C struct</strong> is being replaced with an entirely new value. That is the reason mutation is not allowed on let struct instances</p><p>Consider reading this forum for more detailed context.</p><p><a href="https://forums.swift.org/t/why-are-structs-in-swift-said-to-be-immutable/55319/8">Why are structs in Swift said to be immutable?</a></p><p>Whereas classes member variable can be mutable even if the reference is a let (i.e. constant).</p><pre>class SomeClass {<br>    var a: Int<br>    <br>    init(a: Int) {<br>        self.a = a<br>    }<br>}<br><br>let s = SomeClass(a: 7)<br>print(s.a)<br>s.a = 8<br>print(s.a)<br><br>// prints<br>// 7<br>// 8</pre><h4>4. Stack vs heap</h4><p>Structs are value types so their sizes can be determined in the compile time and can be allocated in the call stack memory.</p><p>Class being reference type the sizes need to be calculated in the runtime, so <strong>Swift</strong> uses the memory heap for the dynamic memory allocation.</p><p>That’s the reason structs are fast compared to class.</p><p>Read more about swift memory management</p><p><a href="https://www.bigmountainstudio.com/community/public/posts/53680-swift-memory-a-deeper-look-into-how-objects-are-stored">Swift Memory - A Deeper Look Into How Objects are Stored</a></p><h4><strong>5. Inheritance and conformance</strong></h4><p>Classes support <strong>Inheritance</strong> of other classes, though it doesn’t support multiple inheritance for a good reason. They can conform to protocols.</p><p>Structs on the other hand don&#39;t support inheritance, but they can also conform to protocol.</p><h4><strong>6. Static vs. Dynamic dispatch</strong></h4><p>Inheritance &amp; method overriding is the reason why classes need dynamic dispatch.</p><p>By default, methods of classes are subject to dynamic dispatch. When you define a class method, it can be overridden by subclasses, and the method implementation to call is determined at runtime based on the actual subclass type.</p><p>Methods of structs are typically statically dispatched because structs are value types, and their methods are resolved based on the compile-time type of the variable. Since struct methods cannot be overridden, there’s no need for dynamic dispatch.</p><h4><strong>7. Type casting</strong></h4><p>Classes support inheritance. So a reference type of super class can contain subclass instances. We as a developer most of the time will need to check the type of the instance rather than the reference in the runtime.</p><p>Swift provides as, is, as?, as! operators to do these type-casting in the runtime.</p><p>Structs on the other hand don’t need runtime type-casting.</p><h4>8. Working with closure</h4><p>If you already know closure then you must know that closure are reference type and the reference types need to be taken care of if we are working with classes. Otherwise, we’ll end up with <strong>retain cycles</strong>.</p><pre>class SomeClass {<br>    var a = 8<br>    func doSomething() {<br>        DispatchQueue.main.async {<br>            print(self.a)<br>        }<br>    }<br>}<br><br>struct SomeStruct {<br>    var a = 8<br>    func doSomething() {<br>        DispatchQueue.main.async {<br>            print(a)<br>        }<br>    }<br>}</pre><p>In the above example, you can see that I had to <strong>explicitly</strong> use self the class member method inside the closure but in Struct, I did not.</p><p>Closure inside Struct can implicitly capture Swift, as the compiler doesn’t need to worry about ARC, but in the case of class, we have to explicitly use self and define the reference type (weak, unowned, or strong) as per our requirement.</p><blockquote>The above example uses @<strong>escaping</strong> closure, which is why we needed to use self. But in the case of non-escaping closure, the life cycle of closure will be confined to the function life cycle. The closure will get <strong>freed up from memory</strong> when the doSomething returns. So we don’t need to worry about ARC, and we don’t have to explicitly mention self even if it is inside a class.</blockquote><h4>9. Equality(==) &amp; Identity(===) operator</h4><p>Equality(==) works for struct and classes that conform to <strong>Equatable</strong> protocol. It tells if two instances are equal or not.</p><p>Wherein Identity(===) works only for instance of a class or class-constrained type<strong>(AnyObject)</strong>. It checks if two reference points to the same memory location.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674f27abac37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto Layout in iOS UIKit]]></title>
            <link>https://ajayamati.medium.com/auto-layout-in-ios-uikit-524b95671234?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/524b95671234</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[autolayout-constraints]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 08:23:39 GMT</pubDate>
            <atom:updated>2023-07-23T15:47:25.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TlcDRA2mgPCwS6zg" /><figcaption>Photo by <a href="https://unsplash.com/@oh_gosh?utm_source=medium&amp;utm_medium=referral">Seyi Ariyo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Auto Layout is a constraint-based layout system that automatically positions and sizes view in a user interface, as a result, allows us to create a dynamic/responsive UI for different screen sizes and orientations.</p><p>First, let’s talk about creating <strong>UI</strong> without <strong>Auto Layout.</strong></p><h3>Frame-based Layout system</h3><pre>class ViewController: UIViewController {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>        <br>        let view = UIView(frame: .init(x: 100, y: 500, width: 200, height: 300))<br>        view.backgroundColor = .red<br>        <br>        self.view.addSubview(view)<br>    }<br>}</pre><p>Here we are creating a <strong>UIView</strong> named <strong><em>view</em> </strong>and giving the frame as CGRect(x: 100, y: 500, width: 200, height: 300) and then adding the <strong><em>view </em></strong>as a subview to the <strong>ViewController’s view</strong>. So what can go wrong?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5dWPa-8H8HKti4gbZGZXw.png" /></figure><p>Our layout looks okay in <strong>iPhone 14 pro</strong> but when it comes to smaller size devices like <strong>iPhone SE</strong> the UI gets clipped. Also if we change the orientation to landscape in <strong>iPhone 14 pro</strong>, you won&#39;t be able to see the <strong>red box</strong>. Let’s see what is happening here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*8yff6Xo6s2fO0dTyXAA9eg.png" /></figure><p>Here the <strong>View Controller’s view</strong> takes the whole device <strong>frame</strong> i.e (393,852) Our custom <strong>UIView</strong> then gets added into the <strong>bound</strong> of the <strong>View Controller’s view</strong>, So the UI is static here.</p><blockquote>Frame refers to the coordinate system of the view’s container (parent view). Bounds refer to the own coordinate system of the view.</blockquote><p>But is there any way to solve this?</p><p>Yes. Consider, We want the red box to be positioned at the <strong>bottom</strong> of the screen with a gap of 16 points <strong>vertically</strong>, and <strong>horizontally</strong> <strong>center</strong> to the device screen. Here’s how we can do.</p><pre>// Width and Height of the Red Box<br>let width: CGFloat = 200.0<br>let height: CGFloat = 300.0<br><br>///Calculating `x-position`<br>/// View is horizontaly centered to the super view<br>let x: CGFloat = self.view.center.x - (width / 2.0)<br><br>/// Calculating `y-position`<br>/// View is verticaly placed at the bottom with a gap of 16 Point<br>let y: CGFloat = self.view.frame.maxY - 16.0 - height<br><br>let view = UIView(frame: .init(x: x, y: y, width: width, height: height))<br>view.backgroundColor = .red<br><br>self.view.addSubview(view)</pre><p>The above code will work just fine with any device size and orientation. But, creating a complex layout with 100s of views where we have to calculate the frame of every view would be an impossible task.</p><p>Now you know the issue with the <strong>frame-based layout system</strong> and here, <strong>Auto Layout</strong>, the <strong>constraint-based layout system</strong> comes into play.</p><h3><strong>Constraint-based layout system</strong></h3><p><strong>Constraints </strong>are <strong>Linear Equations</strong> that we provide to a <strong>UIView</strong> and using these <strong>constraints</strong> the <strong>frame of the UIView </strong>is then gets calculated in the run time.</p><p>The equation follows the format</p><pre>item1.attribute1 = multiplier × item2.attribute2 + constant</pre><p>Let’s replicate the <strong>Red Bo</strong>x layout with <strong>Constraints</strong>.</p><h4>Using Storyboard to Add Constraints</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBNdxwOv3aHUcybOllWY5g.png" /></figure><p>We have added four constraints to our Red Box with the help of the storyboard.</p><p>If you expand the bottom constraint you’ll see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*JmoAqmlfl26dnaYaOaw9Ug.png" /></figure><pre>=&gt; Safe Area.Bottom = Red Box.Bottom * Multiplier + Constant<br><br>Multiplier = 1, So<br>=&gt; Safe Area.Bottom = Red Box.Bottom + Constant<br>=&gt; Red Box.Bottom = Safe Area.Bottom - Constant</pre><p>The above equation is how the frame of the red box gets calculated. Likewise, we can express other constraints into equations.</p><h4>Programmatically adding Constraints</h4><p><strong>Constraints</strong> are instances of <strong>NSLayoutConstraint </strong>and can be made directly with a specified initializer <strong><em>or</em></strong> using <strong>NSLayoutAnchor .</strong></p><p>The initializer is defined as</p><pre>convenience init(<br>    item view1: Any,<br>    attribute attr1: NSLayoutConstraint.Attribute,<br>    relatedBy relation: NSLayoutConstraint.Relation,<br>    toItem view2: Any?,<br>    attribute attr2: NSLayoutConstraint.Attribute,<br>    multiplier: CGFloat,<br>    constant c: CGFloat<br>)</pre><blockquote>From Apple: <br>Constraints represent linear equations of the form view1.attr1 &lt;relation&gt; multiplier × view2.attr2 + c. If the constraint you wish to express does not have a second view and attribute, use nil and <a href="https://developer.apple.com/documentation/uikit/nslayoutconstraint/attribute/notanattribute">NSLayoutConstraint.Attribute.notAnAttribute</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wedzZ4WRUQcm1VxY1jiHkw.png" /></figure><p>We created the four constraints for width, height, centerX, and bottom, the same as the constraints we created earlier using the storyboard. After creating the <strong>NSLayoutConstrains </strong>we have to activate them. We can individually activate each constraint by setting theisActive property to true , or using activate(_ constraints: [<a href="https://developer.apple.com/documentation/uikit/nslayoutconstraint">NSLayoutConstraint</a>]) .</p><blockquote>Here we have to explicilty set translatesAutoresizingMaskIntoConstraints set to false, it means that the autoresizing mask is not translated into constraints, and you are indicating that you&#39;ll be using Auto Layout to define the view&#39;s layout constraints explicitly. For more insight checkout this <a href="https://www.youtube.com/watch?v=pI-yolo9NrM">video</a>.</blockquote><p>We used safeAreaLayoutGuide of the <strong>super view</strong> to make constraints with the safe area instead of the <strong>view</strong> directly.</p><blockquote>From Apple:<br>This method throws an <a href="https://developer.apple.com/documentation/foundation/nsexceptionname/1415426-invalidargumentexception">invalidArgumentException</a> exception if it is used to create an invalid constraint (for example, view1.top == 0.0 x nil.NotAnAttribute + 200.0 or view1.top == 1.0 x view2.height + 20.0).</blockquote><p>Using <strong>Anchor</strong> to add constraints is a bit easy, and better error-proof.</p><p>We can replicate the same constraints using <strong>NSLayoutAnchor </strong>, and here’s how we are going to do it.</p><pre>// Dimensional Constraints<br>let widthConstraint = redBoxView.widthAnchor.constraint(equalToConstant: 200.0)<br>let heightConstraint = redBoxView.heightAnchor.constraint(equalToConstant: 300.0)<br><br>//Axial Contraints<br>let centerXConstraint = redBoxView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0.0)<br>let bottomConstraint = redBoxView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -16.0)</pre><p>In the runtime, we can disable the constraints by setting isActive to false. Also, we can change other properties of <strong>NSLayoutConstraint</strong> .</p><p>Changing constraints inside <strong>UIView.animate </strong>will create animations.</p><pre>  UIView.animate(withDuration: 4.0, delay: .zero) {<br>      heightConstraint.constant = 500<br>      self.view.layoutIfNeeded()<br>  }</pre><p>The above code will create an animation with an expanding height of the Red Box.</p><blockquote>By calling layoutIfNeeded(), you force an immediate update of the view&#39;s layout, ensuring that any pending layout changes are applied. This is useful in situations where you want to ensure that the view appears correctly with the most up-to-date layout before performing additional operations or animations.</blockquote><h3>Intrinsic size and Content Hugging Priority vs Content Compression Resistance Priority</h3><p>UIView components that have intrinsic size are UILabel, UIButton, UIImageView,UITextField, and UITextView . Views with intrinsic size can be used in Auto Layout without specifying their size explicitly, as they can “intrinsically” calculate their width and height. By setting the values for <strong>content hugging priority</strong> and <strong>content compression resistance priority,</strong> we can determine how a layout will look when there is a lack of space or extra space is available.</p><ol><li><strong>Content Hugging Priority<br></strong>Content Hugging Priority is a constraint property that affects a view’s ability to “hug” its content tightly. It determines how much a view resists <strong>growing larger than its intrinsic content size</strong> when there is extra space available in the layout. Higher <strong>Content Hugging Priority</strong> values indicate a stronger preference for maintaining the view’s intrinsic size.</li><li><strong>Content Compression Resistance Priority<br></strong>It determines how much a view resists being compressed when there is a lack of space within the layout. Higher <strong>Content Compression Resistance Priority</strong> values indicate a stronger preference for <strong>maintaining the view’s size and avoiding compression</strong>. When there is insufficient space, views with higher <strong>Content Compression Resistance</strong> <strong>Priority</strong> are less likely to be resized or truncated. Instead, other views with lower resistance priorities might be resized or compressed first.</li></ol><p>Let’s see these two in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WZx1NxH1sd6ncKrJvjblg.png" /></figure><p>In the above example, we added two <strong>UILabels</strong> inside a UIView. For better visualization, I’ve given background colors to each view. Well, the Labels do look fine in the layout but if we change the content of <strong>UILabels</strong> to longer text they will start overlapping each other. Xcode has given a warning for that so we better give them the required constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ebML7enBiI0oBSR7wAVLw.png" /></figure><p>We have provided the <strong>Red Label</strong> with 3 constraints.</p><ol><li><strong>Top</strong> Constraint with a gap of 16 to the <strong>super view</strong></li><li><strong>Leading</strong> Constraint with a gap of 16 to the <strong>super view</strong></li><li><strong>Trailing</strong> Constraint with a gap of 16 to the <strong>Green Label</strong></li></ol><p>Similarly, I added 2 more constraints to the <strong>Green Label</strong>.</p><ol><li><strong>Top</strong> Constraint with a gap of 16 to the <strong>super view</strong></li><li><strong>Trailing</strong> Constraint with a gap of 16 to the <strong>super view</strong></li></ol><p>Now each label has <strong>3 constraints</strong> (1 common constraint for horizontal gap).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9m90z9j5EejdHI5zItJsA.png" /></figure><p>We got an error that says we need to set <strong>Horizontal Hugging Priority</strong>. But wait, before we set the hugging priority let&#39;s set the width of the gray UIView to 2*42(size of the labels)+3*16(gap size) = 132.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IqO1eXb1uXpkgWbAfoN6w.png" /></figure><p>Check out the image. The error just disappears. It happened as the labels get width as much as their intrinsic size. There’s no extra space neither lack of space. If we add some extra text to one of the labels we’ll be back with another error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ma2xSM-t44wY4oz3mAF8Aw.png" /></figure><p>Now it says we need to set the <strong>Horizontal Compression Resistance Priority</strong>.</p><ol><li>When the frame size was bigger we had extra space so we were getting errors for <strong>Horizontal Hugging Priority.</strong></li><li>When the frame size is small and the intrinsic size is bigger, we are left with a lack of space, so we got errors for <strong>Horizontal Compression Resistance Priority.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-QyoHXIIEDwDY_DroNC6Q.gif" /></figure><p>In the first scenario, If we change the <strong>Horizontal Hugging Priority </strong>of the <strong>Red Label</strong> to <strong>252</strong> keeping <strong>251</strong> for the <strong>Green Label,</strong> we can see the <strong>Green Label</strong> expands to the available space but the <strong>Red Label</strong> keeps its width the same as its intrinsic size. Or we can say that the <strong>Red Label</strong> is tightly hugging its content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C72hmviuznjfXdBltsg76w.gif" /></figure><p>In the second scenario, we changed the <strong>Horizontal Compression Resistance Priority</strong> of the <strong>Red Label</strong> to <strong>751</strong>, keeping <strong>750</strong> for <strong>Green Label</strong>. The <strong>Green Label</strong> gets trimmed instead of the <strong>Red Label</strong> because The <strong>Red Label </strong>has a higher <strong>Compression Resistance</strong> than the <strong>Green Label</strong>.</p><p>P.S. These two properties have no effect on views that don&#39;t have any intrinsic size.</p><h3><strong>Reference</strong></h3><ol><li>Auto Resizing Mask: <br><a href="https://www.advancedswift.com/autolayout-vs-autoresizing-masks/">https://www.advancedswift.com/autolayout-vs-autoresizing-masks/</a> <a href="https://www.youtube.com/watch?v=pI-yolo9NrM">https://www.youtube.com/watch?v=pI-yolo9NrM</a></li><li>More On <strong>NSLayoutConstraint</strong>: <a href="https://www.hackingwithswift.com/articles/140/the-auto-layout-cheat-sheet">https://www.hackingwithswift.com/articles/140/the-auto-layout-cheat-sheet</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=524b95671234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ARC in Swift — A Detailed Explanation]]></title>
            <link>https://ajayamati.medium.com/arc-in-swift-strong-vs-weak-vs-unowned-c3a4ab87d1bf?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3a4ab87d1bf</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[arc-in-swift]]></category>
            <category><![CDATA[weak-vs-unowned]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 05:49:50 GMT</pubDate>
            <atom:updated>2023-09-20T11:22:59.019Z</atom:updated>
            <content:encoded><![CDATA[<h3>ARC in Swift — A Detailed Explanation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v0ktTbFLAmNxbmdy" /><figcaption>Photo by <a href="https://unsplash.com/@gary_at_unsplash?utm_source=medium&amp;utm_medium=referral">Gary Chan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>The <strong>memory management</strong> mechanism is different for every language. But it’s the very core of programming and building robust, feature-rich applications. In <strong>Java,</strong> we have <strong>GC</strong> (garbage collector), but in languages like <strong>Obj-c</strong> or <strong>C++</strong>, we developers are responsible for the allocation and deallocation of memory manually. But thanks to Apple, we have <strong>ARC</strong> in Swift which automatically tracks and manages the allocation and deallocation of objects.</p><p>In most cases, we don&#39;t have to do anything for <strong>ARC</strong> to work, but there can be cases where <strong>ARC</strong> will need our help.</p><h3><strong>How ARC (Automatic Reference Counting) works?</strong></h3><p><strong>Structs and Enums </strong>are value types, whereas <strong>Classes</strong> are reference types. So reference counting only applies to C<strong>lass Instances.</strong></p><blockquote>Value-type instances are typically stored directly on the stack or as part of another value, and their memory is automatically managed by the compiler. When a value type goes out of scope or is no longer needed, it is automatically deallocated without the need for reference counting or manual memory management.</blockquote><p>Okay, Let’s take an example.</p><pre>// Created a class<br>class SomeClass {<br>    // Instance Property<br>    var id: String<br>    <br>    // Intializer<br>    init(id: String) {<br>        self.id = id<br>        print(&quot;SomeClass with id \(id) has been initialized&quot;)<br>    }<br>    <br>    deinit {<br>        print(&quot;SomeClass with id \(id) has been de-initialized&quot;)<br>    }<br>}<br><br>var a: SomeClass? = SomeClass(id: &quot;A&quot;) // Reference count of instance is now 1<br>// Prints &quot;SomeClass with id A has been initialized&quot;<br>var b: SomeClass? = a // Reference count inscraeses to 2<br>var c: SomeClass? = a // Reference count inscraeses to 3</pre><p>We declared a class named <strong>SomeClass </strong>and created three references to the same instance. As they are all referring to the same instance the initializer will get called only once.</p><p>Now the instance is being referred by <strong><em>a, b, and c, </em></strong>so the reference count is 3.</p><pre>a = nil // decreases the reference count by 1, remaining 2<br>b = nil // decreases the reference count by 1, remaining 1<br>c = nil // decreases the reference count by 1, remaining 0<br><br>// Prints &quot;SomeClass with id A has been de-initialized&quot;</pre><p>Setting a, b, and c to nil will break the reference and upon reaching a reference count of 0, the instance will get de-initialized, thus calling the <strong>deinit.</strong></p><p>Okay. So now we know how ARC works. But will this always be simple?</p><p>Let’s take another example.</p><pre>class A {<br>    var b: B?<br><br>    deinit {<br>        print(&quot;Deinitialized A&quot;)<br>    }<br>}<br><br>class B {<br>    var a: A?<br><br>    deinit {<br>        print(&quot;Deinitialized B&quot;)<br>    }<br>}<br><br>var a: A? = A()<br>var b: B? = B()<br><br>a?.b = b<br>b?.a = a<br><br>a = nil<br>b = nil</pre><p>If you run the above code, you won’t see any print statement. i.e. both the instance will not get deinitialized. Let’s assess what is happening here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*JZc--lO9011RyXUvXqZUcA.png" /></figure><p><strong>Class A &amp; B </strong>both refer to each other and var <strong>a</strong> and <strong>b</strong> refer to respective instances.</p><p>So instances of class <strong>A and B </strong>are both having a reference count of 2.</p><p>When I set the var <strong>a</strong> to <strong>nil</strong>, instance <strong>A </strong>will not get de-initialized as instance <strong>B </strong>still holds a reference to instance <strong>A</strong>.</p><p>Setting <strong>b </strong>to<strong> nil</strong> won’t be able to de-initialize instance <strong>B</strong> as instance <strong>A</strong> which has not yet been de-initialized still holds a reference to instance <strong>B</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*w87JZR2-rIbzLX4oalUSaw.png" /></figure><p>The above case is an example of <strong>Retain Cycle</strong>. Here<strong> </strong>both instances will never get <strong>de-allocated</strong> and thus will cause a memory leak and we don’t want that.</p><h3>Resolving Retain Cycle</h3><p>Well, not to worry ARC provides us with 3 types of reference with which we can solve <strong>Retain Cycle.</strong></p><p>The three types of references are</p><ol><li><strong>Strong (default)</strong></li><li><strong>Weak</strong></li><li><strong>Unowned</strong></li></ol><p>By default, references are <strong>strong </strong>which increases the <strong>ARC</strong>. Whereas <strong>weak &amp; unowned</strong> will not increase the ARC.</p><p>The use of both <strong>weak and unowned </strong>can solve the <strong>Retain Cycle</strong> issue. But the selection of <strong>weak or unowned </strong>depends upon the relation and life cycle of both instances.</p><h4>Weak Reference</h4><p>A <strong>weak</strong> reference doesn’t keep a strong hold on the instance. A <strong>weak</strong> reference is always defined as an optional type as <strong>ARC </strong>automatically sets the reference to nil when the instance gets deallocated.</p><blockquote>Property Observers don’t get called when ARC sets the value to nil.</blockquote><pre>class A {<br>    var b: B? // A holds a strong reference to B<br><br>    deinit {<br>        print(&quot;Deinitialized A&quot;)<br>    }<br>}<br><br>class B {<br>   weak var a: A? // Now B holds a weak reference to A<br><br>    deinit {<br>        print(&quot;Deinitialized B&quot;)<br>    }<br>}<br><br>var a: A? = A() // Initalizing A<br>var b: B? = B() // Initializing B<br><br>// setting the references<br>a?.b = b<br>b?.a = a</pre><p>Here in this example, we made the reference to <strong>A</strong> inside <strong>B</strong> class a weak reference. Let’s visualize what&#39;s happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOnIL2KwQWe1Djvc6EsVqw.png" /></figure><p>Instance <strong>B</strong> has <strong>2</strong> strong references, so the <strong>ARC</strong> for instance B is <strong>2</strong>. But Instance <strong>A</strong> only has <strong>1</strong> strong reference so the <strong>ARC</strong> is <strong>1</strong>.</p><pre>a = nil // Sets the reference to nil will break the reference<br>// prints Deinitialized A<br>b = nil<br>// prints Deinitialized B</pre><p>Setting <strong>a</strong> to <strong>nil</strong> breaks the only strong reference to instance A, so ARC will deallocate this instance. Now instance B is left with a single reference which is <strong><em>var b</em></strong>. So when we set it to nil, ARC will deallocate the instance <strong>B</strong>.</p><pre>b = nil // Sets the reference to nil will break the reference<br>// still instance B has another strong reference which is<br>// from the instance A so deinit will not get called here<br><br>a = nil // This breaks the only reference to the instace A<br>// prints Deinitialized A<br><br>// Now instance B has no strong reference<br>// prints Deinitialized B</pre><p>Changing the order in which we are setting the value of <strong>variables</strong> to <strong>nil</strong>, will not change the order of <strong>deallocation</strong> of the <strong>objects</strong>. In both scenarios, <strong>A</strong> will get deallocated first, and then <strong>B</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ibjfHm6Y6o6PL2xJvBV7w.png" /></figure><pre>a = nil // prints Deinitialized A<br>print(b?.a) // Prints nil<br><br>b = nil // prints Deinitialized B</pre><p>Here we can see when instance <strong>A</strong> gets de-initialized, the reference to this instance inside <strong>B</strong> is automatically updated to <strong>nil</strong> by <strong>ARC</strong>.</p><h4>Unowned Reference</h4><p>The’s two major differences between <strong>weak</strong> and <strong>unowned.</strong></p><ol><li>Weak is always declared as <strong>optional</strong>, but there are no such constraints with unowned.</li><li>For <strong>weak</strong> references, <strong>ARC</strong> automatically sets the reference to <strong>nil</strong>. But for <strong>unowned</strong> references, we are responsible to manage the instance references. Accessing an already <strong>de-initialized</strong> instance will cause a <strong><em>run-time exception</em></strong>.</li></ol><blockquote>Weak references are always used when the referred instance has a lesser lifetime and unowned is used when the referred instance has same or longer lif-time.</blockquote><pre>class A {<br>    var b: B? // A holds a strong reference to B<br><br>    deinit {<br>        print(&quot;Deinitialized A&quot;)<br>    }<br>}<br><br>class B {<br>   unowned var a: A // Now B holds a unowned reference to A<br>    <br>    init(a: A) {<br>        self.a = a<br>    }<br>    <br>    deinit {<br>        print(&quot;Deinitialized B&quot;)<br>    }<br>}<br><br>var a: A? = A() // Initalizing A<br>var b: B? = B(a: a!) // Initializing B<br><br>// setting the references<br>a?.b = b</pre><p>We changed the reference type to unowned.</p><pre>b = nil<br>print(a?.b) // prints instance B<br>a = nil<br>// prints Deinitialized A<br>// prints Deinitialized B</pre><p>The above code will work just fine. But what if we change the order?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mIVG4ov3QDL-FBDD-Eqbg.png" /></figure><p>When we set <strong>a</strong> to <strong>nil</strong>, instance <strong>A</strong> gets de-initialized. Now if we try to access the reference from instance <strong>B</strong> will get a <strong>run time exception</strong>. So whenever we are using <strong>unowned</strong> we have to be a little extra careful.</p><p>But <strong>unowned</strong> can have its own use cases where we are very sure of the instance lifetime and we want to avoid dealing with optional. Such use cases are seen with <strong>closure</strong> very often<strong>.</strong></p><h3>Closure And ARC</h3><p>The <strong>retention cycle issue </strong>can also be caused between a <strong>closure</strong> and a <strong>class instance</strong> as <strong>closures</strong> are also <strong>reference types</strong>. Similar methods are applied to solve this issue. <strong>Closures</strong> use a capture list to specify the references.</p><pre>class SomeClass {<br>    var x: Int<br>    <br>    lazy var displayValue: () -&gt; Void  = {<br>        print(&quot;The instance has a value of &quot;, self.x)<br>    }<br>    <br>    init(x: Int) {<br>        self.x = x<br>    }<br>    <br>    deinit {<br>        print(&quot;De initalized SomeClass&quot;)<br>    }<br>}<br><br><br>var instance: SomeClass? = SomeClass(x: 6)<br>instance?.displayValue() // prints: The instance has a value of  6<br><br>instance = nil</pre><blockquote>Declaring <strong>displayValue </strong>as lazy<strong> </strong>lets us use<em>self</em> inside the closure. lazy property will not be accessed until after initialization has been completed and self is known to exist.</blockquote><p>See, in the above code <strong>SomeClass</strong> instance holds a <strong>strong</strong> reference to <strong>displayValue</strong> closure and the <strong>closure</strong> also holds a <strong>strong</strong> reference to the <strong>self</strong>, which is the current <strong>instance</strong> of the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TRTN1oE5BFFJXKlbyKFcpQ.png" /></figure><p>To solve this issue we have to change the reference to self as <strong>weak/unowned</strong>. Here, as the closure and class have the same lifetime unowned should be preferred.</p><pre>lazy var displayValue: () -&gt; Void  = { [unowned self] in<br>        print(&quot;The instance has a value of &quot;, self.x)<br>    }</pre><p>Setting instance to nil, will now de-allocate the instance calling the de-initializer.</p><pre>instance = nil<br>// prints De initalized SomeClass</pre><p>For the sake of example, we took the closure but for this particular use case <strong>class method</strong> could have been better.</p><pre>  func displayValue() {<br>      print(&quot;The instance has a value of &quot;, self.x)<br>  }</pre><p>We don&#39;t need to capture self for methods and <strong>ARC</strong> works just fine as the method doesn&#39;t affect the <strong>strong reference count</strong>. But what if, we call a <strong>closure</strong> inside this function which has a longer lifetime than the <strong>class instance</strong>?</p><pre>class SomeClass{<br>  ....<br>    func displayValue() {<br>            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {<br>                print(&quot;The instance has a value of &quot;, self.x)<br>            }<br>        }<br>  ....<br>}<br><br><br>var instance: SomeClass? = SomeClass(x: 6)<br>instance?.displayValue()<br>instance = nil</pre><p>The closure inside displayValue has a <strong>strong reference </strong>toself and is getting called after <strong>2 sec</strong>. So even if we set instance = nil , the de-initializer will get called when it’s finished execution of the closure, i.e</p><pre>// After 2.0 sec<br>// prints The instance has a value of 6<br>// prints De initalized SomeClass</pre><p>But if we use <strong>weak </strong>self?.x inside the <strong>closure</strong> will return nil as the instance gets <strong>de-allocated</strong> and doesn’t wait for the <strong>closure</strong> to finish execution.</p><pre>....<br>func displayValue() {<br>        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in<br>            print(&quot;The instance has a value of &quot;, self?.x)<br>        }<br>    }<br>....<br><br>instance?.displayValue()<br>instance = nil<br>// prints De initalized SomeClass<br>// After 2.0 sec<br>// prints: The instance has a value of nil</pre><p>In contrast, if we use <strong>unowned</strong>, self.x will throw a <strong>runtime exception</strong> as the instance gets <strong>de-allocated</strong> as soon as we set instance = nil.</p><pre>....    <br>func displayValue() {<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) { [unowned self] in<br>            print(&quot;The instance has a value of &quot;, self.x)<br>        }<br>    }<br>....<br>instance?.displayValue()<br>instance = nil<br>// prints De initalized SomeClass<br>// After 2.0 sec<br>//Thread 3: signal SIGABRT</pre><h3>Bonus Section</h3><p>If a class Instance doesn&#39;t have any strong reference it’ll immediately get de-allocated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWv1dSa0zHehRkBWxbNsCQ.png" /></figure><h4>autoreleasepool</h4><p>For <strong>swift classes</strong>, <strong>ARC</strong> is able to properly manage the <strong>allocation</strong> and <strong>deallocation</strong>. But for pure <strong>Obj-c legacy classes </strong>sometimes can cause issues, like writing a loop that creates many temporary objects.</p><p><strong>autoreleasepool</strong> block can solve this issue. The objects which get created inside this block will get <strong>de-allocated</strong> once the block completes execution.</p><p>In <strong>Obj-c</strong> autoreleasepool blocks are marked with @autoreleasepool, and in Swift, we can use autoreleasepool with a closure.</p><pre>for i in 0...10000 {<br>    autoreleasepool {<br>        let file = &quot;file_path_\(i)&quot; // file path for ith image<br>        let url =  URL(fileURLWithPath: file)<br>        let image = try! Data(contentsOf: url)<br>    }<br>}</pre><h4>Explore More</h4><p><a href="https://ajayamati.medium.com/multi-threading-in-swift-3f4c9c4769c5">Multi-Threading in Swift</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3a4ab87d1bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Threading in Swift(Part-1)]]></title>
            <link>https://ajayamati.medium.com/multi-threading-in-swift-3f4c9c4769c5?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f4c9c4769c5</guid>
            <category><![CDATA[data-race]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 11:55:41 GMT</pubDate>
            <atom:updated>2024-09-07T08:51:31.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F-1R7bSgvDZnkkGT" /><figcaption>Photo by <a href="https://unsplash.com/@john_cameron?utm_source=medium&amp;utm_medium=referral">John Cameron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>“What is multi-threading? “</strong>.</h3><p>Even if you are a beginner you must be having some basic knowledge of multi-threading, i.e. Running multiple threads at the same time.</p><p><strong>So the first question arises why do we need multi-threading?</strong></p><p>In a real-life application Consider a scenario when a user needs to download a file from the server. A <strong><em>single-core processor</em></strong> with a <strong><em>single thread</em></strong> can do one task at-a-time. So for a single-threaded application, the user must wait for the download to finish before using the application. Because at that time there won’t be any thread available to process user interactions.</p><p><strong>How to solve this??</strong></p><p>To tackle this issue we can dive into multi-threading. In the above scenario, we can use two threads, one to handle the download and one for the user interaction.</p><h3><strong>So what’s a Thread?</strong></h3><p>A thread is a context in which commands are executed. There are several ways to create Threads in Swift.</p><p>You can either create an Obj-C function and pass it through a selector as starting point</p><pre>Thread.init(target: Any, selector: Selector, object: Any?)</pre><p>Pass a closure into</p><pre>Thread.detachNewThread {<br>}</pre><p>or Sub-class <strong><em>Thread</em></strong></p><pre>class CustomThread: Thread {<br>    override func start() {<br>        print(&quot;Running on Custom Thread &quot;, self.debugDescription)<br>        super.start()<br>    }<br>    <br>    override func main() {<br>        print(&quot;Main called for &quot;, self.debugDescription)<br>    }<br>}<br><br>let thread1 = CustomThread()<br>thread1.start()</pre><p><strong><em>Thread</em></strong> has another two important instance methods, <strong><em>cancel </em></strong>and <strong><em>exit</em></strong>. <strong><em>cancel() </em></strong>sets the current thread <strong><em>isCancelled</em></strong> property to true, which then gets cleaned up by the system gracefully. Whereas <strong><em>exit()</em></strong> makes the <strong><em>Thread</em></strong> stop executing immediately and does not provide an opportunity for cleanup or resource deallocation.</p><h3>Serialization-Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ar7saY4qLViYPPKlwRzgw.png" /></figure><p><strong><em>Serialization</em></strong> is the process of carrying out the execution in a single thread. So only one task can be done at a single time. In contrast, <strong><em>Concurrency</em></strong> refers to carrying out two or more tasks at the same time but not necessarily simultaneously. <strong><em>Concurrency</em></strong> can be achieved by two methods.</p><h4><strong>Context switching</strong> and <strong>Parallelism.</strong></h4><p><strong><em>Context switching</em></strong> is the process performed by an operating system to switch the CPU from executing one thread or process to another. When a context switch occurs, the current state of the running thread or process is saved, including its program counter, register values, and other relevant information.</p><p>In <strong>Parallelism</strong> multiple CPU cores are used to process multiple threads at the same time, as shown in the above diagram.</p><ul><li>So for a <strong><em>Single-core</em></strong> environment to achieve concurrency context switching is used.</li><li>For a <strong><em>Multi-core</em></strong> environment, concurrency can be achieved via parallelism.</li></ul><h3>Sync and Async</h3><h4>Synchronous</h4><p>Consider two tasks,</p><ul><li>downloading a remote file</li><li>Open the file to show to the user</li></ul><p>These two task needs to be done one after another. We have to first completely download the file then we’ll be able open it. This is called <strong><em>synchronous</em></strong> execution. Each task waits for any previous task to complete and then gets executed.</p><p><strong><em>Single-Thread</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*cMA8eU-Q72CC35w4bJ7wRQ.png" /><figcaption>Single-Threaded Sync execution</figcaption></figure><p><strong><em>Multi-Thread</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*dvoExnKYKYmgLaf2Vde32w.png" /><figcaption>Multi-Threaded Sync execution</figcaption></figure><h4>Asynchronous</h4><p>Now Consider two mutually exclusive tasks, e.g. downloading a file from the remote server and updating the application UI. Well, we need to do both the task independently and at-a-time. This is called <strong><em>asynchronous</em></strong> execution. Each task can be executed without waiting for any other tasks to get completed.</p><p><strong><em>Single-Thread</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*ciuGYdBJzdeZBn3EaGksjw.png" /><figcaption>Async Single-Threaded execution using context switch</figcaption></figure><p><strong><em>Multi-Thread</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*6-AkpTkmLQmu_XIZF5a6Kw.png" /><figcaption>Async Multi-Threaded execution using Parallelism</figcaption></figure><blockquote>In synchronous execution, the <strong>caller thread</strong> gets blocked and waits for the complete execution of the <strong>callee</strong> <strong>thread</strong>, but in asynchronous execution <strong>caller</strong> and <strong>callee</strong> <strong>thread</strong> gets executed independently without blocking each other.</blockquote><h4>Asynchronous and Concurrency?</h4><p>We can see that no matter the number of threads present, in <strong><em>synchronous</em></strong> execution every task is performed one by one, whereas in <strong><em>Asynchronous</em></strong> execution multiple tasks get executed at-a-time. So <strong><em>Asynchronous</em></strong> is the way to achieve concurrency.</p><p><strong><em>Concurrency/Serialization</em></strong> defines how two threads are running, whereas <strong><em>Async/Sync</em></strong> tells how two different threads are connected to each other.</p><p>Multithreading and concurrency are a must with the transition from single-core processors to multi-core processors. But the creation and management of Threads is difficult. By default, Threads do not have an autorelease pool, and things like memory management, race condition, deadlocks, etc. become complex with a lot of boiler code.</p><p>Luckily, we are provided an alternative by Apple, <strong>GCD.</strong></p><h3>Grand Central Dispatch</h3><p>It offers a high-level and efficient approach to concurrent programming, by providing a set of APIs and features that abstract away many low-level details of multithreading, making it easier to write efficient and scalable concurrent code.</p><p><strong>GCD</strong> provides <strong><em>Dispatch Queues</em></strong>.</p><h4>What’s a Queue?</h4><p>The <strong>GCD</strong> manages a collection of <strong><em>Dispatch Queues </em></strong>and<strong><em> </em></strong>uses a closure to schedule tasks for execution.</p><p>There are two types of Dispatch Queues available:</p><ul><li><strong>Serial Dispatch Queue</strong>:- Serial Queues, as the name suggests, execute tasks assigned to them in a serial manner i.e. one after another. Order of execution is guaranteed.</li><li><strong>Concurrent Dispatch Queue</strong>:- Concurrent Queue runs multiple tasks at-a-time. Smaller tasks may end sooner, so their order of completion of tasks is not guaranteed.</li></ul><p>By default, <strong><em>GCD</em></strong> provides us with two default Queues, although we can also create our own <strong><em>Dispatch Queues</em></strong>.</p><p><strong>Main Queue (DispatchQueue.main)</strong></p><p>The <strong><em>main queue</em></strong> is a serial queue that runs on the main thread, the thread on which UI updates and user interaction is handled.</p><pre>DispatchQueue.main.async {<br>    print(&quot;This will run on main Thread&quot;)<br>}</pre><blockquote>In general, it is best to use async instead of sync whenever possible. async will not block the current thread, so it will not cause deadlocks.</blockquote><p><strong>Global Queues ( DispatchQueue.global())</strong></p><p>These are <strong>concurrent</strong> queues. The tasks assigned to these queues get executed concurrently on different threads other than the <strong><em>main</em></strong> thread. There are 6 different global queues based on <strong><em>quality of service</em></strong><em>.</em></p><ul><li>.userInteractive - This queue is for tasks that need to be executed quickly, such as user input handling and animations.</li><li>.default - This queue is for tasks that don&#39;t need to be executed quickly, but should still be responsive.</li><li>.utility - This queue is for tasks that can be executed in the background, such as file I/O and network requests.</li><li>.background - This queue is for tasks that can be executed in the background and don&#39;t need to be responsive, such as image processing and data compression.</li><li>.userInitiated - This queue is for tasks initiated by the user that requires a quick response, such as opening a file or loading data in response to a user action. These tasks should have a high priority.</li><li>.unspecified - This queue has no specific QoS level. It is up to the system to decide how to prioritize tasks that are submitted to this queue.</li></ul><pre>DispatchQueue.global(qos: ).async {<br>    <br>}</pre><p><strong>Custom Queue</strong></p><p>We can make our own queue with GCD.</p><pre>let queue = DispatchQueue(label: &quot;com.projectx.gcd&quot;, attributes: .concurrent)<br><br>queue.async {<br>    print(&quot;Asynchronously does the work on the custom queue&quot;)<br>}<br><br>queue.sync {<br>    print(&quot;Synchronously does the work on the custom queue&quot;)<br>}</pre><p>The <strong><em>label</em></strong> is the name of the queue and is a required parameter. By default, all the custom queues are <strong><em>serial</em></strong> in nature but we can explicitly define the <strong><em>attribute</em></strong> to .concurrent to make a <strong><em>concurrent queue</em></strong>.</p><h4>Managing Asynchronous functions</h4><p>Managing <strong>asynchronous</strong> calls can be a little tricky. And with that, the question arrives how can we handle multiple <strong><em>asynchronous</em></strong> calls and handle the execution logic in the order we want?</p><ol><li><strong>Running Tasks in Series</strong></li></ol><p>The first problem arises to simulate synchronous execution using asynchronous functions. By synchronous execution I mean waiting for completion of a task before running another one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRlWUpZ1bG6TVB5k-LEYRA.png" /></figure><p>This is a very common scenario in applications with <strong><em>network calls</em></strong>. Imagine you have two APIs, one is <strong><em>login</em></strong> and another one is to <strong><em>fetch user details</em></strong>. Now in order to <strong><em>fetch user details</em></strong>, the user first has to <strong><em>login</em></strong>.</p><pre>login(userId: String, password: String) {<br>    fetchUserDetail(id: String) {<br>        // do tasks afterward<br>    }<br>}</pre><p>In the above code, I used <strong>completion handlers(nested callbacks) </strong>to solve this problem. Well, this is one of the ways. Looks okay with only two function calls, but imagine if we are having a series of calls one after another.</p><pre>func1 {<br>    func2 {<br>        func3 {<br>            func4 {<br>                <br>            }<br>        }<br>    }<br>}</pre><p>Now this doesn’t look cool, is it? It’ll be very hard to understand and maintain this code. And in coders’ language, it’s called <strong>“ The Pyramid of Doom”</strong>.</p><p>Let’s move on to the next problem statement.</p><p><strong>2. Running tasks in parallel</strong></p><p>The second problem can be to perform some tasks when all the asynchronous calls get completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Hh5HdLTXRtwiBJPQneO4g.png" /></figure><p>Now consider a similar scenario where we have to fetch two types of user details, one is API to fetch the user’s personal detail like <em>name, profile picture, email, and contact details, </em>and the other is to fetch all the stories the user has published (well you can consider the Medium app).</p><p>Now in the <strong>App,</strong> there will be separate sections to show the details, so the <strong>UI </strong>update can be done separately. So we can fetch the details independently and parallelly. But we want to show the loader at the start of fetching and hide the loader when we get responses for both API calls.</p><pre>var flag1 = false<br>var flag2 = false<br>let id = &quot;1234&quot;<br><br>func startFetch() {<br>    // Show the loader<br>    startLoader()<br>    <br>    fetchUserProfileDetails(id: id) {<br>        flag1 = true<br>        hideLoaderIfShould()<br>    }<br>    <br>    fetchUserPublicDetails(id: id) {<br>        flag2 = true<br>        hideLoaderIfShould()<br>    }<br>}<br><br>func startLoader() {<br>    loader.show()<br>}<br><br>func hideLoaderIfShould() {<br>    if flag1 &amp;&amp; flag2 {<br>        loader.hide()<br>    }<br>}</pre><p>Above is one of the ways we can handle the situation, by taking two flags and checking if both are true, i.e. completed.</p><p>Surely the way we handle the above problem statement doesn&#39;t look good. But not to worry <strong>GCD</strong> provides us with another API, the <strong>DispatchGroup.</strong></p><h4><strong>DispatchGroup</strong></h4><p>DispatchGroup provides 4 important methods</p><ol><li><strong>enter(): Increments</strong> the task count by <strong>1</strong> for the <strong>DispatchGroup</strong> instance.</li><li><strong>wait(): Waits</strong> for the current task, for which <strong>enter()</strong> has called, to complete before moving to the next execution.</li><li><strong>leave(): Decrements</strong> the task count by <strong>1</strong> for the <strong>DispatchGroup</strong> instance.</li><li><strong>notify(queue: execute:): </strong>Calls to this method when all the tasks get completed.</li></ol><p>Now let’s solve the previously discuss problem statements using these APIs.</p><ol><li><strong>Running tasks in Series</strong></li></ol><pre>let dispatchGroup = DispatchGroup()<br><br>// starts the tasks-1<br>dispatchGroup.enter()<br>login(userId: String, password: String) {<br>    // ends the tasks-1<br>    dispatchGroup.leave()<br>}<br><br>// waits for tasks-1 to complete<br>dispatchGroup.wait()<br><br>// this will starts the task-2, but will only execute after tasks-1 is complete<br>dispatchGroup.enter()<br>fetchUserDetail(id: String) {<br>    // do tasks afterward<br>    <br>    // ends the tasks-2<br>    dispatchGroup.leave()<br>}<br><br>// this will get called when all the tasks gets completed<br>dispatchGroup.notify(queue: .main) {<br>    print(&quot;Execution completed&quot;)<br>}</pre><p>2. <strong>Running tasks in parallel</strong></p><pre>let id = &quot;1234&quot;<br>let dispatchGroup = DispatchGroup()<br><br>func startFetch() {<br>    // Show the loader<br>    loader.show()<br>    <br>    // starts the task-1<br>    dispatchGroup.enter()<br>    fetchUserProfileDetails(id: id) {<br>        // ends the task-1<br>        dispatchGroup.leave()<br>    }<br>    <br>    // it will start the tasks without waiting for task-1 to complete<br>    dispatchGroup.enter()<br>    fetchUserPublicDetails(id: id) {<br>        // ends task-2<br>        dispatchGroup.leave()<br>    }<br>    <br>    // this will get called when all the tasks gets completed<br>    dispatchGroup.notify(queue: .main) {<br>        print(&quot;Execution completed&quot;)<br>        // hide the loader<br>        loader.hide()<br>    }<br>}</pre><p>Here every task starts with calling <strong>enter() </strong>to let the dispatch queue know the start of the task, and <strong>leave() </strong>gets called on the completion of every task to let the dispatch group know. Calling <strong>wait() </strong>will halt further execution until the last task is complete, and finally the notify method gets called when all the tasks are completed.</p><h3>Summing Up</h3><p>In this article, we learned the concept of multi-threading with the discussion of</p><ol><li>Thread</li><li>Serial-Concurrent-Parallelism</li><li>Sync-Async</li><li>Queue</li><li>Dispatch Group</li></ol><p>Read more on issues in a multithreaded environment in part 2 of this series here.</p><p><a href="https://ajayamati.medium.com/multithreading-part-2-issues-and-countermeasures-ce9b03b45509">Multithreading in Swift (Part 2): issues in a concurrent environment</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f4c9c4769c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started With P5.js]]></title>
            <link>https://ajayamati.medium.com/get-started-with-p5-js-c7f38d844980?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7f38d844980</guid>
            <category><![CDATA[p5js]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[creative-coding]]></category>
            <category><![CDATA[creative]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Fri, 07 May 2021 05:27:43 GMT</pubDate>
            <atom:updated>2021-05-07T06:38:33.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HrcUMfHCsDEPXw2d" /><figcaption>Photo by <a href="https://unsplash.com/@elenatrn?utm_source=medium&amp;utm_medium=referral">Elena Taranenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>An Introduction to creative coding</h4><p>Ever wondered why they say “Coding is fun” ?. If you are from any mainstream programming languages like c,c++, python, or java, then you are definitely aware of the fact that creating variables, writing lots of mathematical expressions just to see some outputs in a console is not that exciting. Not at the beginning, at least.<br>So here comes the p5.js community, which has proved that coding can be fun with their libraries. Without worrying much about the actual code behind the scene, you can start being more creative.</p><p>This article aims at providing a basic understanding of the p5.js library and p5.js web editor but assumes basic knowledge of Javascript and its syntax, specifically:</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements">Statement and Declarations</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expression and Operators</a></li><li><a href="https://www.w3schools.com/js/js_functions.asp">Functions</a></li><li><a href="https://www.w3schools.com/js/js_objects.asp">Objects</a></li></ul><p>I would like to suggest you to refer these docs in parallel.</p><h4>What is p5.js?</h4><p>Here is the quotation from the official site.</p><blockquote>p5.js is a JavaScript library for creative coding, with a focus on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else! p5.js is free and open-source because we believe software, and the tools to learn it, should be accessible to everyone</blockquote><p>The p5.js is a Javascript library that is used to draw sketches on top of the HTML <strong>&lt;canvas&gt;</strong> element. Well, as the documentation says, and with the addition of multiple add-on libraries, we can now perform much more and can think of the whole browser page as our playground.</p><h4>Setup</h4><p>The quickest and easiest way to get started is using the <a href="https://editor.p5js.org/">p5.js web editor</a>. This provides a much better interactive way to do our sketches. If you are more comfortable using your own code editor you can include the <a href="https://cdn.jsdelivr.net/npm/p5/lib/">CDN </a>or <a href="https://p5js.org/download/">download </a>the files in your sketches. If you are using VS Code you can use <a href="https://marketplace.visualstudio.com/items?itemName=samplavigne.p5-vscode">this</a> extension for autocompletion and template creation.</p><p>Alright, let’s start.</p><h4>Our First Sketch</h4><p>We are now ready to write our own sketches. Open <a href="https://editor.p5js.org/">the p5.js web editor</a> and paste the below code into the sketch.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6d5570980243a0ca5b858d9f8c211f1/href">https://medium.com/media/f6d5570980243a0ca5b858d9f8c211f1/href</a></iframe><p>Now press the run button. You can also turn on the auto-refresh so that you don’t have to explicitly rerun the sketch whenever you make any changes to the code.</p><p>Do you see anything in the preview? Nah, you don’t. There’s nothing wrong with the code. Just like its name, the method createCanvas() <strong>, </strong>inside the setup() function, creates an HTML canvas element of width 400px and height 400px. We just cannot see it right now because the canvas background color has the same value as the page background color.</p><p>So let’s give the canvas, a background color.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/512f85f95a2a781eb86bd671ec3d8f84/href">https://medium.com/media/512f85f95a2a781eb86bd671ec3d8f84/href</a></iframe><p>You should see a gray box in the preview. The value 200 is the grayscale color value to the background. The value can be from 0–255.</p><p>We can also give the color in different formats. One such is the RGB format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a152d194f9b67a29ab4d5e64358b66db/href">https://medium.com/media/a152d194f9b67a29ab4d5e64358b66db/href</a></iframe><p>Pasting the above code will result in a red canvas. You can refer to <a href="https://p5js.org/reference/#/p5/background">this link</a> for all the color formats.</p><p>But wait, what is setup() and draw()?</p><p>Let’s understand the code structure.</p><p>The setup() function is called once when the sketch starts. It’s where all things are initialized. It contains initial environment properties such as canvas. It should never be called more than once.</p><p>The draw() function calls in a loop, default is 60 refresh rate per sec. We can change the refresh rate with the framerate() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e1bb6b95babd937c7dc32eb415d0987/href">https://medium.com/media/1e1bb6b95babd937c7dc32eb415d0987/href</a></iframe><p>Now the draw function will be called thrice a sec.</p><p>Let’s visualize the function call by changing the background color on every call.</p><p>First, we have to introduce a new method, random(). It takes two arguments min and max and gives us a value between these two. To read more about random() refer to <a href="https://p5js.org/reference/#/p5/random">this link</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfc49cdd0aaead92d6ed3663b4f39114/href">https://medium.com/media/dfc49cdd0aaead92d6ed3663b4f39114/href</a></iframe><p>Now you should see random colors are being set to the canvas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DrnycxgI758Yt4kuOy-rQ.gif" /></figure><p>Moving on to the next part, let’s add some shape into our sketch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36c39f37347cf55aaeba63eafbd0b90a/href">https://medium.com/media/36c39f37347cf55aaeba63eafbd0b90a/href</a></iframe><p>The circle() method creates a circle at coordinates (100,100) with a diameter of 50.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkKU3uY21qnrFKccbmhfhA.png" /></figure><p>Look at the below image to have a better understanding of the p5.js coordinate system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*r1wtrNhkkf60UYTKyCHX2Q.png" /></figure><p><strong><em>Hooray!!!</em> <em>Congratulations!</em></strong> You have made your first sketch. It’s indeed a simple one but you can explore different shapes from the reference section.</p><h4>Fill &amp; Stroke</h4><p>P5.js gives us a few methods to customize the look of shapes.</p><ul><li><a href="https://p5js.org/reference/#/p5/stroke">stroke(</a>) takes a color value as a parameter in different format as background() method and sets the stoke color</li><li><a href="https://p5js.org/reference/#/p5/noStroke">noStroke(</a>) disable the stroke outline</li><li><a href="https://p5js.org/reference/#/p5/strokeWeight">strokeWeight()</a> takes a single parameter and sets that value as the width of the stroke line.</li><li><a href="https://p5js.org/reference/#/p5/fill">fill()</a> takes a color value as a parameter and sets the fill color of the shapes</li><li><a href="https://p5js.org/reference/#/p5/noFill">noFill()</a> disable the fill color</li></ul><p>Examples:</p><figure><img alt="shapes" src="https://cdn-images-1.medium.com/max/1024/1*FMmv_H7OJ5caxHt2tYPwgQ.png" /></figure><p>We need to be careful while using the above methods. Using one of these sets stroke/fill color value of the succeeding shapes unless and until they are overridden by another function call. These methods retain even across multiple calls of draw().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e907a5cdb7e9e2208203b56c92764050/href">https://medium.com/media/e907a5cdb7e9e2208203b56c92764050/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLFA_a4yGgj3y_HPM_JJug.gif" /></figure><h4>Making sketches alive</h4><p>We now know how to create shapes and place them on our canvas wherever we want. But, how can we make our sketch a little more interactive? Maybe changing the circle position with respect to the mouse movement?</p><p>Well, it’s very easy. p5.js provides two such system variables with which we can access our mouse current position. At any point in time, the position of the mouse pointer can be defined as (mouseX, mouseY). mouseX gives the x-coordinate and mouseY gives the y-coordinate of the current position.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c30a970ba2bda431d89ed8501d5ab7c4/href">https://medium.com/media/c30a970ba2bda431d89ed8501d5ab7c4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTzsWamFxgPuHC3qCMWSZQ.gif" /></figure><p>In the above sketch, the circle’s center will update as the mouse moves.</p><p>Here’s the question that arises “can’t the shapes move there on their own?”. Well, they can. But we have to make some changes to the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1a94fbfd9a663307f5a9b5223e50ee4/href">https://medium.com/media/b1a94fbfd9a663307f5a9b5223e50ee4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7d3dFxT5j3VCofPkyrxMYw.gif" /></figure><p>As the value of x &amp; y changes so the center of the circle, putting the circle into motion. The circle is going out of the canvas and it’s the expected behavior.</p><p>We will make much more interesting sketches in our upcoming tutorial.</p><p><strong>Bye for now! Thank you for reading!</strong> Have fun exploring p5.js!</p><h4>Resources :</h4><p><a href="https://www.youtube.com/watch?v=8j0UDiN7my4&amp;list=PLglp04UYZK_PrN6xWo_nJ-8kzyXDyFUwi">The coding train</a></p><p><a href="https://p5js.org/reference/">P5.js Reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7f38d844980" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Story]]></title>
            <link>https://ajayamati.medium.com/my-first-story-3e59665c197d?source=rss-fe5027dcd53a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e59665c197d</guid>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[first-post]]></category>
            <category><![CDATA[storyofmylife]]></category>
            <dc:creator><![CDATA[Ajaya Mati]]></dc:creator>
            <pubDate>Wed, 05 May 2021 14:58:32 GMT</pubDate>
            <atom:updated>2021-05-05T15:34:46.512Z</atom:updated>
            <content:encoded><![CDATA[<h4>A commitment to a long journey</h4><p>So, here I’m starting to write my own blogs on medium. Well, I’m no professional or have much experience, I’m just writing out of curiosity. Sometimes I get lots of ideas on how to express something difficult in a more pleasant way. And I hope my ideas will be helpful to some of you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H2GOVx2hqDz9H2Dz" /><figcaption>Photo by <a href="https://unsplash.com/@josephandjosephandjoseph?utm_source=medium&amp;utm_medium=referral">Joseph Rosales</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ll start a series on creative coding with the p5.js library. There I’ll explore the core, DOM, and sound library in a detailed way. So stay tuned I’ll be back with some really exciting writings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e59665c197d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>