<?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 Rahul Singh on Medium]]></title>
        <description><![CDATA[Stories by Rahul Singh on Medium]]></description>
        <link>https://medium.com/@rahulsingh05?source=rss-fe51e407ffc1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lQP556YTxIW_Pw0ClI2yBA.jpeg</url>
            <title>Stories by Rahul Singh on Medium</title>
            <link>https://medium.com/@rahulsingh05?source=rss-fe51e407ffc1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:15:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulsingh05/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[What’s New in Swift 4.2]]></title>
            <link>https://medium.com/swift-india/whats-new-in-swift-4-2-443d86686991?source=rss-fe51e407ffc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/443d86686991</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift-4]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Sat, 07 Jul 2018 14:12:51 GMT</pubDate>
            <atom:updated>2019-03-26T05:10:39.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOOI6HAxcYtX9cEyk4hgnA.jpeg" /></figure><p><strong>Swift 4.2</strong> is a major update from 4.1 and 4.0. The update was mostly related to improvements, code optimisation and runtime performance enhancements. You can now use <strong>Xcode 10.0</strong> to build targets that are written in either Swift 4 or Swift 3. In this article, I would be discussing about the new features that were introduced in <strong>Swift 4.2</strong>. Lets get through these one by one.</p><h3>Abolish ImplicitlyUnwrappedOptional (IUO) type — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0054-abolish-iuo.md">SE-0054</a></h3><p>This proposal introduced the removal of <strong>ImplicitlyUnwrappedOptional</strong> type from the Swift and replaceing it with an <strong>IUO attribute</strong> on declarations. You would still continue to use the syntax <strong>T!</strong> . However, using ! at the end of a property or variable declaration&#39;s type no longer indicates that the declaration has IUO type. Rather, it indicates 2 thing:</p><ol><li>The declaration has optional type.</li><li>The declaration has an attribute indicating that its value may be implicitly forced. (No human would ever write or observe this attribute, but we will refer to it as <strong>@_autounwrapped</strong>.) Such a declaration is referred to henceforth as an IUO declaration.</li></ol><p>Below are some of the Examples:</p><pre>// f: () -&gt; Int?, has IUO attribute<br><strong>func</strong> f() -&gt; Int! {<br>   <strong>return</strong> 3<br>}</pre><pre>// succeeds; x1: Int? = 3<br><strong>let</strong> x1 = f()</pre><pre>// succeeds; x2: Int? = .some(3)<br><strong>let</strong> x2: Int? = f()</pre><pre>// succeeds; x3: Int? = .some(3), has IUO attribute<br><strong>let</strong> x3: Int! = f()</pre><pre>// succeeds; x4: Int = 3<br><strong>let</strong> x4: Int = f()</pre><pre>// succeeds; a: [Int?] = [.some(3)]<br><strong>let</strong> a1 = [f()]</pre><pre>// illegal, nested IUO type<br><strong>let</strong> a2: [Int!] = [f()]</pre><pre>// succeeds; a: [Int] = [3]<br><strong>let</strong> a3: [Int] = [f()]</pre><pre>// f: () -&gt; Int?, has IUO attribute<br><strong>func</strong> g() -&gt; Int! {<br>   <strong>return</strong> <strong>nil</strong><br>}</pre><pre>// succeeds; y1: Int? = .none<br><strong>let</strong> y1 = g() </pre><pre>// succeeds; y2: Int? = .none<br><strong>let</strong> y2: Int? = g()</pre><pre>// succeeds; y3: Int? = .none, has IUO attribute<br><strong>let</strong> y3: Int! = g()</pre><pre>// traps<br><strong>let</strong> y4: Int = g()</pre><pre>// succeeds; b: [Int?] = [.none]<br><strong>let</strong> b1 = [g()]</pre><pre>// illegal, nested IUO type<br><strong>let</strong> b2: [Int!] = [g()]</pre><pre>// traps<br><strong>let</strong> b3: [Int] = [g()]</pre><pre><strong>func</strong> p&lt;T&gt;(x: T) {<br>    <strong>print</strong>(x)<br>}</pre><pre>// prints “Optional(3)”; p is instantiated with T = Int?<br>p(f())<br><strong>if</strong> let x5 = f() {<br>   // executes, with x5: Int = 3<br>}</pre><pre><strong>if</strong> let y5 = g() {<br>    // does not execute<br>}</pre><p>The proposal introduced would break the existing code under following 2 situations.</p><ol><li>Explicitly written nested IUO types (like <strong>[Int!]</strong>) should be changed to corresponding optional type (<strong>[Int?]</strong>) or non-optional type (<strong>[Int]</strong>) depending on context it is used.</li><li>Variable bindings which previously had inferred type <strong>T!</strong> from their binding on the right-hand side will now have type <strong>T? </strong>.<strong> </strong>The compiler would display an error and suggest that the value be forced with<strong>!</strong> operator.</li></ol><h3>Conditional conformances — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md">SE-0143</a></h3><p>This was initially introduced in Swift 4.1 under <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md">SE-0185</a> and then redefined in Swift 4.2 to allow you to query at runtime. Swift 4.2 enabled synthesis of conditional conformances to <strong>Equatable</strong> and <strong>Hashable</strong>. Let us understand this with an example.</p><p>Suppose you have a protocol named <strong>TaxAmount</strong>:</p><pre><strong>protocol</strong> TaxAmount {<br>    <strong>func</strong> taxAmount()<br>}</pre><p>And a <strong>Struct</strong> that conforms to that protocol:</p><pre><strong>struct</strong> FoodItem: TaxAmount {<br>    <strong>var</strong> rate = 1000.0</pre><pre>    <strong>func</strong> taxAmount() {<br>        <strong>let</strong> tax = rate/1.18<br>        <strong>print</strong>(tax)<br>    }<br>}</pre><p>Then create an <strong>extension</strong> to <strong>Array</strong> conforming to <strong>TaxAmount</strong> . Also, have a method which would call the protocol method if it confirms to the desired Protocol.</p><pre><strong>extension</strong> Array: TaxAmount <strong>where</strong> Element: TaxAmount {<br>    <strong>func</strong> taxAmount() {<br>        <strong>for</strong> item <strong>in</strong> <strong>self</strong> {<br>            item.taxAmount()<br>        }<br>    }<br>}</pre><pre><strong>func</strong> calculateTax(<strong>_</strong> value: <strong>Any</strong>) {<br>    <strong>if</strong> <strong>let</strong> p = value <strong>as</strong>? TaxAmount {<br>        p.taxAmount()<br>    } <strong>else</strong> {<br>        print(&quot;Not a Taxable Object&quot;)<br>    }<br>}</pre><pre>calculateTax([FoodItem(), FoodItem(), FoodItem()])<br><em>// </em><strong><em>Prints</em></strong><em> 847.457627118644<br>// </em><strong><em>Prints</em></strong><em> 847.457627118644<br>// </em><strong><em>Prints</em></strong><em> 847.457627118644</em></pre><pre>calculateTax([1, 2, 3])<br><em>// </em><strong><em>Prints</em></strong><em> &quot;Not a Taxable Object&quot;</em></pre><p>The <strong>if-let</strong> in <strong>calculateTax(_:)</strong> dynamically queries whether the type in <strong>value</strong> conforms to the protocol <strong>TaxAmount</strong>. In case of an <strong>Array</strong>, that conformance is conditional and requires another dynamic lookup to determine whether the element type conforms to <strong>TaxAmount</strong>. In the first case, the lookup finds the conformance of <strong>FoodItem</strong> to <strong>TaxAmount</strong>. In the second case, there is no conformance of <strong>Int</strong> to <strong>TaxAmount</strong>, so the conditional conformance fails.</p><p>The Conditional Conformance is not only limited to Array but is available to all the Types.</p><pre><strong>extension</strong> Optional: Equatable <strong>where</strong> Wrapped: Equatable {<br><em>/*== already exists */<br></em>}</pre><pre><strong>extension</strong> Array: Equatable <strong>where</strong> Element: Equatable {<br><em>/*== already exists */<br></em>}</pre><pre><strong>extension</strong> ArraySlice: Equatable <strong>where</strong> Element: Equatable {<br><em>/*== already exists */<br></em>}</pre><pre><strong>extension</strong> ContiguousArray: Equatable <strong>where</strong> Element: Equatable {<br><em>/*== already exists */<br></em>}</pre><pre><strong>extension</strong> Dictionary: Equatable <strong>where</strong> Value: Equatable {<br><em>/*== already exists */<br></em>}</pre><p>In addition, conditional conformances can now also be implmented to <strong>Hashable</strong> for the above types, as well as for <strong>Range</strong> and <strong>ClosedRange.</strong></p><pre><strong>extension</strong> Optional: Hashable <strong>where</strong> Wrapped: Hashable {<br><em>/*…*/<br></em>}</pre><pre><strong>extension</strong> Array: Hashable <strong>where</strong> Element: Hashable {<br><em>/*…*/<br></em>}</pre><pre><strong>extension</strong> ArraySlice: Hashable <strong>where</strong> Element: Hashable {<br><em>/*…*/<br></em>}</pre><pre><strong>extension</strong> ContiguousArray: Hashable <strong>where</strong> Element: Hashable {<br><em>/*…*/<br></em>}</pre><pre><strong>extension</strong> Dictionary: Hashable <strong>where</strong> Value: Hashable {<br><em>/*…*/<br></em>}</pre><pre><strong>extension</strong> Range: Hashable <strong>where</strong> Bound: Hashable {<br><em>/*…*/<br></em>}</pre><pre><strong>extension</strong> ClosedRange: Hashable <strong>where</strong> Bound: Hashable {<br><em>/*…*/<br></em>}</pre><h3>Derived Collection of Enum Cases — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0194-derived-collection-of-enum-cases.md">SE-0194</a></h3><p>This proposal introduced a new <strong>CaseIterable</strong> protocol that would by default generate an array property of all cases in an enum. Prior to Swift 4.2, one would have to resort to various <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0194-derived-collection-of-enum-cases.md#workarounds">workarounds</a> in order to iterate over all cases of a simple enum. But now, with Swift 4.2, you just have to conform to the <strong>CaseIterable</strong> protocol and complier would generate an <strong>allCases</strong> property that is an array of all your enum’s cases, in the order you defined them.</p><pre><strong>enum</strong> Direction: <strong>CaseIterable</strong> {<br>    case east, west, north, south<br>}</pre><pre><strong>for</strong> direction <strong>in</strong> <strong>Direction.allCases</strong> {<br>    <strong>print</strong>(&quot;Directions are: \(direction).&quot;)<br>}</pre><p>The automatic synthesis of <strong>allCases</strong> would only take place for <strong>enums</strong> that do not have associated values. You would need to implement it yourself in such cases.</p><pre><strong>enum</strong> Airport {<br>    <strong>static var</strong> allCases: [Airport] {<br>        return [.munich, .sanFrancisco, .singapore, .london(airportName: &quot;Heathrow&quot;), .london(airportName: &quot;Gatwick&quot;)]<br>    }</pre><pre>    <strong>case</strong> munich<br>    <strong>case</strong> sanFrancisco<br>    <strong>case</strong> singapore<br>    <strong>case</strong> london(airportName: String)<br>}</pre><h3>Introduce User-defined “Dynamic Member Lookup” Types — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0195-dynamic-member-lookup.md">SE-0195</a></h3><p>This proposal introduced a new <strong>@dynamicMemberLookup</strong> attribute. Types that use it, provide &quot;<strong>dot</strong>&quot; syntax for arbitrary names which are resolved at runtime - in a <strong>completely type safe</strong> way.</p><pre><strong>@dynamicMemberLookup</strong><br><strong>struct</strong> Person {<br>    <strong>subscript</strong>(<strong>dynamicMember</strong> param: <strong>String</strong>) -&gt; <strong>String</strong> {<br>        <strong>let</strong> properties = [&quot;personName&quot;: &quot;John Appleseed&quot;, &quot;City&quot;: &quot;Ohio&quot;]<br>        <strong>return</strong> properties[param, default: &quot;&quot;]<br>    }<br>}</pre><pre><strong>let</strong> person = Person()<br><strong>print</strong>(person.name)<br><strong>print</strong>(person.city)<br><strong>print</strong>(person.age)</pre><p>In the above example, the <strong>Person</strong> object is created as it should be. Then it would print the person’s <strong>name</strong> and <strong>city</strong> as “<strong>John Appleseed</strong>” and “<strong>Ohio</strong>” respetively. Since, there is no property named “age”, it would return an empty string.<strong>subscript(dynamicMember:)</strong> method <em>must</em> return a string, which is where Swift’s type safety comes in. Even though you’re dealing with dynamic data, Swift will still ensure that you get back what you expected.</p><p>You can implement different <strong>subscript(dynamicMember:)</strong> methods for different return Data Types.</p><pre><strong>@dynamicMemberLookup</strong><br><strong>struct</strong> Person {<br>    <strong>subscript</strong>(<strong>dynamicMember</strong> param: <strong>String</strong>) <strong>-&gt;</strong> <strong>String</strong> {<br>        <strong>let</strong> properties = [&quot;personName&quot;: &quot;John Appleseed&quot;, &quot;City&quot;: &quot;Ohio&quot;]<br>        <strong>return</strong> properties[param, <strong>default</strong>: &quot;&quot;]<br>}</pre><pre><strong>subscript</strong>(<strong>dynamicMember</strong> param: <strong>String</strong>) <strong>-&gt;</strong> <strong>Int</strong> {<br>        <strong>let</strong> properties = [&quot;age&quot;: 43, &quot;height&quot;: 173]<br>        <strong>return</strong> properties[member, <strong>default</strong>: 0]<br>    }<br>}</pre><pre><strong>let</strong> person = Person()<br><strong>print</strong>(person.name)<br>// <strong>Prints</strong> &quot;John Appleseed&quot;</pre><pre><strong>print</strong>(person.city)<br>// <strong>Prints</strong> &quot;Ohio&quot;</pre><pre><strong>print</strong>(person.age)<br>// <strong>Prints</strong> 43</pre><pre><strong>print</strong>(person.height)<br>// <strong>Prints</strong> 173</pre><p>You can even overload subscript to return closures:</p><pre><strong>@dynamicMemberLookup</strong><br><strong>struct</strong> User {<br>    <strong>subscript</strong>(<strong>dynamicMember</strong> parm: <strong>String</strong>) -&gt; (_ title: <strong>String</strong>) -&gt; <strong>Void</strong> {<br>        <strong>return</strong> {<br>            <strong>print</strong>(&quot;John Appleseed was born at <strong>\($0)</strong>.&quot;)<br>        }<br>    }<br>}</pre><pre><strong>let</strong> user = User()<br>user.print(&quot;Leominster, Massachusetts, United States&quot;)<br>// <strong>Prints</strong> &quot;John Appleseed was born at Leominster, Massachusetts, United States&quot;</pre><p><strong>@dynamicMemberLookup</strong> can be assigned to <strong>protocols</strong>, <strong>structs</strong>, <strong>enums</strong>, and even <strong>classes . </strong>One last example that I would like to cover in this would be the example given by the Auther (<strong>Chris Lattner</strong>). Its about <strong>JSON</strong> enum which uses dynamic member lookup to create more natural syntaxing. This example would realy help understand the use of <strong>@dynamicMemberLookup</strong></p><pre><strong>enum</strong> JSON {<br>    <strong>case</strong> IntValue(<strong>Int</strong>)<br>    <strong>case</strong> StringValue(<strong>String</strong>)<br>    <strong>case</strong> ArrayValue(<strong>Array&lt;JSON&gt;</strong>)<br>    <strong>case</strong> DictionaryValue(<strong>Dictionary&lt;String, JSON&gt;</strong>)<br>}</pre><pre><strong>extension</strong> JSON {<br>    <strong>var</strong> stringValue : <strong>String</strong>? {<br>        <strong>if</strong> <strong>case</strong> .StringValue(<strong>let</strong> str) = <strong>self</strong> {<br>            <strong>return</strong> str<br>        }<br>        <strong>return</strong> <strong>nil</strong><br>    }</pre><pre><strong>subscript</strong>(<strong>index</strong>: Int) <strong>-&gt;</strong> <strong>JSON</strong>? {<br>        <strong>if</strong> <strong>case</strong> .ArrayValue(let arr) = <strong>self</strong> {<br>            <strong>return</strong> index &lt; arr.count ? arr[index] : <strong>nil</strong><br>        }<br>        <strong>return nil</strong><br>    }<br>   <br>    <strong>subscript</strong>(key: String) <strong>-&gt;</strong> JSON? {<br>        <strong>if case</strong> .DictionaryValue(<strong>let</strong> dict) = <strong>self</strong> {<br>            <strong>return</strong> dict[key]<br>        }<br>        <strong>return nil</strong><br>    }</pre><pre><strong>subscript(dynamicMember</strong> param: <strong>String</strong>) <strong>-&gt;</strong> <strong>JSON</strong>? {<br>        <strong>if</strong> <strong>case</strong> .DictionaryValue(<strong>let</strong> dict) = <strong>self</strong> {<br>            <strong>return</strong> dict[param]<br>        }<br>        <strong>return nil</strong><br>    }<br>}</pre><pre><strong>let</strong> json = JSON.stringValue(&quot;Dynamic Member Lookup Example&quot;)</pre><p>Below is the way of navigating an instance of JSON enum With and Without dynamic member look up.</p><pre><strong>Without dynamic member look up.</strong><br>json[0]?[&quot;name&quot;]?[&quot;first&quot;]?.stringValue</pre><pre><strong>With dynamic member look up.</strong><br>json[0]?.name?.first?.stringValue</pre><h3>Compiler Diagnostic Directives — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0196-diagnostic-directives.md">SE-0196</a></h3><p>This proposal introduced <strong>#warning</strong> and <strong>#error</strong> directives that would prompt the Swift compiler to emit a custom warning or an error during compilation.</p><p><strong>#warning — </strong>Force Xcode to issue a warning when building your code.</p><pre><strong>func</strong> configPath() -&gt; <strong>String</strong> {<br>    <strong>#warning</strong>(&quot;This should be made more safe&quot;)<br>    <strong>return</strong> <strong>Bundle.main</strong>().<strong>path</strong>(<strong>forResource</strong>: “Config”, <strong>ofType</strong>: “plist”)!<br>}</pre><p><strong>#error — </strong>Get comple time error and build would fail.</p><pre><strong>struct</strong> Configuration {<br>    <strong>var</strong> apiKey: <strong>String</strong> {<br>        <strong>#error</strong>(&quot;Please enter your API key below.&quot;)<br>        <strong>return</strong> &quot;Enter your key here&quot;<br>    }<br>}</pre><blockquote><strong>NOTE:</strong> If a <strong>#warning</strong> or <strong>#error</strong> exists inside a branch of a <strong>#if</strong> directive that is not taken, then no diagnostic is emitted.</blockquote><pre><strong>#if</strong> <strong>false</strong><br>    <strong>#warning</strong>(&quot;This will not trigger a warning.&quot;)<br>    <strong>#error</strong>(&quot;This will not trigger an error.&quot;)<br><strong>#endif</strong></pre><pre><strong>#if true</strong><br>    <strong>#warning</strong>(&quot;This will trigger a warning.&quot;)<br>    <strong>#error</strong>(&quot;This will trigger an error.&quot;)<br><strong>#endif</strong></pre><h3>Adding in-place removeAll(where:) to the Standard Library — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0197-remove-where.md">SE-0197</a></h3><p>This proposal introduced a new <strong>removeAll(where:)</strong> method. This would remove all entities in a collection in-place matching a given predicate.</p><pre><strong>var</strong> name = [&quot;John&quot;, &quot;William&quot;, &quot;Michael&quot;, &quot;Gary&quot;, &quot;Liam&quot;]<br><strong>name.removeAll</strong> { <strong>$0.hasSuffix</strong>(&quot;am&quot;) }</pre><pre><strong>print</strong>(name)<br>// <strong>Prints</strong> &quot;John&quot;, &quot;Michael&quot;, &quot;Gary&quot;</pre><p>If you where to implement this without <strong>removeAll(where:)</strong> method, then probably you would have used <strong>filter() </strong>method.</p><pre>name = name<strong>.filter</strong>{<strong>!$0.hasPrefix</strong>(&quot;am&quot;)}</pre><h3>Adding toggle to Bool — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0199-bool-toggle.md">SE-0199</a></h3><p>This proposal introduced a new <strong>toggle()</strong> method to Booleans that would flip between true and false. This implemenation of this proposal is just few lines of code. It is easy and safe to write for complex data structures.</p><pre><strong>extension</strong> <strong>Bool</strong> {<br>    <strong>mutating</strong> <strong>func</strong> toggle() {<br>        <strong>self</strong> = <strong>!self</strong><br>    }<br>}</pre><pre><strong>var</strong> loggedIn = false<br>loggedIn.<strong>toggle()</strong></pre><h3>Random Unification — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0202-random-unification.md">SE-0202</a></h3><p>This proposal’s main focus was to create a unified random API, and a secure random API for all platforms. Currently, Swift used C API’s to perform random functionality. But with this, you can now, generate random numbers just by calling the <strong>random()</strong> method on whatever numeric type you want and providing the range you want to work with.</p><pre><strong>// Int</strong><br><strong>let</strong> randomIntFrom0To10 = <strong>Int.random</strong>(<strong>in</strong>: 0 <strong>..&lt;</strong> 10)</pre><pre><strong>// Float<br>let</strong> randomFloat = <strong>Float.random</strong>(<strong>in:</strong> 0 <strong>..&lt;</strong> 1)</pre><pre><strong>// Double<br>let</strong> randomDouble = <strong>Double.random</strong>(<strong>in:</strong> 0 <strong>…</strong> .pi, <strong>using:</strong> &amp;myCustomRandomNumberGenerator)</pre><pre><strong>// Boolean<br>let</strong> randomBool1 = <strong>Bool.random</strong>()<br><strong>let</strong> randomBool2 = <strong>Bool.random</strong>(<strong>using</strong>: &amp;myCustomRandomNumberGenerator)</pre><p>Randomisation is just not limited to Numbers, but now, it can be used for <strong>Collections</strong> as well. <strong>Collection</strong> also has 2 new methods i.e.: <strong>shuffle()</strong> and <strong>shuffled()</strong> .</p><pre><strong>let</strong> greetings = [&quot;hey&quot;, &quot;hi&quot;, &quot;hello&quot;, &quot;hola&quot;]</pre><pre>// Utilizes the standard library’s default random. This returns an Optional<br><strong>print</strong>(greetings.<strong>randomElement()!</strong>)</pre><pre>// This returns an Optional<br><strong>print</strong>(greetings.<strong>randomElement(using:</strong> &amp;myCustomRandomNumberGenerator)<strong>!)</strong></pre><pre><strong>var</strong> playingCards = [&quot;Club&quot;, &quot;Diamond&quot;, &quot;Heart&quot;, &quot;Spade&quot;]</pre><pre>// Shuffle in place<br>playingCards<strong>.shuffle()</strong></pre><pre>// Get a shuffled array<br><strong>let</strong> shuffled = playingCards<strong>.shuffled()</strong></pre><h3>Add last(where:) and lastIndex(where:) Methods — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0204-add-last-methods.md">SE-0204</a></h3><p>This proposal primarily introduced 3 methods namely <strong>last(where:) lastIndex(where:) </strong><strong>lastIndex(of:) </strong>. The first two requires a closure as an argument whereas the last requires the Element to be searched.</p><pre><strong>let</strong> numberSequence = [20, 30, 10, 40, 20, 30, 10, 40, 20]<br><strong>let</strong> lastHighestNumber = numberSequence<strong>.last(where:</strong> { <strong>$0</strong> &gt; 25 })<br><strong>print</strong>(lastHighestNumber)<br>// <strong>Prints</strong> 40</pre><pre><strong>let</strong> lastHighestNumberIndex = numberSequence<strong>.lastIndex(where:</strong> { <strong>$0</strong> &gt; 25 })<br><strong>print</strong>(lastHighestNumberIndex)<br>// <strong>Prints</strong> 7</pre><pre><strong>let</strong> lastIndexOfElement = numberSequence<strong>.lastIndex(of:</strong> 10)<br><strong>print</strong>(lastIndexOfElement)<br>// <strong>Prints</strong> 7</pre><p>In addition, the <strong>index(of:)</strong> and <strong>index(where:)</strong> method names were also renamed to <strong>firstIndex(of:)</strong> and <strong>firstIndex(where:)</strong>, respectively. This is beneficial for two reasons. First, it groups the <strong>first...</strong> and <strong>last...</strong> methods into two symmetric analogous groups. Second, it leaves the <strong>index...</strong> methods as solely responsible for index manipulation.</p><pre><strong>let</strong> firstHighestNumber = numberSequence<strong>.first(where:</strong> { <strong>$0</strong> &gt; 25 })<br><strong>print</strong>(firstHighestNumber)<br>// <strong>Prints</strong> 30</pre><pre><strong>let</strong> firstHighestNumberIndex = numberSequence<strong>.firstIndex(where:</strong> { <strong>$0</strong> &gt; 25 })<br><strong>print</strong>(firstHighestNumberIndex)<br>// <strong>Prints</strong> 1</pre><pre><strong>let</strong> firstIndexOfElement = numberSequence<strong>.firstIndex(of:</strong> 10)<br><strong>print</strong>(firstIndexOfElement)<br>// <strong>Prints</strong> 2</pre><h3>Hashable Enhancements — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0206-hashable-enhancements.md">SE-0206</a></h3><p>This proposal introduced a new <strong>Hasher</strong> type representing the hash function. I extends the <strong>Hashable</strong> protocol with a new <strong>hash(into:)</strong> requirement that expresses hashing in terms of <strong>Hasher</strong>. This new requirement would replace the old <strong>hashValue</strong> property, which is now deprecated.</p><p>Before Swift 4.1, one had to calculate a <strong>hashValue</strong>property by themselves. In swift 4.1, this was improved so that <strong>hashValue</strong>property was synthesized automatically by the complier on Conformance. Hence, the below code</p><pre><strong>struct</strong> Person: <strong>Hashable</strong> {<br>    <strong>var</strong> personName: <strong>String</strong><br>    <strong>var</strong> personAge: <strong>Int</strong></pre><pre><strong>    var</strong> hashValue: <strong>Int</strong> {<br>        return personName.<strong>hashValue</strong> ^ personAge.<strong>hashValue</strong> <strong>&amp;* 16777619</strong><br>    }<br>}</pre><p>turned into:</p><pre><strong>struct</strong> Person: <strong>Hashable</strong> {<br>    <strong>var</strong> personName: <strong>String</strong><br>    <strong>var</strong> personAge: <strong>Int</strong><br>}</pre><p>However, if you want to implement your own Hashing mechanism, you would still need to implement a hashValue method using an algorithm that suits you best.</p><p>Swift 4.2 is improving this situation by introducing a new <strong>Hasher</strong> struct that provides a randomly seeded, universal <strong>hash(into:)</strong> function.</p><pre><strong>struct</strong> Person: <strong>Hashable</strong> {<br>    <strong>var</strong> personName: <strong>String</strong><br>    <strong>var</strong> personAge: <strong>Int</strong></pre><pre><strong>func</strong> <strong>hash</strong>(<strong>into</strong> <strong>hasher</strong>: <strong>inout</strong> <strong>Hasher</strong>) {<br>        <strong>hasher.combine</strong>(personName)<br>        <strong>hasher.combine</strong>(personAge)<br>    }<br>}</pre><p>There is another way of doing this. You could also use<strong>Hasher</strong> as a standalone hash generator.</p><pre><strong>let</strong> john = Person(personName: &quot;John Appleseed&quot;, personAge: 50)<br><strong>let</strong> paul = Person(personName: &quot;Paul Warner&quot;, personAge: 45)</pre><pre><strong>var</strong> hasher = <strong>Hasher</strong>()<br>hasher<strong>.combine</strong>(john)<br>hasher<strong>.combine</strong>(paul)</pre><pre><strong>let</strong> hash = hasher.<strong>finalize()</strong></pre><blockquote>You must <em>not</em> call <strong><em>finalize()</em></strong> if you’re writing a custom <strong><em>hash(into:)</em></strong> method for your types.</blockquote><p><strong>Hasher</strong> is a resilient struct, enabling future versions of the standard library to improve the hash function without the need to change (or even recompile) existing code that implements <strong>Hashable </strong>.</p><h3>Add an allSatisfy algorithm to Sequence — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0207-containsOnly.md">SE-0207</a></h3><p>This proposal introduced <strong>allSatisfy(_:)</strong> on <strong>Sequence</strong> that validated every element and returned true if they all match a given predicate:</p><pre><strong>let</strong> individualScores = [95, 96, 82, 87, 75]<br><strong>let</strong> firstDivision = individualScores.<strong>allSatisfy</strong> { <strong>$0</strong> &gt;= 60 }<br><strong>print</strong>(firstDivision)<br>// Prints true</pre><pre><strong>let</strong> metricScore = [95, 96, 82, 87, 32]<br><strong>let</strong> passed = metricScore.<strong>allSatisfy</strong> { <strong>$0</strong> &gt;= 40 }<br><strong>print</strong>(passed)<br>// Prints false</pre><h3>Compiler Version Directive — <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0212-compiler-version-directive.md">SE-0212</a></h3><p>This proposal introduced a <strong>compiler</strong> directive that is syntactically equivalent to the existing <strong>#if swift</strong> version check. This checks for the version of the compiler, regardless of which compatibility mode it is currently running.</p><p>Prior to Swift 4, the version of <strong>compiler</strong> and <strong>language</strong> were one and same. Swift 4 introduced a Compatibility Mode, where the compiler can also run for previous Swift versions. Below is the Table which shows the invocation of different <strong>Swift Version</strong> based on the <strong>Compiler</strong> and <strong>Language</strong> version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*AxXNkLa72M6KS5HVY_Gvkw.png" /></figure><p>Below are some of the example.</p><pre><strong>#if swift</strong>(&gt;=4.1) &amp;&amp; <strong>compiler</strong>(&gt;=5.0)<br>    <strong>print</strong>(&quot;Executes for Swift 5.0 compiler and above in — swift-version 4 mode and above.&quot;)<br>#endif</pre><pre><strong>#if swift</strong>(&gt;=4.1) || (<strong>swift</strong>(&gt;=3.3) &amp;&amp; !<strong>swift</strong>(&gt;=4.0))<br>    <strong>print</strong>(&quot;Executes for Swift 4.1 compiler and above.&quot;)<br>#endif</pre><pre><strong>#if compiler</strong>(&gt;=4.2)<br>    <strong>print</strong>(&quot;Executes for Swift 4.2 compiler and above.&quot;)<br><strong>#endif</strong></pre><pre><strong>#if compiler</strong>(&gt;=5.0)<br>    <strong>print</strong>(&quot;Executes for Swift 5.0 compiler and above.&quot;)<br><strong>#endif</strong></pre><p><strong>Points To Ponder:</strong></p><ol><li>Calling off ImplicitlyUnwrappedOptional (IUO) type.</li><li>Conditional conformances improvements.</li><li>Iterating Enum cases.</li><li>Dynamic member look up using dot syntax for subscripts.</li><li>Warning and error diagnostic directives.</li><li>In-built remove functionality based on certain conditions.</li><li>Boolean toggling.</li><li>Random number generation and shuffling.</li><li>Method refactoring and adding new methods to Array.</li><li>Hashable enhancements.</li><li>Ability to check whether all elements in a Sequence satisfied a certain condition.</li><li>Compiler version directive.</li></ol><p>Hope you have enjoyed this. For further details (like Motivation, Design Solutions, Alternate Solution, Impacts, etc.) on any of the feature, click on the Link provided.</p><blockquote>If you have any comment, question, or recommendation, feel free to post them in the comment section below! You can also follow me on Medium for new articles and connect with me on <a href="https://www.linkedin.com/in/rahulsingh05/">LinkedIn</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=443d86686991" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-india/whats-new-in-swift-4-2-443d86686991">What’s New in Swift 4.2</a> was originally published in <a href="https://medium.com/swift-india">Swift India</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Architecture & Application Life Cycle]]></title>
            <link>https://medium.com/swift-india/ios-architecture-application-life-cycle-85c192664574?source=rss-fe51e407ffc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/85c192664574</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[application-lifecycle]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Thu, 21 Jun 2018 18:24:13 GMT</pubDate>
            <atom:updated>2018-07-08T12:57:59.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*tbpwshYHeWYo7YUoIb7SwA.jpeg" /></figure><blockquote>Just as established products and brands need updating to stay alive and vibrant, you periodically need to refresh or reinvent yourself. <strong>By: Mireille Guiliano</strong></blockquote><p>The term <strong>Architecture</strong> means the ‘<strong>skeleton</strong>’ of the system. It can be visialized as the highest level of abstraction for that particular system.</p><p>iOS is a layered architecture comprising of 4 different layers namely <strong>Cocoa Touch</strong>, <strong>Media Layer</strong>, <strong>Core Service</strong>, <strong>Core OS (<em>Image 1</em>)</strong>. Each of these layers is built with different frameworks that can be used and incorporated into the applications. Let us go through each of these layers in details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*526cGRqBaU4pR-fhn6FZDA.png" /><figcaption><strong>Image 1</strong></figcaption></figure><h3><strong>Cocoa Touch Layer</strong></h3><p>It is the topmost layer in the iOS architecture. It contains some of the key frameworks which native iOS applications rely upon. <strong>UIKit</strong> framework being the most prominent one. <strong>MapKit</strong>, <strong>PushKit</strong>, <strong>EventKit </strong>are some of the other vital frameworks.</p><p>It defines the basic application management and infrastructure, multitasking support, user interface management, multi touch support, motion event etc.</p><h3>Media Layer</h3><p>This layer provides multimedia services that you can use within your iPhone, and other iOS devices. The Media layer comprises of <strong>Graphics</strong>, <strong>Audio</strong>, and <strong>Video</strong>.</p><p>This layer consists of Assets Library, Core Text, Core Graphics, OpenGL ES and OpenAL, AV Foundation and Core Media. This layer is responsible for any kinds of drawing, rendering 2D and 3D data, buffereing video, Text layout etc.</p><h3>Core Service Layer</h3><p>This layer provides features such as block objects, Grand Central Dispatch, In-App Purchase, and iCloud Storage. <strong>A</strong>utomatic <strong>R</strong>eference <strong>C</strong>ounting (ARC) was introduced in this particular layer which takes care of all the Memory Management.</p><p>The <strong>Foundation</strong> framework is yet another essential framework for iOS and OS X applications.</p><p>Core Services layer is also closely tied to the C-based <strong>Core Foundation</strong> framework or Core Foundation. This has a feature referred to as <strong>toll-free bridging</strong>, which enables the substitution of Cocoa objects for Core Foundation objects in function parameters and vice versa.</p><h3>Core <strong>OS</strong></h3><p>The Core OS layer holds the low level features that most other technologies are built upon. It also interacts directly with the hardware.</p><p>Most of the functionality provided by the three higher level layers is built upon the Core OS layer and its low level features. The Core OS layer provides a handful of frameworks that your application can use directly, such as the Accelerate and the Security frameworks.</p><p>The Core OS layer also encapsulates the kernel environment and low level UNIX interfaces to which the application has no access for so obvious security reasons. However, through the <strong>libSystem</strong> library, which is C-based, many low level features can be accessed directly, such as BSD sockets, POSIX threads, and DNS services.</p><h3>Execution States of an Application</h3><p>The iOS operating system manages the application state, but the application itself is responsible for managing important tasks to ensure smooth transition between the states. You are required to respond appropriately to application state transitions. At any given moment, your application would be in one of the below <strong><em>five states</em></strong> (<strong><em>Image 2</em></strong>).</p><ol><li><strong>Not Running —</strong> Either the application has not started or was running and has been terminated by the system.</li><li><strong>Inactive — </strong>An application is running in the Foreground but is not receiving any events. This could happen in case a Call or Message is received. An application could also stay in this state while in transition to a different state.</li><li><strong>Active —</strong> An application is running in the Foreground and receiving the events. This is the normal mode for the Forground apps. The only way to go to or from the Active state is through the Inactive state.</li><li><strong>Background —</strong> An application is running in the background and executing the code. In addition, an application being launched directly into the background enters this state instead of the inactive state.</li><li><strong>Suspended — </strong>An application is in the background but is not executing the code. The system moves the application to this state automatically and does not notify. In case of low memory, the system may purge suspended application without notice to make free space for the foreground application. When you press the home button, or switch to another app, your app is Suspended.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*aC3BZPmqoxfyYMTEJdhlXg.png" /><figcaption><strong><em>Image 2</em></strong></figcaption></figure><p>If your app is not running, the path to get to the Active state is:</p><pre><strong>Not Running → Inactive → Active</strong></pre><p>If your app is Suspended, then the path to active is:</p><pre><strong>Suspended → Background → Inactive → Active.</strong></pre><p>The path from Active to Suspended is:</p><pre><strong>Active → Inactive → Background → Suspended</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*vpSFlaMJ9WZK3P7SNi2Q0g.png" /><figcaption><strong>State Change Flow</strong></figcaption></figure><p><strong>UIApplication</strong> object defines few set of delegate methods which are called in response to different important events in the lifetime of the application. Below are those <strong><em>seven</em></strong> most important <strong><em>delegate methods</em></strong> that you should handle in your Project.</p><ol><li><strong>application:willFinishLaunchingWithOptions — </strong>This method is called after your application has been launched and its main storyboard or nib file has been loaded, but before your app’s state has been restored. You should use this method to initialize your application.</li><li><strong>application:didFinishLaunchingWithOptions — </strong>This method is called after state restoration is complete and before app’s window is displayed. You should use this method to complete your app’s initialization and some final adjustments.</li><li><strong>applicationDidBecomeActive — </strong>This method is either called to let your app know that it moved from the inactive to active state or your app was launched by the user or the system or in case user ignores an interruption (such as an incoming phone call or SMS message) that sent the application temporarily to the inactive state. You should use this method to restart any tasks that were paused (or not yet started) while the app was inactive.</li><li><strong>applicationWillResignActive — </strong>This method is called to let your app know that it is about to move from active to inactive state. This can happen in case of any interruptions (such as an incoming phone call or SMS message) or when the user quits the app. You should use this method to pause any ongoing tasks or disable timers etc.</li><li><strong>applicationDidEnterBackground — </strong>This method is called to let app know that it not running in the foreground. You have approximately <strong>five</strong> seconds to perform any tasks and return back. In case you need additional time, you can request additional execution time from the system by calling <a href="https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtask"><strong>beginBackgroundTask(expirationHandler:)</strong></a>. If the method does not return before time runs out your app is terminated and purged from memory.</li><li><strong>applicationWillEnterForeground — </strong>This method is called as a part of the transition from the background to the active state. You should use this to undo any change you made to your app upon entering the background. <strong>applicationDidBecomeActive</strong> method is called soon after this method has finished its execution which then moves the app from the inactive to the active state.</li><li><strong>applicationWillTerminate — </strong>This method is called to let you know that your app is about to terminate. You should use this method to perform any final clean-up task. You have approximately <strong>five</strong> seconds to perform any tasks and return back. If the method does not return before time expires, the system may kill the process altogether. This method may be called in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.</li></ol><p>I hope this article provided value on the iOS Architecture and Application Life Cycle. As always if you have any suggestions or questions feel free to reach out.</p><p><a href="https://www.linkedin.com/shareArticle?mini=true&amp;url=https%3A//medium.com/%40rahulsingh05/ios-architecture-application-life-cycle-85c192664574&amp;title=&amp;summary=&amp;source=">LinkedIn</a> <a href="https://twitter.com/home?status=https%3A//medium.com/%40rahulsingh05/ios-architecture-application-life-cycle-85c192664574">Twitter</a> <a href="https://www.facebook.com/sharer/sharer.php?u=https%3A//medium.com/%40rahulsingh05/ios-architecture-application-life-cycle-85c192664574">Facebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85c192664574" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-india/ios-architecture-application-life-cycle-85c192664574">iOS Architecture &amp; Application Life Cycle</a> was originally published in <a href="https://medium.com/swift-india">Swift India</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 4.0: Automatic Reference Counting (ARC) — Part 2]]></title>
            <link>https://medium.com/swift-india/swift-4-0-automatic-reference-counting-arc-part-2-848d42cf5819?source=rss-fe51e407ffc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/848d42cf5819</guid>
            <category><![CDATA[cars]]></category>
            <category><![CDATA[swift-4]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Tue, 22 May 2018 14:35:01 GMT</pubDate>
            <atom:updated>2018-06-21T18:31:25.298Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to Part Two of this tutorial on Automatic Reference Counting! In the <a href="https://medium.com/@rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-1-d21d3ccf12b5"><strong>First Part</strong></a>, you learned about some fundamental concepts of ARC such as <strong>weak</strong>, <strong>Unowned </strong>and how to resolve Reference Cycle using <strong>weak</strong> and <strong>unowned</strong>.</p><p>In this final part, you’ll learn about one last scenario, where both the <strong>properties</strong> should have a value and neither property should ever be <strong>nil</strong> once the initialization is complete. Also, you would learn how to overcome the <strong>Strong Reference Cycle</strong> in <strong>Closures</strong>. Let’s dive straight into it.</p><p>Suppose we have a <strong>Country</strong> and <strong>President</strong> class. Each of these class stores an instance of the other class as a variable. This means that every <strong>Country</strong> should have a <strong>President</strong> and every <strong>President</strong> should be associated with a <strong>Country</strong>.</p><p>To fulfil this requirement without causing a memory Leak, you would need to declare one property (In our case <strong>countryPresident</strong> in the <strong>Country</strong> Class) as an <strong><em>implicitly unwrapped optional Property</em></strong>. This can be done by placing the exclamation mark at the end of its type annotation(<strong>President</strong>!). While for the other, you would need to declare it as an <strong>unowned </strong>property (In our case <strong>country</strong> in the <strong>President</strong> Class).</p><pre><strong>class</strong> <strong>Country</strong> {<br>    <strong>let</strong> countryName: <strong>String</strong><br>    <strong>var</strong> countryPresident: <strong>President</strong>!</pre><pre><strong>    init</strong>(countryName: <strong>String</strong>, presidentName: <strong>String</strong>) {<br>        <strong>self</strong>.countryName = countryName<br>        <strong>self</strong>.countryPresident = <strong>President</strong>(presidentName: presidentName, country: <strong>self</strong>)<br>        <strong>print</strong>(&quot;Country is being initialised&quot;)<br>    }</pre><pre><strong>    deinit</strong> {<br>        <strong>print</strong>(&quot;Country is being de-initialised&quot;)<br>    }<br>}</pre><pre><strong>class President</strong> {<br>    <strong>let</strong> presidentName: <strong>String</strong><br>    <strong>unowned</strong> <strong>let</strong> country: <strong>Country</strong><br><br>    <strong>init</strong>(presidentName: <strong>String</strong>, country: <strong>Country</strong>) {<br>        <strong>self</strong>.presidentName = presidentName<br>        <strong>self</strong>.country = country<br>        <strong>print</strong>(&quot;President is being initialised&quot;)<br>    }</pre><pre><strong>    deinit</strong> {<br>        <strong>print</strong>(&quot;President is being de-initialised&quot;)<br>    }<br>}</pre><p>Because <strong>countryPresident</strong> has a default <strong>nil</strong> value, a new <strong>Country</strong> instance is considered fully initialized as soon as the <strong>Country</strong> instance sets its <strong>countryName</strong> property within its initializer. This means that the Country initializer can start to reference and pass around the implicit <strong>self</strong> property as soon as the <strong>countryName</strong> property is set. The Country initializer can therefore pass <strong>self</strong> as one of the parameters for the <strong>President</strong> initializer when the Country initializer is setting its own <strong>countryPresident</strong> property. Doing so doesn&#39;t create any strong Reference (<strong><em>Image 1–1</em></strong>).</p><pre><strong>var</strong> country:<strong>Country</strong>? = <strong>Country</strong>(countryName: &quot;India&quot;, presidentName: &quot;Ram Nath Kovind&quot;)</pre><pre>// Prints &quot;<strong>President is being initialised&quot;<br></strong>// Prints &quot;<strong>Country is being initialised&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*ta898sbt0a17DC4R6xNLgA.png" /><figcaption><strong>Image 1–1</strong></figcaption></figure><p>Now, when the country is set to <strong>nil</strong>, president would also be automatically nullified (<strong><em>Image 1-2</em></strong>).</p><pre>country = nil</pre><pre>// Prints <strong>&quot;President is being de-initialised&quot;<br></strong>// Prints <strong>&quot;Country is being de-initialised&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*DYi0bRosISaIE4zwyRAfJA.png" /><figcaption><strong>Image 1-2</strong></figcaption></figure><p>Try removing <strong>unowned </strong>from the <strong>President</strong> Class’s <strong>country</strong> property. Observe the leak caused when setting <strong>country</strong> as <strong>nil </strong>.</p><h3><strong>Strong Reference Cycle</strong> in <strong>Closures</strong></h3><p>A strong reference cycle can also occur if you assign a closure to a property of a class instance and the body of that closure captures the instance. This capture might occur because the closure’s body accesses a property of the instance, such as self.someProperty, or because the closure called a method on the instance, such as self.someMethod(). In either of the case, these access would cause the closure to “capture” self, creating a strong reference cycle.</p><blockquote>This strong reference cycle occurs because closures, like classes, are reference types.</blockquote><p>Lets see how this strong reference cycle is caused. Suppose you have a <strong>Person</strong> Class with <strong>firstName</strong>, <strong>lastName</strong> property. You also have a <strong>lazy</strong> closure property which would return you a full name by combining <strong>firstName</strong> and <strong>lastName</strong>. Lets name it as <strong>fullName </strong>of type<strong>()-&gt;String </strong>To know more about closure, you can read the<strong> </strong><a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html"><strong>Apple Documentation</strong></a><strong>.</strong></p><p>The <strong>Person</strong> Class provides a single initializer, which takes a 2 argument (<strong>firstName</strong> and <strong>lastName</strong>). The class also defines a deinitializer, which prints a message to show when an <strong>Person</strong> instance is deallocated.</p><pre><strong>class</strong> <strong>Person</strong> {<br>    <strong>var</strong> firstName: <strong>String</strong>?<br>    <strong>var</strong> lastName: <strong>String</strong>?</pre><pre>    <strong>lazy</strong> <strong>var</strong> fullName: <strong>()-&gt;String</strong> = {<br>        <strong>return</strong> (&quot;\(<strong>self</strong>.firstName!) \(<strong>self</strong>.lastName!)&quot;)<br>    }</pre><pre>    <strong>init</strong>(firstName: <strong>String</strong>, lastName: <strong>String</strong>) {<br>        <strong>self</strong>.firstName = firstName<br>        <strong>self</strong>.lastName = lastName<br>        <strong>print</strong>(&quot;Person Class is being initialised&quot;)<br>    }</pre><pre>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;Person Class is being de-initialised&quot;)<br>    }<br>}</pre><blockquote>The <strong>person</strong> variable above is defined as an optional <strong>Person</strong>, so that it can be set to <strong><em>nil</em></strong> to demonstrate the presence of a strong reference cycle.</blockquote><p>The <strong>Person</strong> instance’s <strong>fullName</strong> property holds a strong reference to its closure. Also, because the closure refers to <strong>self</strong> within its body (as a way to reference <strong>self.firstName</strong> and <strong>self.lastName</strong>), the closure captures <strong>self</strong> . This means that it also holds a strong reference to the <strong>Person</strong> instance. As a result, strong reference cycle is created between the two (<strong><em>Image 2–1</em></strong>).</p><blockquote>Even though the closure refers to <strong>self</strong> multiple times, Swift ensures that it only captures <strong>one</strong> strong reference to the <strong>Person</strong> instance.</blockquote><pre><strong>var</strong> person: <strong>Person</strong>? = <strong>Person</strong>(<strong>firstName:</strong> &quot;Rahul&quot;, <strong>lastName:</strong> &quot;Singh&quot;)<br>// Prints<strong> &quot;Person Class is being initialised&quot;</strong></pre><pre><strong>print</strong>(person!.<strong>fullName</strong>())<br>// Prints <strong>&quot;Rahul Singh&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*wFh5R9I0YaD5GqYgKBp3QQ.png" /><figcaption><strong>Image 2–1</strong></figcaption></figure><p>No message is logged while setting the person variable to <strong>nil</strong> . This shows that neither the <strong>Person</strong> instance nor its closure were deallocated. This is because of the <strong>Strong Reference Cycle</strong> created between the variable and closure (<strong><em>Image 2–2</em></strong>).</p><pre>person = nil</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*G35qhdh5uYAfFA9WgCcPag.png" /><figcaption><strong>Image 2–2</strong></figcaption></figure><h3>How to resolve the Strong Reference between Class and Closure?</h3><p>To solve this problem, Swift has an elegent way called as <strong>Closure Capture List</strong>. You can define the <strong><em>capture list</em> </strong>as a part of closure’s definition. A <strong><em>capture list</em></strong> defines a rule to use when capturing one or more reference types within the closure’s body. The way strong reference cycles between two class instances is resolved, ie, you declare each captured reference either to be a <strong>weak</strong> or <strong>unowned</strong> , likewise you can choose theses referneces depending on the relationships between the different parts of your code.</p><blockquote>Each item in a <strong><em>capture list</em></strong> is a pairing of the <strong>weak</strong> or <strong>unowned</strong> keyword with a reference to a class instance (such as <strong>self</strong>) or a variable initialized with some value (such as <strong>delegate</strong> = <strong>self.delegate!</strong>). These pairings are written within a pair of square braces, separated by commas.</blockquote><p>The implementation of <strong>Person</strong> Class remains same to the previous implementation, apart from the addition of a <strong><em>capture list</em></strong> within the <strong>fullName</strong> closure (<strong><em>Image 2–3)</em></strong>. The <strong><em>capture list</em></strong> is [unowned self], which means “capture self as an unowned reference rather than a strong reference”.</p><pre><strong>class</strong> <strong>Person</strong> {<br>    <strong>var</strong> firstName: <strong>String</strong>?<br>    <strong>var</strong> lastName: <strong>String</strong>?<br>    <br>    <strong>lazy</strong> <strong>var</strong> fullName: ()-&gt; <strong>String</strong> = {<strong>[unowned self] in</strong><br>        <strong>return</strong> (&quot;\(<strong>self</strong>.firstName!) \(<strong>self</strong>.lastName!)&quot;)<br>    }</pre><pre>    <strong>init</strong>(firstName: <strong>String</strong>, lastName: <strong>String</strong>) {<br>        <strong>self</strong>.firstName = firstName<br>        <strong>self</strong>.lastName = lastName<br>        <strong>print</strong>(&quot;Person Class is being initialised&quot;)<br>    }</pre><pre>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;Person Class is being de-initialised&quot;)<br>    }<br>}</pre><pre><strong>var</strong> person: <strong>Person</strong>? = <strong>Person</strong>(<strong>firstName:</strong> &quot;Rahul&quot;, <strong>lastName:</strong> &quot;Singh&quot;)<br>// Prints<strong> &quot;Person Class is being initialised&quot;</strong></pre><pre><strong>print</strong>(person!.<strong>fullName</strong>())<br>// Prints <strong>&quot;Rahul Singh&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*lbD6oOBjiMthMVCqnUM7WQ.png" /><figcaption><strong>Image 2–3</strong></figcaption></figure><p>In contrast to earlier, this time setting <strong><em>person</em></strong> variable to <strong>nil</strong> would deallocate the Person Instance and print the desired message (<strong><em>Image 3–4</em></strong>).</p><pre>person = nil<br>// Prints &quot;<strong>Person Class is being de-initialised</strong>&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*MssVKv2q9JlKIiaIJiPU-A.png" /><figcaption><strong>Image 3–4</strong></figcaption></figure><blockquote><strong><em>Source:</em></strong><em> </em><strong><em>Apple Docs</em></strong><em> and of course </em><strong><em>Internet</em></strong> <em>😄</em></blockquote><p>The Playground file can be found <a href="https://www.dropbox.com/s/ylxupdq9fuppq0f/Automatic%20Reference%20Counting-2.zip?dl=0"><strong>here</strong></a>. Feel free to play around with it. Now, poke in if we can use <strong>weak</strong> instead of <strong>unowned </strong>in the Closure of the Person Class? If yes, how can this be achieved?</p><p>Hope you have liked my tutorial on <strong>Automatic Reference Counting</strong>.</p><p>Do write your comments, if you enjoyed this post. I’d like to grow my readership. Can you help me out by sharing this blog post?</p><p><a href="https://www.linkedin.com/shareArticle?mini=true&amp;url=https%3A//medium.com/%40rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-2-848d42cf5819&amp;title=Automatic%20Reference%20Counting(ARC)%20-%20Part%202&amp;summary=&amp;source=">LinkedIn</a> <a href="https://twitter.com/home?status=https%3A//medium.com/%40rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-2-848d42cf5819">Twitter</a> <a href="https://www.facebook.com/sharer/sharer.php?u=https%3A//medium.com/%40rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-2-848d42cf5819">Facebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=848d42cf5819" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-india/swift-4-0-automatic-reference-counting-arc-part-2-848d42cf5819">Swift 4.0: Automatic Reference Counting (ARC) — Part 2</a> was originally published in <a href="https://medium.com/swift-india">Swift India</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift 4.0: Automatic Reference Counting (ARC) — Part 1]]></title>
            <link>https://medium.com/swift-india/swift-4-0-automatic-reference-counting-arc-part-1-d21d3ccf12b5?source=rss-fe51e407ffc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d21d3ccf12b5</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[swift-4]]></category>
            <category><![CDATA[cars]]></category>
            <dc:creator><![CDATA[Rahul Singh]]></dc:creator>
            <pubDate>Sun, 22 Apr 2018 18:07:54 GMT</pubDate>
            <atom:updated>2018-05-22T14:48:39.561Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift too uses Automatic Reference Counting (ARC) to keep track and manage all the objects created by the application. This signifies that it handles Memory Management itself and we do not need to take care of it. But there are few situations where we as a developer need to provide few other information, in particularly, the relationship between objects, to avoid Memory Leaks. We would be discussing those situations here.</p><blockquote>Reference Counting applies only to the instances of the <strong>Class</strong> because it is Reference Type. This means that multiple objects can refer to the same object. Where as <strong>Structures</strong> and <strong>Enumerations</strong> are Value Types.</blockquote><h3>How ARC works?</h3><p>Every time we create an instance of a Class, ARC allocates memory that holds information about the Type and Value it holds to. Whenever we assign a class instance to a constant or variable, that particluar constant or variable makes a strong reference to the instance and does not allow it to be deallocated as long as that strong reference exists. ARC keeps track of all the constants and variables currently it is referring to and will not deallocate until the last active reference is released. Once, all the active references are removed, ARC frees up the memory by removing the instance. This ensures that class instances do not take up unnecessary memory when not required.</p><p>Let’s see with an Example:</p><pre>class <strong>Employee</strong> {<br>    let empName: <strong>String</strong></pre><pre>    <strong>init</strong>(employeeName empName: <strong>String</strong>) {<br>        <strong>self.</strong>empName = empName<br>        <strong>print</strong>(&quot;\(empName) is being initialized&quot;)<br>    }<br>    <br>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;\(empName) is being deinitialized&quot;)<br>    }<br>}</pre><pre><strong>var</strong> emp1: <strong>Employee</strong>?<br><strong>var</strong> emp2: <strong>Employee</strong>?<br><strong>var</strong> emp3: <strong>Employee</strong>?</pre><p>In the above Class named <strong>Employee</strong>, we have an initialiser that sets the instance and prints a message to indicate that initialisation is in process. This also has a de-initialiser that prints out a message when an insance of the Class is deallocated.</p><p>Now, let’s create <strong>Employee</strong> instance and assign it to the first variable <strong>emp1</strong>.</p><pre>emp1 =  <strong>Employee</strong>(employeeName: &quot;John Appleseed&quot;)<br>// Prints <strong>&quot;John Appleseed is being initialized&quot;</strong></pre><p>Now that <strong>Employee</strong> instance is assigned to the <strong>emp1.</strong> There is a strong reference from <strong>emp1</strong> to the new <strong>Employee</strong> instance and ARC ensures that this <strong>Employee</strong> is kept in memory and not deallocated. <strong>Retain Count</strong> has increased by <strong>1</strong>.</p><pre><strong>emp2</strong> = <strong>emp1</strong><br><strong>emp3</strong> = <strong>emp1</strong></pre><p>Now, there are 3 strong references to <strong>Employee</strong> instance that we created at the beginning. The <strong>Retain Count</strong> would now be <strong>3</strong>.</p><p>Now, lets break <strong>2</strong> of these strong references (including the original reference) by assigning <strong>nil</strong>. The <strong>Retain Count</strong> would now be 1. <strong>Employee</strong> instance would not deallocate as there is still exisits 1 last strong reference (<strong>emp3</strong>).<br>ARC would not deallocate the <strong>Employee</strong> instance until the 3rd and final strong reference is broken.</p><pre><strong>emp1</strong> = nil // Retain Count would decrease by 1<br><strong>emp2</strong> = nil // Retain Count would decrease by 1</pre><p>As soon as 3rd and final strong reference is set to <strong>nil</strong>, no further strong reference exisits. ARC is now free to remove the <strong>Employee</strong> instance from the Memory. Pretty Simple Huh!!. Lets dive deep in.</p><pre><strong>emp3</strong> = nil<br>// Prints &quot;<strong>John Appleseed is being deinitialized&quot;</strong></pre><h3>What are Reference Cycles?</h3><p>There could be a scenario where two class instance holds a strong Reference to each other and there is no way for the system to deallocate them. This means that the <strong>Retain Count</strong> of both the class insance would never come down to 0. This is known as <strong><em>Strong Refernce Cycle</em></strong>. Let us see this with an example.</p><pre><strong>class</strong> <strong>Employee</strong> {<br>    <strong>let</strong> empName: <strong>String</strong><br>    <strong>var</strong> dept: <strong>Department</strong>?<br>    <br>    <strong>init</strong>(employeeName empName: <strong>String</strong>) {<br>        <strong>self.</strong>empName = empName<br>        <strong>print</strong>(&quot;\(empName) is being initialized&quot;)<br>    }<br>    <br>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;\(empName) is being deinitialized&quot;)<br>    }<br>}</pre><pre><strong>class</strong> <strong>Department</strong> {<br>    <strong>let</strong> deptName: <strong>String</strong><br>    <strong>var</strong> emp: <strong>Employee</strong>?</pre><pre>    <strong>init</strong>(departmentName deptName: <strong>String</strong>) {<br>        <strong>self.</strong>deptName = deptName<br>        <strong>print</strong>(&quot;\(deptName) is being initialized&quot;)<br>    }<br> <br>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;\(deptName) is being deinitialized&quot;)<br>    }<br>}</pre><p>In the above code, we have created 2 class. One for <strong>Employee</strong> and other for <strong>Department</strong>. Both these classes have strong reference to <strong>Department(</strong><strong>dept) </strong>and <strong>Employee(</strong><strong>emp)</strong> instance respectively. The <strong>Retain Count</strong> for <strong>john</strong> and <strong>iOS</strong> variable would be <strong>1</strong>.</p><pre><strong>var</strong> john: <strong>Employee</strong>? = <strong>Employee</strong>(employeeName: &quot;john&quot;)<br><strong>var</strong> iOS: <strong>Department</strong>? = <strong>Department</strong>(departmentName: &quot;iOS&quot;)</pre><pre><strong>// Prints </strong>&quot;john is being initialized&quot;<strong><br>// Prints </strong>&quot;iOS is being initialized&quot;</pre><p>We would create an <strong>Employee</strong> and <strong>Department</strong> instance. This in turn would create a strong reference to <strong>john</strong> and <strong>iOS</strong> variable (<strong><em>Image 1–1</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*wjjbL4zxCnwihaRQch8oYw.png" /><figcaption><strong>Image 1–1</strong></figcaption></figure><p>Now assign the two instances together so that Employee is associated with Department and Department is linked to Employee. This would create a strong reference cycle among each other and the <strong>Retain Count</strong> for <strong>john</strong> and <strong>iOS</strong> variable would increase by 1. <strong>Retain</strong> <strong>Count</strong> for <strong>john</strong> and <strong>iOS</strong> variable is <strong>2</strong> (<strong><em>Image 1-2</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*vUgrYVMRGrvvDbxCsRGenQ.png" /><figcaption><strong>Image 1-2</strong></figcaption></figure><pre>john!.dept = iOS<br>iOS!.emp = john</pre><p>If we set the <strong>john</strong> and <strong>iOS</strong> variable to <strong>nil </strong>, there would still exisits a strong reference between the Employee and Department instance which now cannot be broken. <strong>Retain</strong> <strong>Count</strong> now would be <strong>1</strong>. Since, the <strong>Retain Count</strong> did not drop to <strong>0</strong>, ARC did not deallocate the instances. Such scenarios causes memory leaks in our application (<strong><em>Image 1-3</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*xKUYcpw9QEVG5B7UWqAXqA.png" /><figcaption><strong>Image 1-3</strong></figcaption></figure><h3>How to Resolve these Reference Cycles?</h3><p>Swift provides two ways of resolving these Strong Reference Cycles: <strong>weak </strong>and <strong>unowned reference</strong>.</p><h3>Weak Reference</h3><p>Apple Doc states that a weak reference is a reference that does not keep a strong hold on the instance it refers to, and so does not stop <strong>ARC</strong> from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing the <strong>weak</strong> keyword before a property or variable declaration.</p><p><strong>Weak Reference</strong> should be used in cases where other instance can be deallocated first without any issue. Confused!!! Let us see this with an example.</p><p>Just add <strong>weak</strong> before <strong>emp</strong> variable in the <strong>Deparment</strong> Class. The class would look like the below.</p><pre><strong>class</strong> <strong>Department</strong> {<br>    <strong>let</strong> deptName: <strong>String</strong><br>    <strong><em>weak</em></strong> <strong>var</strong> emp: <strong>Employee</strong>?</pre><pre><strong>init</strong>(departmentName deptName: <strong>String</strong>) {<br>        self.deptName = deptName<br>        <strong>print</strong>(&quot;\(deptName) is being initialized&quot;)<br>    }<br> <br>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;\(deptName) is being deinitialized&quot;)<br>    }<br>}</pre><p>Now, if we create instance variable of <strong>Employee</strong> and <strong>Deparment</strong> and assign these instances to each other, <strong>Employee</strong> instance would hold a strong reference to the <strong>Deparment</strong> but <strong>Department</strong> insatance would hold a weak reference to the <strong>Employee </strong>instance. <strong>Retain Count</strong> of <strong>Employee </strong>would be <strong>1</strong> where as <strong>Retain Count</strong> of <strong>Department</strong> would be <strong>2 </strong>(<strong><em>Image 1-4</em></strong>).</p><pre><strong>var</strong> john: <strong>Employee</strong>? = <strong>Employee</strong>(employeeName: &quot;john&quot;)<br><strong>var</strong> iOS: <strong>Department</strong>? = <strong>Department</strong>(departmentName: &quot;iOS&quot;)</pre><pre>john!.dept = iOS<br>iOS!.emp = john</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*5-6VhAAg1NFemmWMh5HgqQ.png" /><figcaption><strong>Image 1-4</strong></figcaption></figure><p>Since <strong>Employee</strong> instance has only one strong reference, as soon as we set the <strong>Employee</strong> instance to <strong>nil</strong>, the <strong>Retain Count</strong> would become <strong>0</strong> and it would be deallocated. Also, the <strong>emp</strong> variable of the <strong>Department</strong> would be set to <strong>nil</strong> reducing the <strong>Retain Count</strong> to <strong>1</strong>(<strong><em>Image 1-5</em></strong>).</p><pre>john = nil<br>// Prints &quot;<strong>john is being deinitialized&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*wO0uAOsXqfIXzF9EMBKDiQ.png" /><figcaption><strong>Image 1-5</strong></figcaption></figure><p>Now, the only strong Reference left to the <strong>Deparment</strong> is from the <strong>iOS</strong> variable. Setting <strong>nil</strong> to the <strong>iOS</strong> variable would reduce the <strong>Retain Count</strong> by 1, thus making it 0. Hence, <strong>ARC</strong> would <strong>deallocate</strong> the <strong>Department</strong> instance (<strong><em>Image 1-6</em></strong>).</p><pre>iOS = nil<br>// Prints <strong>&quot;iOS is being deinitialized&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*zR6Pi11mPAVpatF-oC45zg.png" /><figcaption><strong>Image 1-6</strong></figcaption></figure><h3>Unowned Reference</h3><p>Unowned reference too does not keep a strong hold on the instance it refers to. However, there is one major difference between Week and Unowned Reference. It should only be used when we are sure that both the instance has almost same or more life span. A Weak references must be defined using optional whereas Unowned references must be defined using non-optional types. Both do not increase the <strong>Retain Count</strong>. Lets see an example.</p><p>Suppose we are creating an application for a car Company where they need to keep track of every vehicle sold to the People. We would have <strong>Vehicle</strong> and <strong>Driver</strong> Model class.</p><p>In the following we have created 2 Class. <strong>Owner</strong> and <strong>Vehicle</strong> class. In this <strong>Owner</strong> may or may not <strong>Vehicle</strong> but <strong>Vehicle</strong> to come on Road would need to have a <strong>Owner </strong>. In such case, the <strong>Owner</strong> should hold a <strong>strong</strong> reference to the <strong>Vechicle</strong> but the <strong>Vehicle</strong> should just have a unowned reference to the <strong>Owner</strong>. This is because there is no<strong>Vehicle</strong> which doen’t have an <strong>Owner</strong> . So, its existence only lies till the Owner owns the Vehicle. But the same doesn’t hold true for Owner.</p><pre><strong>class Owner</strong> {<br>    <strong>let</strong> ownerName: <strong>String</strong><br>    <strong>var</strong> vehicle: <strong>Vehicle</strong>?<br><br>    <strong>init</strong>(ownerName name: <strong>String</strong>) {<br>        self.ownerName = name<br>        <strong>print</strong>(&quot;\(ownerName) is being initialized&quot;)<br>    }</pre><pre>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;\(ownerName) is being deinitialized&quot;)<br>    }<br>}</pre><pre><strong>class</strong> <strong>Vehicle</strong> {<br>    <strong>let</strong> vehicleNumber: <strong>String</strong><br>    <strong>unowned</strong> <strong>let</strong> owner: <strong>Owner</strong></pre><pre>    <strong>init</strong>(vehicleNumber number: <strong>String</strong>, owner: <strong>Owner</strong>) {<br>        self.vehicleNumber = number<br>        self.owner = owner</pre><pre>        <strong>print</strong>(&quot;\(vehicleNumber) is being initialized&quot;)<br>    }</pre><pre>    <strong>deinit</strong> {<br>        <strong>print</strong>(&quot;\(vehicleNumber) is being deinitialized&quot;)<br>    }<br>}</pre><p>Now, lets create the <strong>Owner</strong> and <strong>Vehicle</strong> instance and associate with each other. The <strong>Retain Count</strong> for the <strong>Owner</strong> instance is 1 which is held by variable. In case of <strong>Vehicle</strong>, its just the <strong>Owner</strong> who is holding the <strong>strong</strong> reference to it (<strong><em>Image 2–1</em></strong>).</p><pre>var appleseed: <strong>Owner</strong>?<br>appleseed = Owner(ownerName: &quot;John Appleseed&quot;)</pre><pre>appleseed?.vehicle = <strong>Vehicle</strong>(vehicleNumber: &quot;TE 12 MP 5678&quot;, owner: appleseed!)</pre><pre>// Prints <strong>&quot;John Appleseed is being initialized&quot;</strong><br>// Prints <strong>&quot;TE 12 MP 5678 is being initialized&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*mYd5YPiss4naETfcweg8ug.png" /><figcaption><strong>Image 2–1</strong></figcaption></figure><p>Its existence is only till the existence of the Owner. Once, the Owner instance is deallocated, the Vehicle instance would automatically be deallocated as there is no strong reference associated to it (<strong><em>Image 2–2, Image2–3</em></strong>).</p><pre>appleseed = nil<br>// Prints <strong>&quot;John Appleseed is being deinitialized&quot;</strong><br>// Prints <strong>&quot;TE 12 MP 5678 is being deinitialized&quot;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*sQGRFS_wci7cbIruOVlODQ.png" /><figcaption><strong>Image 2–2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*HNZBmITbijsLXm_f-wbP2g.png" /><figcaption><strong>Image2–3</strong></figcaption></figure><blockquote><strong><em>Source:</em></strong><em> </em><strong><em>Apple Docs</em></strong><em> and of course </em><strong><em>Internet</em></strong> <em>😄</em></blockquote><p>We’ve covered the basics of <strong>ARC</strong> in this tutorial. You can find the Playground <a href="https://www.dropbox.com/s/p673dlimkx73s8d/Automatic%20Reference%20Counting-1.zip?dl=0">here</a>. Feel free to download and play around with it.</p><p>Part 2 of this series can be found <a href="https://medium.com/@rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-2-848d42cf5819">here</a>.</p><p>Do write your comments, if you enjoyed this post.</p><p>I’d like to grow my readership. Can you help me out by sharing this blog post?</p><p><a href="https://www.linkedin.com/shareArticle?mini=true&amp;url=https%3A//medium.com/%40rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-1-d21d3ccf12b5&amp;title=Swift%204.0%3A%20Automatic%20Reference%20Counting%20(ARC)%E2%80%8A%E2%80%94%E2%80%8APart%C2%A01&amp;summary=&amp;source=">LinkedIn</a> <a href="https://twitter.com/home?status=https%3A//medium.com/%40rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-1-d21d3ccf12b5">Twitter</a> <a href="https://www.facebook.com/sharer/sharer.php?u=https%3A//medium.com/%40rahulsingh05/swift-4-0-automatic-reference-counting-arc-part-1-d21d3ccf12b5">Facebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d21d3ccf12b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-india/swift-4-0-automatic-reference-counting-arc-part-1-d21d3ccf12b5">Swift 4.0: Automatic Reference Counting (ARC) — Part 1</a> was originally published in <a href="https://medium.com/swift-india">Swift India</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>