<?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[Hash Coding - Medium]]></title>
        <description><![CDATA[Everyone should learn to code. - Medium]]></description>
        <link>https://medium.com/hash-coding?source=rss----8167d64d21a9---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Hash Coding - Medium</title>
            <link>https://medium.com/hash-coding?source=rss----8167d64d21a9---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 03 Aug 2026 11:58:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/hash-coding" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Swift — Functions & Closures — Part II]]></title>
            <link>https://medium.com/hash-coding/swift-functions-closures-part-ii-eaf240c684d6?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/eaf240c684d6</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jayant Kumar Yadav]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 15:51:29 GMT</pubDate>
            <atom:updated>2025-03-31T15:51:29.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking The iOS Interview</h4><h3>Swift — Functions &amp; Closures — Part II</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CRKAORMrCG01VWv0" /><figcaption>Photo by <a href="https://unsplash.com/@tomstanislavsky?utm_source=medium&amp;utm_medium=referral">Tomáš Stanislavský</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How was the previous part? I hope it helped you get a brief of what kind of questions related to functions are asked in an interview. In case you haven’t got a chance to look at the first part, I would highly recommend you to visit <a href="https://medium.com/hash-coding/swift-functions-closure-part-i-e339faa51ffc?source=friends_link&amp;sk=6078017d5670ff8bd16f5040e3602f23"><em>Swift — Functions &amp; Closure — Part I</em></a> before we move ahead.</p><p>I know you are consistently following <a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088?source=friends_link&amp;sk=292ce0e0b97002d4d40d06c0a6a1f59d"><em>Hacking the iOS Interview</em></a> preparation series but if somehow you stumbled directly here, I would suggest taking a look at our main story (it host every link in this series).</p><p><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></p><h3><strong>How can you create closures in swift ?</strong></h3><p>A closure is a function combined with any captured variables. And functions can be created using either the func keyword or { } closure expression. But the important thing here is that function has to capture values from outside their local scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3afd9f4ecba931a05d0cd9f8c858559/href">https://medium.com/media/c3afd9f4ecba931a05d0cd9f8c858559/href</a></iframe><p>Usually claps, being a local variable of clapCounter, would go out of scope just after the return statement, and it’d be destroyed. Instead, because it’s captured by innerFunc, the Swift runtime will keep it alive until the function that captured it gets destroyed. We can call the myClaps closure multiple times, and we see that the total number of claps increases.</p><p>This is one way of creating a closure while the other way can be using closure expression {}.</p><h3><strong>What is the capture list and explain output for the code snippets?</strong></h3><p>Closures syntax has a way to specify all constants and variables it wants to capture from the surrounding context in which it’s defined. For this, they use a comma-separated list within [ ] before their parameter list and this is known as a capture list. Values can be captured as either strong, weak and unowned, depending upon the use case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42c6296bed4a420b18e2c952061446e3/href">https://medium.com/media/42c6296bed4a420b18e2c952061446e3/href</a></iframe><p>If no capture list is present in the closure declaration, then the evaluation of all variables of the surrounding context referenced within a closure will be deferred until the closure call happens. This means any change to webSeries before invoking closure will be reflected inside closure.</p><blockquote>In case of an <em>escaping</em> closure, it’ll implicitly capture any objects, values and functions that are referenced within it. Since such closures may be executed at a later time, they need to maintain strong references to all of their dependencies to prevent them from being deallocated in the meantime.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d698d2b44b6b95f74ae260f24752feaf/href">https://medium.com/media/d698d2b44b6b95f74ae260f24752feaf/href</a></iframe><p>The capture list creates a copy webSeries during closure declaration. This means captured value doesn’t change even though you assign a new value to webSeries in the surrounding environment.</p><blockquote>Both functions and closures are reference type. So, if we take a copy of closure, that copy shares the same capturing values as its original.</blockquote><h3>Explain @escaping, @nonescaping and @autoclosure?</h3><p>These attributes are applied to closures passed in as parameters to function. Closure parameters are @nonescaping by default. A non-escape closure tells the compiler that the closure you pass in will be executed within the body of that function and nowhere else. When the function ends, the closure will no longer exist in memory.</p><p>Escaping closures are those whose invocation escapes the scope of the function to which they are passed as an argument. One way they can escape is by being stored in a variable outside of the function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1a5ea6916695ed2c59bd22b1a55936b/href">https://medium.com/media/d1a5ea6916695ed2c59bd22b1a55936b/href</a></iframe><p>completionHandler is assigned in a variable outside function scope and later invoked after the function is returned. As a result, the compiler throws an error demanding to add @escaping before type of completionHandler.</p><p><strong>Line 7 —</strong> <em>Assigning non-escaping parameter ‘completionHandler’ to an </em><em>@escaping closure</em></p><blockquote>An escaping closure that refers to self needs special consideration if self refers to an instance of a class. Capturing self in an escaping closure makes it easy to accidentally create a strong reference cycle.</blockquote><p>@autoclosure attribute enables us to define an argument to a function that gets automatically wrapped within a closure. This resulting closure doesn’t take any parameters and when it’s invoked, it returns the value of the expression that’s wrapped within it. Primarily used to defer the evaluation of an expression until it’s needed, rather than doing it when the argument is passed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed2a5f0c1628314361b8887d12ec2006/href">https://medium.com/media/ed2a5f0c1628314361b8887d12ec2006/href</a></iframe><p>In this implementation of the assert function, 4 &gt; 0 &amp; 4 &lt; 6 expressions will be wrapped in a closure and evaluated only when this closure is invoked instead of while passing them as an argument.</p><h3><strong>Why escaping closures can’t capture mutating self for structs and enums?</strong></h3><p>Within a mutating function, a mutable version of self is provided which is similar to inout parameters to a function. Modifications to this copy of self are written back to the original one when the function returns. If an escaping closure implicitly captures this mutating self and do some changes, those changes won’t be reflected in the original copy and lead to confusion. Similarly inout parameters can’t be captured in an escaping closure. To put this in words of swift proposal <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md">SE-0035</a>,</p><blockquote>Capturing an inout parameter, including self in a mutating method, becomes an error in an escapable closure literal unless the capture is made explicit (and thereby immutable).</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9163ba975760e093676e702b6bd9091f/href">https://medium.com/media/9163ba975760e093676e702b6bd9091f/href</a></iframe><p>We have covered most of the stuff related to closures here. Next story we’ll cover Higher-order functions. Keep following for updates when these parts get published. Drop a comment in case you have an interesting closure interview question.</p><p>I hope you find this story helpful. If you liked it, share this with your community and feel free to give your claps below 👏 to help others find it! Thanks for reading.</p><h3>What’s next to read ?</h3><ul><li><a href="https://medium.com/hash-coding/swift-initialization-4f5bebc26425">Swift — Initialization</a></li><li><a href="https://medium.com/hash-coding/swift-access-control-ios-dab45a0b79ab">Swift — Access Control —  iOS</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <em>Signup Now.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/798368a2c34d2563691b02ab72c25fa2/href">https://medium.com/media/798368a2c34d2563691b02ab72c25fa2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaf240c684d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-functions-closures-part-ii-eaf240c684d6">Swift — Functions &amp; Closures — Part II</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Initialization]]></title>
            <link>https://medium.com/hash-coding/swift-initialization-4f5bebc26425?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/4f5bebc26425</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Shivam Pandey]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 14:29:15 GMT</pubDate>
            <atom:updated>2021-03-08T14:37:32.504Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking the iOS Interview</h4><h3>Swift — Initialization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WUyZHC2-tjHffRInTNidA.png" /></figure><p>Initializations in Swift can be asked in interviews with respect to both structs and classes. While this concept is relatively easier to understand when it comes to structs, however, things can get a bit tricky when answering questions regarding classes. We need to be aware of the 2-phase initialization for classes along with the convenience and designated initializers. Here, I will try to cover the questions which can be asked in the interviews, so make sure to bookmark this post!</p><h3>Difference between convenience vs designated initializers?</h3><p>Both convenience and designated initializers are related to classes. <strong>Designated initializers</strong> initialize all the stored properties of a class and then move up to the superclass to initialize all its properties:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50e20b5da8bcce413caf08fd235870b0/href">https://medium.com/media/50e20b5da8bcce413caf08fd235870b0/href</a></iframe><p>Usually, a class will have only a single designated initializer.</p><p>The<strong> convenience initializer</strong> does not initialize all the stored properties of the class. However, it will rely on other initializers present in the class to initialize the stored properties of that class with some default values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50e4188f4032b38641c6e2c0fdcef078/href">https://medium.com/media/50e4188f4032b38641c6e2c0fdcef078/href</a></iframe><h3>Why are convenience initializers provided, when we already have designated initializers?</h3><p>The convenience initializers act as a secondary initializer, and these are used in those scenarios where it is not required for the caller to provide all the initial values of that class at the time of initialization. The caller will use these initializers to create the instance by providing only some of the stored properties, and the rest of the properties will be initialized with the default values provided inside that same class.</p><h3>Does Swift provide convenience and designated initializers for structs as well?</h3><p>As inheritance is not supported in structs, Swift does not provide convenience and designated initializers for structs. However, a custom initializer in a struct can call other initializers present in the class, and these initializers are called <strong>delegating initializers</strong>.</p><h3><strong>What are delegating initializers?</strong></h3><p>Delegating initializers of a struct are those that call other initializers of the same struct. Delegate initialization is useful when you want to provide an alternate initializer argument list but you don’t want to repeat the logic that is in your custom initializer. Also, using delegating initializers helps reduce the amount of code you have to write.</p><h3>Will the below-given code compile?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3226276dd090eea267424f16baaf391e/href">https://medium.com/media/3226276dd090eea267424f16baaf391e/href</a></iframe><p>It will not compile as a convenience can call another convenience initializer, but eventually, the chain of convenience initializers has to end up with a call to the designated initializer.</p><h3>Explain initializer delegation for class types?</h3><figure><img alt="Swift initializer delegation" src="https://cdn-images-1.medium.com/max/1006/1*ksLncFJ-tPAmGs9CovRlbg.png" /><figcaption>Rules for initializer delegation (source: Swift Docs)</figcaption></figure><p>It becomes easier to remember the initializer delegation rule for class types after seeing the above image. It can be summed up in two categories:</p><ul><li><strong>Convenience initializer delegates across the class:<br></strong>This means that a convenience initializer can only call other initializers from the same class but cannot call the initializers of the superclass.</li><li><strong>Designated initializer delegates up the class hierarchy:<br></strong>It means that it becomes the responsibility of the designated initializer to call the initializers of the superclass so that the stored properties of the parent class can be initialized. <strong>But at the same time, the designated initializer cannot call a convenience initializer of the superclass.</strong></li></ul><h3>Explain Two-Phase initialization in Swift</h3><p>Two-phase initialization in Swift is explained very clearly in <a href="https://docs.swift.org/swift-book/LanguageGuide/Initialization.html">Swift’s official documentation</a>:</p><blockquote>Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.</blockquote><p>This can be seen in the below code example:</p><figure><img alt="Swift two phase initialization" src="https://cdn-images-1.medium.com/max/1024/1*46BccwD9vXpvgHj87fgQsA.png" /><figcaption>Example showing Swift’s two-phase initialization</figcaption></figure><h3>What are the compiler rules to support two-phase initialization?</h3><p>There are four rules, which if not satisfied, the compiler will not let the code compile. These are important because it helps in preventing the accessing the store properties before they are initialized. The rules can be summarised as below:</p><ul><li>A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.</li></ul><figure><img alt="Example showing Swift’s two phase initialization’s safety rule" src="https://cdn-images-1.medium.com/max/1024/1*Wu9VYm25t7FfAqEi-DJx0g.png" /><figcaption>super.init(…) is not allowed to be called until all the properties of the Employee class has been initialized.</figcaption></figure><ul><li>A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn’t, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQniqKomuw9vSsE38svmWg.png" /><figcaption>self.name is not allowed to be accessed before calling super.init(…)</figcaption></figure><ul><li>A convenience initializer must delegate to another initializer before assigning a value to <em>any</em> property (including properties defined by the same class). If it doesn’t, the new value the convenience initializer assigns will be overwritten by its own class’s designated initializer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lRxL3ym_2qSV83rKj9J1A.png" /><figcaption>self.profile is not allowed to be assigned before calling another initializer from the convenience initializer</figcaption></figure><ul><li>An initializer can’t call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4KKIR9AKEBmCNfbKSWWgA.png" /><figcaption>getEmployee() method cannot be called until the 1st phase of initialization is complete</figcaption></figure><h3>What are memberwise initializers?</h3><p>I have explained the answer to the above question in my earlier post: <a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd#7e84">Swift — Structs vs Classes — Part I</a>. You can refer to the same, and can also go through the other interview questions based on structs vs classes in the same post.</p><h3>What are failable initializers?</h3><p>There can be certain situations, which if not satisfied, should not result in the formation of a concrete instance — be it a class, a struct, or an enum.</p><h4>The interviewer can give you a situation based on the Employee class. He can ask to design a code in such a way that the caller cannot initialize the Employee instance if the age of the employee is less than 18 or greater than 60.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f897765830aa64df25ea97e0f58554c7/href">https://medium.com/media/f897765830aa64df25ea97e0f58554c7/href</a></iframe><p>We can add a failable initializer to the Employee class as given below in the example:</p><figure><img alt="Example showing Swift’s failable initializer" src="https://cdn-images-1.medium.com/max/1024/1*atr6rg2og0HlE7G9Dc9gdQ.png" /></figure><h3>What are required initializers?</h3><p>Required initializers are those initializers that are supposed to be overridden by each and every subclass of that class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoXw7Ij2NiCRChehWCYrPw.png" /><figcaption>The Citizen class gives an error as it has not implemented the required initializer from its superclass</figcaption></figure><p>Next, following up on the required keyword, the interviewer can ask about the explanation of the error shown in the below code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xh-K5Vu9heCy0oNb-E18tw.png" /></figure><p>You must have observed that when you create a subclass of UIView, the compiler forces you to implement <em>init(coder:). </em>When you create the CustomView’s instance using Interface Builder, the method <em>init(coder:) </em>is called so that any custom initialization can be done here.</p><p>I hope you find this story helpful. If you enjoyed it, share this with your community, and feel free to hit the clap button below 👏 to help others find it! Thanks for reading. 👍</p><h3>What’s next to read?</h3><ul><li><a href="https://medium.com/hash-coding/swift-access-control-ios-dab45a0b79ab">Swift — Access Control —  iOS</a></li><li><a href="https://medium.com/hash-coding/swift-structures-and-classes-part-ii-b319998c5b7e">Swift — Structures and Classes — Part II</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <strong><em>Subscribe Now</em></strong><em>.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding%2F&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href">https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5bebc26425" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-initialization-4f5bebc26425">Swift — Initialization</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Access Control —  iOS]]></title>
            <link>https://medium.com/hash-coding/swift-access-control-ios-dab45a0b79ab?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/dab45a0b79ab</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Neha Bansal]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 03:35:28 GMT</pubDate>
            <atom:updated>2021-03-03T04:07:35.837Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking The iOS Interview</h4><h3>Swift — Access Control</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufyLiRdRxDh26HVNUY-P5w.jpeg" /></figure><p>Access controls are mostly asked when you are halfway through your technical interview. The interviewer wants to know whether you can identify critical pieces in your code and whether you ensure that those code pieces are hidden or exposed accordingly to other parts of your codebase.</p><h3><strong>What are Access Controls in Swift?</strong></h3><p>Swift provide five different types of access controls within your code. These access levels restrict access to parts of your code from code in other source files and modules. These are relative to the source file in which any entity can define(<strong>entity</strong> e.g properties, methods, types and so on, and <strong>module</strong> e.g which can be shipped as a single unit in an application such as target or any framework).</p><ul><li><strong><em>Open</em></strong><em> — </em>This is where you can access all data members and member functions within the same module(target) and outside of it. You can subclass or override outside the module(target).</li><li><strong><em>Public</em></strong><em> — </em>This is the same as <strong><em>open</em></strong>, the only difference is you can’t subclass or override outside the module(target).</li><li><strong><em>Internal</em></strong><em> — </em>This is the default access level in Swift, it allows all data members and member functions to be accessed within the same module(target) only and restrict access outside the module(target).</li><li><strong><em>Private — </em></strong>This is where you can access data members and function within its enclosing declaration as well as an extension within the same file. It does not allow access in a subclass with in the same file or in another file.</li><li><strong><em>File-private -</em></strong><em> </em>This is the same as <em>private</em>, the only difference is it allows access in a subclass with in the same file.</li></ul><h3>What is the default access level in swift?</h3><p>If we don’t mention an access level before any entity, it is <strong><em>internal</em></strong> by default. It’s explained in the above section.</p><h3>Access Modifier Comparison</h3><p>The interviewer generally ask you the differences between various access modifiers, for example:</p><ul><li><strong><em>open</em></strong> vs <strong><em>public</em></strong></li><li><strong><em>public</em></strong> vs <strong><em>internal</em></strong></li><li><strong><em>private</em></strong> vs <strong><em>fileprivate</em></strong></li></ul><h3>Explain the difference between Open vs Public — (least restrictive)</h3><p><strong><em>public - </em></strong>you cannot subclass <strong><em>public</em></strong> entity outside the module(target) but in <strong><em>open</em></strong> you can inherit a class or override a method.</p><p>When using <strong><em>public</em></strong> modifier while creating a class inside a framework, we can not inherit that class inside another module(target) as can be seen in the below given example:</p><figure><img alt="public access modifier example in Swift" src="https://cdn-images-1.medium.com/max/1024/1*dwuTRI_-D0yvVlYp4aYaKQ.png" /><figcaption>NetworkManager.swift class inside a framework</figcaption></figure><p>Now In the below example, we have NetworkFramework imported in the app’s target and we try to subclass the NetworkManager into loginNetworkManager</p><figure><img alt="Public access modifier gives an error when trying inherit a class outside the module" src="https://cdn-images-1.medium.com/max/1024/1*PPk8k6Umht4sTsRiNByf6A.png" /><figcaption>LoginNetworkManager.swift class in a separate module(module can be app target or any other framework)</figcaption></figure><p>Similarly, while using <strong><em>public</em></strong> methods in another module it will give the compiler error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xc_Xz3YbKJxCLE8zMWiRbQ.png" /><figcaption>LoginNetworkManager.swift class in a separate module with the public function</figcaption></figure><p>As we can see the compiler gives an error. To remove this error we will have to upgrade the access modifier from <strong><em>public</em></strong> to <strong><em>open</em></strong>. Now it will work fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Td_vWriAx8OtIoVutu-hSQ.png" /></figure><p>You can be asked to write the code as shown in the above example in the interview.</p><h3>Explain the difference between Internal vs Public?</h3><p><strong>Public — </strong>access enables data members to be used within any source file from their defining module, <strong>and also in a source file from another module that imports the defining module</strong></p><p><strong>Internal</strong> — access enables entities to be used within any source file from their defining module, but <strong>not in any source file outside of that module</strong>.</p><h4><strong>When should we use the internal access level?</strong></h4><p>When we want to create a framework in which we don’t want to allow classes and their entities to be accessed<strong> </strong>from other framework or module then <strong><em>internal</em></strong> plays an important role. This can be explained more clearly to the interviewer using an example like the one given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nAyv4ybk9JkBLqhRlZwaw.png" /><figcaption>NetworkManager.swift class inside the framework with default access level</figcaption></figure><p>Now, if we try to use this class in any other module then it will generate compiler error as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQwvFHvP6rglJeKbm3N24w.png" /><figcaption>LoginNetworkManager.swift class in any other target</figcaption></figure><h3>Explain the difference between Private vs Fileprivate — (most Restrictive)</h3><p>We should explain the difference using the below cases with a real example:</p><h4><strong>private — </strong>Allow<strong> </strong><em>access data members and function within its enclosing declaration as well as an extension within the same file</em></h4><p><strong>Case 1</strong>: <strong>Within the same source file</strong>, if property or function is declared as <strong><em>private</em></strong> in class — then the scope is by default the class and extension of that class only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrSWDFtVjl--ekXdkEC8Yw.png" /><figcaption>NetworkManager.swift which declared properties and function as private access level</figcaption></figure><h4><strong><em>So, can we access data members inside the subclass?</em></strong></h4><p>No, the subclass is not allowed to access those data members defined in the superclass within the same source file as shown above.</p><p><strong>Case 2</strong>: <strong>In the different source file</strong>, If property or function is declared as <strong><em>private</em></strong> in one source file and access within extension/subclass in another source file — <strong>access not allowed</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0rgdZndENBtSCegoMIUjQ.png" /><figcaption>NetworkUtility.swift file which creates an extension of NetworkManager class and accesses private data members here</figcaption></figure><p>So here, we have seen the compiler error which clearly says “<em>properties are inaccessible due to </em><strong><em>private</em></strong><em> protection level</em>” now we can resolve this error by using <strong><em>fileprivate</em></strong>. Let’s see an example:</p><h4><strong>filePrivate — Allow access data members and functions within the same source file either in subclass or extensions</strong></h4><p><strong>Case 1</strong>: <strong>Within the same source file</strong>, If we create an extension or subclass with in the same class file and try to access <strong><em>fileprivate</em></strong> entity in its extension/Subclass — <strong>access allowed</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBXwOsDG-LhqUh48PEYVOg.png" /><figcaption>NetworkManager.swift class with properties and functions declared as file private and accessed in subclass and extensions.</figcaption></figure><p>So as seen in the <strong><em>private</em></strong> access level there was an error while created subclass within the same source file here we have resolved that error by declared data members as <strong><em>fileprivate.</em></strong></p><p><strong>Case 2</strong>: <strong>In the different source file, <em>fileprivate</em> </strong>behaves the same as the <strong><em>private</em></strong> modifier as shown in the below example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfrMCJpy7wJf3fsO0KdODA.png" /></figure><p>Here, the compiler error is generated as <strong><em>fileprivate</em></strong> says that you can access the data members within the same file in which they are declared while <strong><em>private</em></strong> says that you can only access data members within enclosing declaration scope and extensions.</p><h3>Where can we apply access levels?</h3><p>The interviewer can ask this question in a way that can we use modifiers in enum or struct?</p><ul><li>Classes, structs, enumerations, protocols</li><li>Properties, functions, computed properties and subscripts</li><li>Custom types, and nested types</li></ul><h3>How do Access levels work with tuple?</h3><blockquote>Tuple types don’t have a standalone definition in the way that classes, structures, enumerations, and functions do. A tuple type’s access level is determined automatically from the types that make up the tuple type, and can’t be specified explicitly.</blockquote><p>Let’s see the example in which we try to show you that tuple considered as one of the properties in the class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPEcFGy_-HGRWgfZlJb5mw.png" /><figcaption>NetworkManager.swift class which declared tuple as private access level</figcaption></figure><p>It clearly says that all the member inside tuple determined automatically with the same type which declared in the property</p><p><em>The below question can be asked in multiple-choice type questions:</em></p><p><strong>For example, if you compose a tuple from two different types, one with <em>internal</em> access and one with <em>private</em> access then what will be the access level of that tuple?</strong></p><blockquote>The access level for that compound tuple type will be <strong>private</strong>.</blockquote><p>Because the most restrictive access level is applied in that case to compound tuple so in this case <strong><em>private</em></strong> is the most restrictive access level.</p><p>I hope you find this story helpful. If you enjoyed it, share this with your community and feel free to hit the clap button below 👏 to help others find it! Thanks for reading. 👍</p><h3>What’s next to read?</h3><ul><li><a href="https://medium.com/hash-coding/swift-functions-closure-part-i-e339faa51ffc">Swift  —  Functions &amp; Closure  —  Part I</a></li><li><a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd">Swift — Copy-On-Write Optimization</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <strong><em>Slide to Subscribe Now.</em></strong> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/798368a2c34d2563691b02ab72c25fa2/href">https://medium.com/media/798368a2c34d2563691b02ab72c25fa2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dab45a0b79ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-access-control-ios-dab45a0b79ab">Swift — Access Control —  iOS</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift  —  Functions & Closure  —  Part I]]></title>
            <link>https://medium.com/hash-coding/swift-functions-closure-part-i-e339faa51ffc?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/e339faa51ffc</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jayant Kumar Yadav]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 05:06:44 GMT</pubDate>
            <atom:updated>2021-03-03T04:14:27.046Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking The iOS Interview</h4><h3>Swift — Functions &amp; Closures — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rYQgbHgDJvLzH-jx" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaryanphoto?utm_source=medium&amp;utm_medium=referral">Joshua Reddekopp</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the favourite topics for an interviewer when it comes to finding an interviewee’s swift knowledge. A good grip on functions, closures and higher-order function related concept will provide you with an edge. This discussion would most probably open with a question of the difference between function and closure. Let’s start with the same.</p><h3><strong>What are functions and closures in swift ?</strong></h3><p>Functions are a self-contained piece of code that performs a specific task. They are referred to as first-class objects. Every function has a type, consisting of its parameter types and return type, which makes it easy to pass functions as parameters to other functions and to return functions from functions. They can be nested to encapsulate functionalities within other functions.</p><p>A combination of a function and an environment of captured variables is called a closure. They can capture and store references to any constants and variables from the context in which they’re defined. This is known as <em>closing over</em> those constants and variables. They are usually unnamed functions.</p><h3>What is the closure expression ?</h3><p>There are two ways of creating functions — either with the <em>func</em> keyword or with <em>{}</em>. Swift calls the later closure expressions. <em>{} </em>are a way to write inline functions in a brief, focused syntax. Closure expressions provide several syntax optimizations for writing functions in a shortened form without loss of clarity or intent.</p><blockquote>Closure expressions <em>{ }</em> can be thought of as function literal in the same way that <em>[ ]</em> and <em>[ : ]</em> are array and dictionary literal.</blockquote><p>Here’s an extract from the book <a href="https://www.objc.io/books/advanced-swift/">Advanced Swift by objc.io</a> —</p><blockquote>Remember, a closure is a function combined with any captured variables. While functions created with <em>{ }</em> are called closure expressions, people often refer to this syntax as just closures. But don’t get confused and think that functions declared with the closure expression syntax are different from other functions — they aren’t. They’re both functions, and they can both be closures.</blockquote><h3><strong>How closure expressions help brevity in swift ?</strong></h3><p>They use various compiler level inferences and shorthands to minimize the code to write while maintaining the intent. Let’s take an example of this simple function twice which returns double of its argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/578b35645fd2ca3221774b650f0dd17b/href">https://medium.com/media/578b35645fd2ca3221774b650f0dd17b/href</a></iframe><p>And here’s the same function is written using the closure expression syntax. Just like before, we can pass it to the map.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca88097ec9f9ed2774e849a394e973f7/href">https://medium.com/media/ca88097ec9f9ed2774e849a394e973f7/href</a></iframe><p>Closure expression syntax can be a lot more compact, we can boil down the above statements to its shortest form possible. Remember the rules against each step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea973051a364e40921280281655e93f/href">https://medium.com/media/bea973051a364e40921280281655e93f/href</a></iframe><h3>What would be the output of the following code ?</h3><pre>let someFunction = { $0 + $1 }</pre><p>This will show an error because the compiler is not able to infer the types of parameters. If you want to assign closure expressions to a variable, and the compiler is not able to infer types, this is when you’d have to lock down which specific types it’s operating on. A variable can’t hold a generic function — only a specific one.</p><pre>let someFunction: (Int, Int) -&gt; Int = { $0 + $1 }</pre><blockquote>Function parameters are constants by default we can’t mutate them directly. If you haven’t read <a href="https://medium.com/hash-coding/swift-let-vs-var-b2a74e098c2a?source=friends_link&amp;sk=db78eee92d8220d927b1a6bb160bae45">Swift — let vs var</a> story, then it’s time to pause and have a look.</blockquote><h3>What is wrong with this code snippet ?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cab37e30933b7b79d9ad0da8c392761/href">https://medium.com/media/1cab37e30933b7b79d9ad0da8c392761/href</a></iframe><p>You can only pass a variable as the argument for an in-out parameter. This makes sense because we’re not allowed to mutate let variables.</p><p><strong>Line 7 —</strong> <em>Cannot pass immutable value as inout argument: ‘currentClaps’ is a ‘let’ constant</em></p><p>Furthermore, in-out is pass-by-value-and-copy-back, not pass-by-reference. They are an alternative way for a function to affect outside of the scope of its body. To quote The Swift Programming Language —</p><blockquote>An in-out parameter has a value that’s passed <em>into</em> the function, is modified by the function, and is passed back <em>out</em> of the function to replace the original value.</blockquote><blockquote><strong>In-out parameters can’t have default values, and variadic parameters can’t be marked as in-out.</strong></blockquote><h3><strong>Explain the issues with the below code snippet ?</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7df74581175f048fc687d9b007c976aa/href">https://medium.com/media/7df74581175f048fc687d9b007c976aa/href</a></iframe><p>You can use an inout parameter inside nested functions, but Swift will make sure your usage is safe. For instance, you can define a nested function (either using <em>func</em> or using a <em>closure expression</em>) and safely mutate an inout parameter. However, you’re not allowed to let that inout parameter escape. This makes sense, given that the inout value is copied back just before the function returns. If we could somehow modify it later, what should happen? Should the value get copied back? What if the source no longer exists? Having the compiler verify this is critical for safety.</p><p><strong>Line 7</strong> — <em>Escaping closure captures ‘inout’ parameter ‘claps’</em></p><h3><strong>Why argument labels aren’t required in the function call when it is assigned to some variable ?</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c3fb3d5c9e5ac732d50c634c68e05c0/href">https://medium.com/media/2c3fb3d5c9e5ac732d50c634c68e05c0/href</a></iframe><p>We must not include an argument label in the <em>addTwoNumbers</em> call, whereas <em>add</em> call requires the argument label. Swift only allows argument labels in function declarations; the labels aren’t included in a function’s type. This means that you currently can’t assign argument labels to a variable of a function type, though this will <a href="https://forums.swift.org/t/update-commentary-se-0111-remove-type-system-significance-of-function-argument-labels/3391">likely change in a future Swift version</a>.</p><p>That’s mostly everything on functions in swift. The next part of this story will revolve around closures and after that one more part on Higher-order functions. Keep following for updates when these parts get published. In case you come across other important question do let me know in the response section.</p><p>I hope you find this story helpful. If you liked it, share this with your community and feel free to give your claps below 👏 to help others find it! Thanks for reading.</p><h3>What’s next to read ?</h3><ul><li><a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd">Swift — Copy-On-Write Optimization</a></li><li><a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd">Swift — Structures and Classes — Part 1</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <em>Signup Now.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding%2F&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href">https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e339faa51ffc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-functions-closure-part-i-e339faa51ffc">Swift  —  Functions &amp; Closure  —  Part I</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Copy-On-Write Optimization]]></title>
            <link>https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/46b1890862dd</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Shivam Pandey]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 12:07:43 GMT</pubDate>
            <atom:updated>2021-03-09T01:38:06.961Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking the iOS Interview</h4><h3>Swift — Copy-On-Write Optimization</h3><figure><img alt="Swift — Copy-On-Write Optimization" src="https://cdn-images-1.medium.com/max/1024/1*TZCWfdsfcBIxMGtFphzzVg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrew Neel</a> on <a href="https://unsplash.com/s/photos/blogging?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This concept can be asked as a follow-up question when discussing structs vs classes in Swift. If you haven’t gone through my previous posts on Structs and Classes, you can find them here: <a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd?source=friends_link&amp;sk=f448269d56f82222da1f5d4356e9a5ef">Part I</a> and <a href="https://medium.com/hash-coding/swift-structures-and-classes-part-ii-b319998c5b7e?source=friends_link&amp;sk=2e947f4fb456dd325d1318450da32c22">Part II</a>.</p><h3>What is Copy-on-Write Optimization in Swift?</h3><p>As we know that value types can only have a single owner, therefore they need to be copied every time they are passed around. When we have a value type containing a lot of data, copying them each time (even when passing around) can lead to a lot of memory consumption. To mitigate this downside, the Swift compiler adds an optimization called c<em>opy-on-write</em>.</p><p>Using c<em>opy-on-write, </em>the compiler does not go on creating copies of the objects when they are merely being passed around among multiple variables, <strong>unless and until</strong> a variable tries to modify the data.</p><h3>Write some code to explain Copy on Write using an example</h3><p>Swift arrays implement c<em>opy-on-write </em>optimization, which means if we create an array and simply assign it to another variable (without any of the variables modifying the array), both the arrays will share the same reference to the underlying data.</p><figure><img alt="Copy on Write in Swift" src="https://cdn-images-1.medium.com/max/1024/1*mPQCKyEAF1KLcyLw0zorWQ.png" /><figcaption>Code example depicting copy-on-write in Swift</figcaption></figure><p>In the above example, we can see in the logs printed in the console that the memory address of both the arrays — <em>arr1</em> and <em>arr2</em> are the same.</p><p>Now when <em>arr2</em> modifies the contents of the array, its memory address is updated and the memory address of arr1 remains the same as the previous one.</p><figure><img alt="Copy on Write in action in Swift" src="https://cdn-images-1.medium.com/max/1024/1*--2UWQNX1P_WFdFFQDOoYw.png" /><figcaption>Address of arr2 has changed after modifying the array</figcaption></figure><h3>Is there any disadvantage of Copy on Write?</h3><p>Since <em>value types</em> can only have a single owner, they don&#39;t have to incur the overhead of reference counting. But, the <strong>Copy on Write </strong>value types needs to internally maintain a reference count to be aware of the number of copies being created of that value. When a new copy is created, the internal reference count is also incremented.</p><p>Updating the reference count is a slow operation because it has to be thread-safe, and to achieve that, locking mechanisms are implemented internally, which have their own costs. Thus, if we are not careful, the performance can be adversely affected.</p><p>Let&#39;s consider the below-given sample code containing a struct called <em>MediaItem</em> which contains a string, a dictionary, and an array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1454205c0fe2a5e3e7faf6e8116c6ed/href">https://medium.com/media/e1454205c0fe2a5e3e7faf6e8116c6ed/href</a></iframe><p>When passing this MediaItem’s objects around, the internal reference count of all the properties have to be maintained. This overhead will result in a decrease in performance.</p><h3>How to implement Copy on Write for custom value types?</h3><p>Following up on the above example of the MediaItem struct, we can make some changes in the code to reduce the overhead.</p><p>We can wrap the properties inside a private MediaData class as shown in the example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d42d4e25e0a27e79e3bfff2fde0d8297/href">https://medium.com/media/d42d4e25e0a27e79e3bfff2fde0d8297/href</a></iframe><p>By wrapping the properties inside a class, the struct now has to maintain a single internal reference count when making a copy.</p><p>We can add new computed properties to expose <em>name</em> and <em>data, </em>and can be achieved using the below approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6892c762f49b39ba91c5b0365482e668/href">https://medium.com/media/6892c762f49b39ba91c5b0365482e668/href</a></iframe><p>Using the above implementation we can achieve Copy-on-Write for our custom value types.</p><p>We have used a not-so-commonly-used method here of the <a href="https://developer.apple.com/documentation/swift/2429905-isknownuniquelyreferenced">Swift Standard Library</a>:</p><blockquote><a href="https://developer.apple.com/documentation/swift/2429905-isknownuniquelyreferenced"><strong>isKnownUniquelyReferenced(_:)</strong></a><strong><br></strong>Returns a Boolean value indicating whether the given object is known to have a single strong reference.</blockquote><p>This method is used to efficiently check the Copy on Write implementation, as we need to know if the object has a single owner. If it doesn’t, we create a copy of the object before modifying it.</p><p>I hope you find this story helpful. If you enjoyed it, share this with your community, and feel free to hit the clap button below 👏 to help others find it! Thanks for reading. 👍</p><h3>What’s next to read?</h3><ul><li><a href="https://medium.com/hash-coding/swift-initialization-4f5bebc26425">Swift — Initialization</a></li><li><a href="https://medium.com/hash-coding/swift-access-control-ios-dab45a0b79ab">Swift — Access Control —  iOS</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <em>Signup Now.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding%2F&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href">https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46b1890862dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd">Swift — Copy-On-Write Optimization</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking The iOS Interview]]></title>
            <link>https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/f1dc9fec8088</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jayant Kumar Yadav]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 06:01:16 GMT</pubDate>
            <atom:updated>2025-03-31T15:52:40.250Z</atom:updated>
            <content:encoded><![CDATA[<h4>Prepare for the best 🤟</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMapWfGWE1a_VIWVfFFXqQ.png" /></figure><p>No matter how good you’re at iOS development, interviews are always stressful. It’s hard to prepare and gather all resources over the internet. Furthermore, you never know what the interviewer will ask you. It always feels like there’s so much to prepare and you’re nowhere near the level needed to clear interviews. <strong>Is this your feeling? Don’t worry.</strong></p><p>We have planned to curate this iOS interview preparation series to propagate those experiences that we got through tons of our interviews and gathered from our network. This includes companies like <strong>Flipkart</strong>, <strong>Walmart</strong>, <strong>Citrix</strong>, <strong>InMobi</strong>, <strong>Directi</strong>, <strong>Expedia</strong>, <strong>Gojek, PhonePe </strong>and many more to count. So, whether you’re the one looking to take the next step in your career, or whether you’re the one who is trying to hire someone in your team, I hope this series will have something you both can learn.</p><blockquote>As they say, not every series is available on Netflix. Some exist on Medium.</blockquote><p>We have questions ranging from basic Swift to expert level concepts of iOS development, architectures, design patterns and system design. We will try to cover all, just bear with us.</p><h3>Swift</h3><ul><li><a href="https://medium.com/hash-coding/swift-let-vs-var-b2a74e098c2a?source=friends_link&amp;sk=db78eee92d8220d927b1a6bb160bae45">let vs var</a></li><li>Structs &amp; Classes — <a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd?source=friends_link&amp;sk=f448269d56f82222da1f5d4356e9a5ef">Part I</a>, <a href="https://medium.com/hash-coding/swift-structures-and-classes-part-ii-b319998c5b7e?source=friends_link&amp;sk=2e947f4fb456dd325d1318450da32c22">Part II</a></li><li><a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd?source=friends_link&amp;sk=00c22f41fb00937c685c0182585f71e2">Copy-on-Write</a></li><li>Functions &amp; Closures — <a href="https://medium.com/hash-coding/swift-functions-closure-part-i-e339faa51ffc?source=friends_link&amp;sk=6078017d5670ff8bd16f5040e3602f23">Part I</a>, <a href="https://medium.com/hash-coding/swift-functions-closures-part-ii-eaf240c684d6">Part II</a></li><li>Inheritance<strong> [ coming soon ]</strong></li><li><a href="https://medium.com/hash-coding/swift-access-control-ios-dab45a0b79ab?source=friends_link&amp;sk=8d19f744751c4e732b028af74e934e0e">Access Control</a></li><li><a href="https://medium.com/hash-coding/swift-initialization-4f5bebc26425?source=friends_link&amp;sk=754073d3df0b5240f092d8d3ec33fae7">Initialization</a></li><li>Protocols <strong>[ coming soon ]</strong></li><li>Generics <strong>[ coming soon ]</strong></li></ul><p>These are the kinds of questions we were asked but remember that different companies interview in different ways so your experience may vary. But at the least, this series makes sure you will be well prepared before going to an interview. That’s for sure. 👍</p><blockquote>Every interview deserves its own unique experience.</blockquote><p>We hope this curated iOS interview preparation series will help you land your dream job! We’ll be glad to hear your stories. Do share them with us.</p><p>Save this story on your medium and share it with your friends, help them find this great resource for their iOS interview preparation. <strong>Isn’t it what good friends do?</strong></p><blockquote><em>Claps on the medium are token of appreciation. They don’t have Bitcoin.</em></blockquote><p>If you have any queries or suggestions, drop them below in the response. We’ll be more than happy to help you out.</p><p>Thanks, <a href="https://medium.com/u/9acae567b29b">Shivam Pandey</a>!</p><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <em>Signup Now.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding%2F&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href">https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1dc9fec8088" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Structures and Classes — Part II]]></title>
            <link>https://medium.com/hash-coding/swift-structures-and-classes-part-ii-b319998c5b7e?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/b319998c5b7e</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Shivam Pandey]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 17:02:54 GMT</pubDate>
            <atom:updated>2021-03-03T04:16:09.352Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking the iOS Interview</h4><h3>Swift — Structs and Classes — Part II</h3><figure><img alt="Swift struct vs class interview questions" src="https://cdn-images-1.medium.com/max/1024/1*erVqlTKQ7b1wnZhdBRMNKQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fotis Fotopoulos</a> on <a href="https://unsplash.com/s/photos/software?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this post, I will continue with some advanced questions related to structs vs classes in Swift. These become important topics in the iOS interviews as if we are not careful using these, then this can unintentionally lead to memory leaks as well as crashes in the app.</p><p>In case you missed the previous part, you can find it here: <a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd">Swift — Structs and Classes — Part I</a>.</p><h3><strong>Explain the lifecycle of struct vs class in Swift?</strong></h3><p>Understanding the lifecycle of structs and particularly classes become very important as the interviewer can ask about those scenarios which can lead to unintentional performance bottlenecks and crashes in the app.</p><h4>Structs</h4><p><em>Structs</em> are value types, and so they don’t have multiple owners and therefore their lifecycle is relatively easier to maintain. Their lifetime is bounded to the lifetime of the variable containing the struct. The struct’s memory will be freed when the variable goes out of scope.</p><h4>Classes</h4><p><em>Classes</em> can have multiple owners, therefore Swift uses ARC to keep track of the number of references to a particular instance. The Swift runtime calls the object’s deinit when the <em>reference count</em> becomes zero and the memory is freed.</p><h3>Explain strong reference cycles in Swift</h3><p><em>Reference cycles </em>occur when two objects hold strong references to each other, and because of which both the objects never get deallocated, and thus cause memory leaks. Structs do not face this problem because being value types, there are no references to structs. But while dealing with classes we need to be careful about creating unintentional reference cycles.<br>We can see the example of a strong reference cycle in the below example, where there is a Parent-Child relationship.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/087983a5f24933000bfd0f2618368b06/href">https://medium.com/media/087983a5f24933000bfd0f2618368b06/href</a></iframe><p>You can be asked to write some code similar to the above example to show a scenario in which a reference cycle can happen.</p><p>In <strong><em>line 27 and 28</em></strong> even after setting both parent and child to <em>nil</em>, the deinit’s of both the objects are not called denoting that there is a memory leak. This happens because the reference count of both parent and child never goes down to 0.</p><p>To solve this problem, Swift has provided us with two options — <br><strong><em>weak </em>and<em> unowned</em></strong><em>.</em></p><h3>Weak vs Unowned in Swift?</h3><h4>Explain weak references</h4><p>In the above example, we can break the reference cycle by making the child’s reference to the parent as <em>weak</em>. Assigning an object to a <em>weak</em> variable doesn&#39;t change its reference count.</p><p><em>Weak</em> references must always be optional as the variable will automatically be set to <em>nil</em> once the referred object gets deallocated. We can correct the above code by making the parent property in the Child class as <em>weak.</em></p><figure><img alt="Swift strong reference cycle example" src="https://cdn-images-1.medium.com/max/1024/1*sDIjYoWZ0sTILegqxWLehQ.png" /><figcaption>Both the deinits are called when using <em>weak</em> reference</figcaption></figure><p>The <em>weak</em> references are generally used in delegate patterns in iOS.</p><h4>Explain <strong>Unowned References</strong></h4><p>There can be certain situations where we want a non-strong reference that is not optional. For example, the child should always have a parent associated with it. Here, we can use the <em>unowned</em> keyword.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfed159fdc8d3f125429acefdaf3bfbb/href">https://medium.com/media/bfed159fdc8d3f125429acefdaf3bfbb/href</a></iframe><p>When using <em>unowned</em>, we have to ensure that the parent outlives the child. If the parent gets deallocated before the child, and the unowned variable is tried to be accessed, the program will crash.</p><blockquote>This is because the Swift runtime keeps a second reference count in the object to keep track of unowned references. When all the strong references are gone, the object will release all of its resources (for example, any references to other objects). However, the memory of the object itself will still be there until all unowned references are gone too. The memory is marked as invalid ( also called zombie memory), and any time we try to access an unowned reference, a runtime error will occur.</blockquote><h3>What to choose between unowned vs weak?</h3><ul><li>If we can ensure the parent is going to outlive the child, then we can choose the <em>unowned</em> reference. This will also give us the option to use that <em>unowned</em> reference as a <em>let-constant</em> as with <em>weak</em> reference we can only use an <em>optional-var.</em></li><li>If we cannot guarantee the lifetime of both or either of the references then we should use a <em>weak </em>reference, as <em>unowned</em> can cause the program to crash if we try to access that reference that has no other strong reference attached to it.</li></ul><p>These are the major concepts and questions which can be asked in interviews. For additional information, you can always refer to the <a href="https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html">official Swift documentation for structures and classes</a>.</p><p>If you like the content, save it on medium and share it with your iOS community and help us reach a larger audience who could use this. You can appreciate it as well. Clap or <strong>C<em>laps</em></strong><em>. 👏 👏</em></p><h3>What’s next to read?</h3><ul><li><a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd">Swift — Copy-On-Write Optimization</a></li><li><a href="https://medium.com/hash-coding/swift-functions-closure-part-i-e339faa51ffc">Swift  —  Functions &amp; Closure  —  Part I</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <em>Signup Now.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding%2F&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href">https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b319998c5b7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-structures-and-classes-part-ii-b319998c5b7e">Swift — Structures and Classes — Part II</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Structures and Classes — Part 1]]></title>
            <link>https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/582e26bdf8dd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Shivam Pandey]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 07:25:53 GMT</pubDate>
            <atom:updated>2021-03-03T04:16:39.873Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking the iOS Interview</h4><h3>Swift — Structs vs Classes — Part I</h3><figure><img alt="Swift struct vs class interview questions" src="https://cdn-images-1.medium.com/max/1024/1*5FWohaERnEU4L0YL-BXBHw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Distel</a> on <a href="https://unsplash.com/s/photos/software?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This forms a very common question for almost all iOS interviews. This is because it plays a significant role in choosing the right abstraction mechanism keeping both performance and modeling in mind. Questions can range from areas covering consistency of data as well as the performance of the app.</p><h3><strong>What are structs and classes?</strong></h3><p><em>Structs</em> and <em>classes</em> are like a template or prototype that contains the variables and the methods common to all objects of that kind. These help in keeping the code organized for easier maintenance and reusability.</p><h3>What are class only features in Swift as compared to structs?</h3><ul><li><strong>Inheritance:</strong> a class can inherit the characteristics of another class.</li><li><strong>Type-casting:</strong> helps in checking and interpreting the type of a class instance at runtime.</li><li><strong>Deinitializers:</strong> enable an instance of a class to free up any resources it has assigned.</li><li><strong>Reference counting:</strong> allows more than one reference to a class instance.</li></ul><h3><strong>What are value types vs reference types?</strong></h3><ul><li><strong>Value types: </strong>Each instance keeps an independent copy of its data, for example — structs, enums or tuples. Changing one instance will have no effect on the other.</li><li><strong>Reference types:</strong> Instances share a single copy of the data. Changing data in one instance will change the data for all the instances pointing to the same instance, for example — classes.</li></ul><h3><strong>When to use struct vs class in Swift?</strong></h3><p>When creating a new model, we need to carefully contemplate the use cases of the model. Based on this, we should decide between structs and classes.</p><h4><a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd#b53b">Use structs when:</a></h4><ul><li><strong>Comparing instance data with == makes sense<br></strong>This means when only data needs to be compared, and memory locations of these data are not important.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af1cac8903a4c3d115ca06b79919b5a9/href">https://medium.com/media/af1cac8903a4c3d115ca06b79919b5a9/href</a></iframe><p>In the above example, it is important to compare the value of the NetworkRequest’s urls and not the memory addresses.</p><ul><li><strong>You want copies to have an independent state<br></strong>Take the above example and modify it a little by assigning <em>request1</em> to <em>request2, </em>and changing the url of request2 only.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e0780737e69eebd4aa7fd1ad96990f0/href">https://medium.com/media/6e0780737e69eebd4aa7fd1ad96990f0/href</a></iframe><p>We can see that both the requests have different urls as each request have a different copy of the urls.</p><ul><li><strong>The data will be used in code across multiple threads<br></strong>When passing and copying the value types in a multi-threaded environment we can be sure that each context will have a separate unique copy which will not impact the others. This can help avoid a lot of unintentional bugs.</li></ul><h4><a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd#b53b">Use classes when:</a></h4><ul><li><strong>Comparing instance identity with === makes sense</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6c6b2b08fbe3fb608ad5f153ae8b95e/href">https://medium.com/media/b6c6b2b08fbe3fb608ad5f153ae8b95e/href</a></iframe><ul><li><strong>You want to create a shared, mutable state<br></strong>If we want to share the state among the threads and variables then use classes.</li></ul><h3><strong>Where are structs and classes allocated in memory?</strong></h3><p>Structs are allocated in the <em>stack</em> memory. <br>References of the class objects can be created on the stack but all the properties of that class’ object will be kept in the heap.</p><h3><strong>Reference counting in classes vs structs?</strong></h3><p>Since <em>classes</em> support <em>heap</em> allocations they need to maintain reference counts for allocating and deallocating objects.<br><em>Structs</em> do not need reference counting. However, if structs contain references then they would incur twice the number of reference counting overhead as compared to a class.</p><h3><strong>Method Dispatching in classes vs structs?</strong></h3><p><em>Classes </em>use method dispatch. But if a class is marked as <em>final, </em>the compiler will use static dispatch.<br><em>Structs </em>use static dispatch.</p><h3><strong>What are memberwise initializers?</strong></h3><p>Memberwise initializers are those initializers which the compiler generates automatically for <em>structs</em>. We can initialize a struct’s object using these initializers even though we have not provided any custom initializers.</p><p>The order of the arguments in these initializers is decided by the order of the declared properties in the struct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1724e987cfd7b570d698c58c4fee745c/href">https://medium.com/media/1724e987cfd7b570d698c58c4fee745c/href</a></iframe><p>However, if we write any custom initializer, the compiler will not generate the memberwise initializer.</p><p>If we <strong>want both memberwise and custom initializers</strong>, we should add the custom initializer in the extension of that struct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6acf272ebec67c2289d0fd6309450333/href">https://medium.com/media/6acf272ebec67c2289d0fd6309450333/href</a></iframe><p>Also, I would suggest iOS developers to read the <a href="https://docs.swift.org/swift-book/LanguageGuide/Initialization.html">official Swift documentation</a> to know more about the initialization process in Swift.</p><h3>What is the “mutating” keyword in Swift and when is it used?</h3><p>When we have to change any property of a struct, we should use the <em>mutating</em> keyword before the <em>func </em>keyword when defining a method. This is because the self parameter that’s implicitly passed into every method is immutable by default.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84d699b79bd694d55a8b38235e54d4e0/href">https://medium.com/media/84d699b79bd694d55a8b38235e54d4e0/href</a></iframe><p>Within a mutating method, <em>self</em> is passed as a var. The <em>mutating</em> keyword helps the compiler to decide which methods cant be called on let constants. If we try to call a mutating method on a <em>let</em> variable, the compiler shows an <em>error</em>.</p><figure><img alt="Swift mutating keyword usage example" src="https://cdn-images-1.medium.com/max/1024/1*vwbHddSWIMpmLOc5E4KowA.png" /><figcaption>When creating request2 as a let variable — compiler gives an error.</figcaption></figure><p>It’s just tip of the iceberg. I have a lot to cover on this topic, so divided this story into two parts. Many advanced concepts and questions of structs and classes in swift can be found here: <a href="https://medium.com/hash-coding/swift-structures-and-classes-part-ii-b319998c5b7e?source=friends_link&amp;sk=2e947f4fb456dd325d1318450da32c22">Swift — Structs and Classes — Part II</a>.</p><p>Apart from this, one should also be aware of <a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd">Swift’s Copy on Write</a> optimization when dealing with value types, and how we can i<a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd#edc9">mplement Copy on Write for our own custom types</a>.</p><p>Keep following!</p><p>If you like the content, save it on medium and share with your iOS community and help us reach a larger audience who could use this. You can appreciate it as well. Clap or <strong>C<em>laps</em></strong><em>. 👏 👏</em></p><h3>What’s next to read?</h3><ul><li><a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd">Swift — Copy-On-Write Optimization</a></li><li><a href="https://medium.com/hash-coding/swift-functions-closure-part-i-e339faa51ffc">Swift  —  Functions &amp; Closure  —  Part I</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <em>Signup Now.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding%2F&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href">https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582e26bdf8dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd">Swift — Structures and Classes — Part 1</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift  —  let vs var]]></title>
            <link>https://medium.com/hash-coding/swift-let-vs-var-b2a74e098c2a?source=rss----8167d64d21a9---4</link>
            <guid isPermaLink="false">https://medium.com/p/b2a74e098c2a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Jayant Kumar Yadav]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 06:34:18 GMT</pubDate>
            <atom:updated>2021-03-03T04:13:37.873Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hacking the iOS Interview</h4><h3>Swift — let vs var</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kgeTW6saSNtynXWj" /><figcaption>Photo by <a href="https://unsplash.com/@officestock?utm_source=medium&amp;utm_medium=referral">Sebastian Herrmann</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At first, it looks like a trivial question of Swift language. But this might lead to discussions around language semantics and its mutability/immutability in general. You have to be ready for this deep dive.</p><h3>What are let and var ? What is the difference between them ?</h3><p>Both let and var are for creating variables in Swift. let helps you create immutable variables (constants) while on the other hand var creates mutable variables. Variables created by both of them either hold a reference or a value.</p><p>The difference between them is that when you create a constant using let you have to assign something to it before the first use and can’t reassign it. And when you declare a variable with var it can either be assigned right away or at a later time or not at all and can be reassigned at any time.</p><h3><strong>Can we mutate function parameters ?</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cdeaa9294ab58ea114253ba4bd0e851/href">https://medium.com/media/1cdeaa9294ab58ea114253ba4bd0e851/href</a></iframe><p>Function parameters are constants by default. Trying to change their value within functions body results in a compile-time error.</p><p><strong>Line 2</strong> — <em>Cannot assign to value: ‘value’ is ‘let’ constant.</em></p><blockquote>Have you ever wondered why function parameters are not variables? <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0003-remove-var-parameters.md">Find out here</a></blockquote><h3><strong>Can you help compile this code? Explain the cause of compile-time errors, if any.</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d0825c43cd909a7bc51112207331f0/href">https://medium.com/media/63d0825c43cd909a7bc51112207331f0/href</a></iframe><blockquote>Structs have value type semantics in Swift. Whenever you try to mutate them, they get copied with mutation applied to them and reassigned back.</blockquote><p>The let variables holding struct can’t mutate it as it would mean you are mutating value of the immutable variable which can not happen in Swift. On the other hand, the var variable holding struct can mutate itself. Similarly, the rule of let &amp; var will apply to individual properties of the struct.</p><p><strong>Line 7</strong> — <em>Cannot assign to property: ‘constantBlog’ is a ‘let’ constant.</em></p><p><strong>Line 8 &amp; 12</strong> — <em>Cannot assign to property: ‘claps’ is a ‘let’ constant.</em></p><h3><strong>Where do you think compile-time errors would be present in this code?</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf117c017bae1ca93195d16aba2f8d4a/href">https://medium.com/media/bf117c017bae1ca93195d16aba2f8d4a/href</a></iframe><blockquote>Classes have reference type semantics in Swift. Whenever you try to mutate them, the object stored elsewhere in memory gets mutated while the reference to it remains the same.</blockquote><p>You can modify a class’s members whether or not the variable referencing it is mutable.</p><p><strong>Line 13 &amp; 17</strong> — <em>Cannot assign to property: ‘claps’ is a ‘let’ constant.</em></p><p>The whole point is that your interviewer wants to dig deep for your understandings of how mutation works in swift. What can be mutated and what not.</p><p>I hope you find this story helpful. If you liked it, share this with your community and feel free to give your claps below 👏 to help others find it! Thanks for reading.</p><h3>What’s next to read?</h3><ul><li><a href="https://medium.com/hash-coding/swift-structures-and-classes-part-1-582e26bdf8dd">Swift — Structures and Classes — Part 1</a></li><li><a href="https://medium.com/hash-coding/swift-copy-on-write-optimization-46b1890862dd">Swift — Copy-On-Write Optimization</a></li><li><a href="https://medium.com/hash-coding/hacking-the-ios-interview-f1dc9fec8088">Hacking The iOS Interview</a></li></ul><p>Get notified every time we post a new story to our publication. <a href="https://medium.com/hash-coding">Follow us now</a></p><p>We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. <em>Signup Now.</em> ✉️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fslidetosubscribe.com%2Fembed%2Fhashcoding%2F&amp;dntp=1&amp;display_name=Slide+to+Subscribe&amp;url=https%3A%2F%2Fslidetosubscribe.com%2Fhashcoding%2F&amp;image=https%3A%2F%2Fslidetosubscribe.com%2Fi%2Fhashcoding.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slidetosubscribe" width="450" height="152" frameborder="0" scrolling="no"><a href="https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href">https://medium.com/media/2956eaa018ae55070275da8564dfdd2f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2a74e098c2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hash-coding/swift-let-vs-var-b2a74e098c2a">Swift  —  let vs var</a> was originally published in <a href="https://medium.com/hash-coding">Hash Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>