<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[ThomasHanning.com]]></title><description><![CDATA[iOS Development & Swift Blog]]></description><link>https://www.thomashanning.com/</link><image><url>https://www.thomashanning.com/favicon.png</url><title>ThomasHanning.com</title><link>https://www.thomashanning.com/</link></image><generator>Ghost 5.79</generator><lastBuildDate>Fri, 23 Feb 2024 00:39:02 GMT</lastBuildDate><atom:link href="https://www.thomashanning.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Swift: Comparing Enums With Associated Values]]></title><description><![CDATA[Comparing enums in Swift is very straightforward – as long as they don’t have associated values. In this post, we will discuss what you can do in that case.]]></description><link>https://www.thomashanning.com/swift-comparing-enums-with-associated-values/</link><guid isPermaLink="false">63d38b8127e59a003deebe77</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sun, 12 Feb 2023 09:56:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1457803097035-3ace37af34a7?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDQwfHxhcHBsZXN8ZW58MHx8fHwxNjc2MTk1Njcx&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1457803097035-3ace37af34a7?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDQwfHxhcHBsZXN8ZW58MHx8fHwxNjc2MTk1Njcx&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="Swift: Comparing Enums With Associated Values"><p><em><em><em><em>This post was originally published on 0</em></em>2<em><em>/</em></em>24<em><em>/1</em></em>8<em><em> and updated on </em></em>02<em><em>/</em></em>12<em><em>/23</em></em></em></em>.</p><p>Let&#x2019;s start with a simple case:</p><pre><code class="language-swift">enum TestEnum {
    case testA
    case testB
}

let testEnum1 = TestEnum.testA
let testEnum2 = TestEnum.testB
let testEnum3 = TestEnum.testA

print(testEnum1 == testEnum2) //false
print(testEnum1 == testEnum3) //true</code></pre><p>So in this example, we are defining an enum called <code>TestEnum</code>, which has two cases. Then we are declaring two variables of this type and we compare them &#x2013; they behave as expected and everything is working fine.</p><h3 id="enums-with-associated-values">Enums With Associated Values</h3><p>Now let&#x2019;s look into the hard stuff. First, we add an associated value to one of the cases:</p><pre><code>enum TestEnum {
    case testA(Int)
    case testB
}

let testEnum1 = TestEnum.testA(5)</code></pre><p>As already explained <a href="https://www.thomashanning.com/swift-enums/">in this post</a>, you can use an enum with associated values to add some additional information. It can only be accessed within a switch statement though:</p><pre><code class="language-swift">enum TestEnum {
    case testA(Int)
    case testB
}

let testEnum1 = TestEnum.testA(5)


switch testEnum1 {
case .testA(let a):
    print(&quot;Case testA with associated value \(a)&quot;)
case .testB:
    print(&quot;Case testB&quot;)
}</code></pre><p>As expected, the output is</p><pre><code>Case testA with associated value 5</code></pre><h3 id="comparing-enums-with-associated-values">Comparing Enums With Associated Values</h3><p>So, now let&#x2019;s try to compare two of them:</p><pre><code>enum TestEnum {
    case testA(Int)
    case testB
}

let testEnum1 = TestEnum.testA(5)
let testEnum2 = TestEnum.testB

if testEnum1 == testEnum2 {   //COMPILER ERROR!!!
    print(&quot;equal&quot;)
}</code></pre><p>In this case, we get a compiler error:</p><pre><code>Binary operator &apos;==&apos; cannot be applied to two &apos;TestEnum&apos; operands</code></pre><p>And this makes sense because it&#x2019;s not clear when they are equal. For example, are two <code>testA</code> values equal if their associated values are equal? Or are two <code>testA</code> values always equal? It depends on the circumstances and the meaning of the enum.</p><div class="kg-card kg-product-card"><div class="kg-product-card-container"><div class="kg-product-card-title-container"><h4 class="kg-product-card-title">Subscribe to ThomasHanning.com</h4></div><div class="kg-product-card-description"><ul><li><a href="https://www.thomashanning.com/ios-dev-swift-newsletter/">iOS Dev &amp; Swift Email Newsletter </a>- Curated iOS development and Swift resources from around the web</li><li>Exclusive posts for members only</li><li>Be the first to know when new posts are released</li><li>Write comments</li></ul></div><a href="https://www.thomashanning.com/#/portal/signup" class="kg-product-card-button kg-product-card-btn-accent" target="_blank" rel="noopener noreferrer"><span>Subscribe</span></a></div></div><h3 id="equatable-protocol">Equatable protocol</h3><p>But we can implemente our definition of <code>==</code>. For that, we implement the Equatable protocol:</p><pre><code>enum TestEnum {
    case testA(Int)
    case testB
}

extension TestEnum: Equatable {
    
    public static func ==(lhs: TestEnum, rhs:TestEnum) -&gt; Bool {
        switch lhs {
        case .testA(let a):
            switch rhs {
            case .testA(let b):
                return a == b
            case .testB:
                return false
            }
        case .testB:
            switch rhs {
            case .testB:
                return true
            case .testA:
                return false
            }
        }
        
    }
}</code></pre><p>That&#x2019;s a lot of code for a little bit of work, but it does the job! Now, two <code>TestEnum</code> are equal, if one of the following two conditions is true:</p><ul><li>Both are <code>testB</code> cases.</li><li>Both are <code>testA</code> cases AND their associated values are equal.</li></ul><p>Of course, it&#x2019;s possible to write that code a little bit more elegant:</p><pre><code>enum TestEnum {
    case testA(Int)
    case testB
}

extension TestEnum: Equatable {
    
    public static func ==(lhs: TestEnum, rhs:TestEnum) -&gt; Bool {
        
        switch (lhs,rhs) {
        case (.testB, .testB):
            return true
        case (.testA(let a), .testA(let b)):
            return a == b
        default:
            return false
        }
        
    }
}</code></pre><p>And now let&#x2019;s test whether it&#x2019;s working as expected:</p><pre><code>let testEnum1 = TestEnum.testA(5)
let testEnum2 = TestEnum.testA(10)
let testEnum3 = TestEnum.testA(5)
let testEnum4 = TestEnum.testB
let testEnum5 = TestEnum.testB

print(testEnum1 == testEnum2) //false
print(testEnum1 == testEnum3) //true
print(testEnum1 == testEnum4) //false
print(testEnum4 == testEnum5) //true</code></pre><p>It can also be implemented in another way, like this:</p><ul><li>Both are <code>testB</code> cases.</li><li>Both are <code>testA</code> cases</li></ul><p>Then, the associated values don&#x2019;t influence the equality:</p><pre><code>extension TestEnum: Equatable {
    
    public static func ==(lhs: TestEnum, rhs:TestEnum) -&gt; Bool {
        
        switch (lhs,rhs) {
        case (.testB, .testB):
            return true
        case (.testA,.testA):
            return true
        default:
            return false
        }
    }
}

let testEnum1 = TestEnum.testA(5)
let testEnum2 = TestEnum.testA(10)
let testEnum3 = TestEnum.testA(5)
let testEnum4 = TestEnum.testB
let testEnum5 = TestEnum.testB

print(testEnum1 == testEnum2)
print(testEnum1 == testEnum3)
print(testEnum1 == testEnum4)
print(testEnum4 == testEnum5)</code></pre><p>As said before, it depends on the context.</p>]]></content:encoded></item><item><title><![CDATA[Merge Sort In Swift]]></title><description><![CDATA[Merge sort is a sorting algorithm that uses a divide-and-conquer approach to sort an array of elements. It's a highly efficient algorithm that is widely used in various applications. In this post, we will implement merge sort  in Swift.]]></description><link>https://www.thomashanning.com/merge-sort-in-swift/</link><guid isPermaLink="false">63d38b8127e59a003deebe57</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sun, 05 Feb 2023 11:08:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1521192520982-5d6ca468a30f?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fHNvcnR8ZW58MHx8fHwxNjc1NTkzNzEy&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1521192520982-5d6ca468a30f?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fHNvcnR8ZW58MHx8fHwxNjc1NTkzNzEy&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="Merge Sort In Swift"><p><em><em>This post was originally published on 0</em>2<em>/</em>09<em>/1</em>7<em> and updated on </em>02<em>/</em>05<em>/23</em></em>.</p><p>Let&apos;s start by looking at the mechanics of merge sort:</p><h3 id="understanding-the-mechanics-of-merge-sort">Understanding the Mechanics of Merge Sort</h3><p>The <a href="https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm?ref=thomashanning.com">divide-and-conquer approach</a> is a technique used by <a href="https://en.wikipedia.org/wiki/Merge_sort?ref=thomashanning.com">merge sort</a> to sort an array of elements. It starts by dividing the input array into two halves and continues to divide each half until each subarray contains only one element. This approach allows the algorithm to break down a complex problem into smaller, more manageable subproblems that can be solved more easily.</p><p>Once the input array has been divided into subarrays containing only one element, the algorithm begins the merging process. The merging process involves comparing and merging adjacent subarrays into larger sorted subarrays. This process is repeated until the entire input array is sorted and merged into a single sorted array. The merging process ensures that the elements in the final sorted array are in the correct order.</p><h3 id="time-and-space-complexity">Time and space complexity</h3><p>Merge sort has a <a href="https://www.freecodecamp.org/news/time-complexity-of-algorithms/?ref=thomashanning.com">time complexity</a> of O(n log n), where n is the number of elements in the array. This is because the algorithm divides the array into two halves in each recursive step, and each step requires O(n) time to merge the two sorted halves. The log n term comes from the number of recursive steps required to divide the array into single elements.</p><p>The <a href="https://www.geeksforgeeks.org/g-fact-86/?ref=thomashanning.com">space complexity</a> of merge sort is O(n), as the algorithm requires an auxiliary array to store the sorted elements while merging the two halves. This is because the algorithm sorts the elements in-place, meaning that it operates on the original array rather than creating a new one.</p><p>It&apos;s important to note that the time and space complexities of merge sort are the same regardless of the order of the elements in the original array. This makes it a stable sorting algorithm, meaning that elements that have the same value maintain their relative order in the final sorted array.</p><div class="kg-card kg-product-card"><div class="kg-product-card-container"><div class="kg-product-card-title-container"><h4 class="kg-product-card-title">Subscribe to ThomasHanning.com</h4></div><div class="kg-product-card-description"><ul><li>&quot;iOS Dev &amp; Swift Email Newsletter&quot; - The newsletter of curated iOS development and Swift resources from around the web.&#xA0;</li><li>Get the latest blog posts from ThomasHanning.com directly into your inbox</li><li>Write comments</li></ul></div><a href="https://www.thomashanning.com/#/portal/signup" class="kg-product-card-button kg-product-card-btn-accent" target="_blank" rel="noopener noreferrer"><span>Subscribe</span></a></div></div><h3 id="example">Example</h3><figure class="kg-card kg-image-card"><img src="https://www.thomashanning.com/content/images/2023/02/MergeSort01.jpeg" class="kg-image" alt="Merge Sort In Swift" loading="lazy" width="700" height="700" srcset="https://www.thomashanning.com/content/images/size/w600/2023/02/MergeSort01.jpeg 600w, https://www.thomashanning.com/content/images/2023/02/MergeSort01.jpeg 700w"></figure><p>We want to sort the array [98,1,45,13,6]. First, the array will be divided into subarrays [98,1,45] and [13,6]. Then, the divided lists will be divided again. This process will be continued until &#xA0;every array has exactly one item. In the picture, this is accomplished in line four. </p><p>Then the merging process starts: Always two lists will be merged. So the two arrays [98] and [1] will be merged into [1,98]. Additionally, the arrays [45] and [13] will be merged into [13,45]. It&apos;s important to note that in this merging process, the elements get sorted: We look at the first elements and take the smaller element. Then we continue until both arrays are merged.</p><p>The process will be repeated until only one list is left &#x2013; the sorted list.</p><h3 id="merge-sort-in-swift">Merge Sort in Swift</h3><p>Now let&#x2019;s implement the algorithm in <a href="https://www.thomashanning.com/tag/swift/">Swift</a>. There are different approaches for solving that problem, we will take a recursive one:</p><pre><code class="language-swift">import Foundation

func merge(left:[Int],right:[Int]) -&gt; [Int] {
    var mergedList = [Int]()
    var left = left
    var right = right
    
    while left.count &gt; 0 &amp;&amp; right.count &gt; 0 {
        if left.first! &lt; right.first! {
            mergedList.append(left.removeFirst())
        } else {
            mergedList.append(right.removeFirst())
        }
    }

    return mergedList + left + right
}

func mergeSort(list:[Int]) -&gt; [Int] {
    guard list.count &gt; 1 else {
        return list
    }
    
    let leftList = Array(list[0..&lt;list.count/2])
    let rightList = Array(list[list.count/2..&lt;list.count])
    
    return merge(left: mergeSort(list:leftList), right: mergeSort(list:rightList))
}</code></pre><p>The function mergeSort divides the list into two lists and returns the merged and sorted list by using the function merge. Within the function call, the function calls itself recursively for both lists. When mergeSort gets a list, that has just one element, it returns the whole list.</p><p>The function merge always compares the first items of the two lists and appends the smaller item to the new sorted list.</p><h3 id="testing-the-algorithm">Testing the algorithm</h3><p>Now we can test the algorithm:</p><pre><code class="language-swift">var list = [Int]()

for _ in 0..&lt;100 {
    list.append(Int(arc4random_uniform(UInt32(1000))))
}

print(list)

print()

print(mergeSort(list: list))</code></pre><p>The generated output is:</p><pre><code class="language-swift">[723, 647, 801, 378, 630, 789, 654, 1, 66, 848, 178, 837, 79, 921, 880, 663, 835, 497, 459, 59, 940, 380, 37, 897, 29, 346, 11, 192, 955, 652, 276, 205, 903, 935, 762, 681, 211, 218, 586, 393, 372, 708, 202, 660, 35, 654, 392, 839, 710, 948, 50, 726, 999, 79, 881, 324, 22, 49, 564, 639, 117, 256, 978, 179, 942, 710, 7, 389, 701, 128, 239, 548, 848, 771, 538, 548, 359, 50, 752, 892, 87, 107, 959, 717, 846, 546, 417, 350, 212, 239, 938, 788, 75, 16, 664, 897, 588, 368, 199, 350]

[1, 7, 11, 16, 22, 29, 35, 37, 49, 50, 50, 59, 66, 75, 79, 79, 87, 107, 117, 128, 178, 179, 192, 199, 202, 205, 211, 212, 218, 239, 239, 256, 276, 324, 346, 350, 350, 359, 368, 372, 378, 380, 389, 392, 393, 417, 459, 497, 538, 546, 548, 548, 564, 586, 588, 630, 639, 647, 652, 654, 654, 660, 663, 664, 681, 701, 708, 710, 710, 717, 723, 726, 752, 762, 771, 788, 789, 801, 835, 837, 839, 846, 848, 848, 880, 881, 892, 897, 897, 903, 921, 935, 938, 940, 942, 948, 955, 959, 978, 999]</code></pre><p>As we can see, we get the expected results.</p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[iOS Dev & Swift Newsletter #1]]></title><description><![CDATA[The first month of the year is already over! In the first few weeks, there were already very interesting blog posts and YouTube videos in the world of iOS development and Swift.]]></description><link>https://www.thomashanning.com/ios-dev-swift-newsletter-1/</link><guid isPermaLink="false">63d7ec53e021d7003db420ac</guid><category><![CDATA[Newsletter]]></category><category><![CDATA[iOS development]]></category><category><![CDATA[Swift]]></category><category><![CDATA[SwiftUI]]></category><category><![CDATA[Resources]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sat, 04 Feb 2023 14:44:09 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1577863231392-b5de256c3310?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDJ8fGphbnVhcnl8ZW58MHx8fHwxNjc1MDk3MDQw&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<div class="kg-card kg-header-card kg-width-full kg-size-small kg-style-accent" style data-kg-background-image><h2 class="kg-header-card-header" id="ios-development">iOS Development</h2></div><img src="https://images.unsplash.com/photo-1577863231392-b5de256c3310?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDJ8fGphbnVhcnl8ZW58MHx8fHwxNjc1MDk3MDQw&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="iOS Dev &amp; Swift Newsletter #1"><p>Code styling is both a subjective and important topic. In this post, Daniel James makes many good proposals.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://medium.com/@james.daniel.isaiah/how-senior-ios-engineers-style-code-for-performance-and-clarity-467fa2a9d1f1?ref=thomashanning.com"><div class="kg-bookmark-content"><div class="kg-bookmark-title">How Senior iOS Engineers Style Code: Performance And Clarity</div><div class="kg-bookmark-description">This article is the result of studying Swift Style from The Pragmatic Bookshelf and lived experience. Any level iOS engineer can use this&#x2026;</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://cdn-static-1.medium.com/_/fp/icons/Medium-Avatar-500x500.svg" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">Medium</span><span class="kg-bookmark-publisher">Daniel James</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://miro.medium.com/max/500/1*BhxNuh8wQHztInYH7gQt2w.png" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr><p>Watch this video if you want to know how to create the sliders of the iOS control center:</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/k0mm-Dh9C9U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen title="iOS Control Center Volume Control Slider Animation Using SwiftUI | Hero Animation | Xcode 14"></iframe></figure><hr><div class="kg-card kg-header-card kg-width-full kg-size-small kg-style-accent" style data-kg-background-image><h2 class="kg-header-card-header" id="swift">Swift</h2></div><p>This is a short but good post about the options for adding animations to <a href="https://www.thomashanning.com/tag/swiftui/">SwiftUI</a> views:</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://tanaschita.com/20230116-animations-in-swiftui/?ref=thomashanning.com"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Understanding basic animations in SwiftUI</div><div class="kg-bookmark-description">Learn different options to animate SwiftUI views in your iOS applications. Understand the two animation options animation(_:value:) view modifier and the withAnimation(_:_:) global function.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://tanaschita.com/favicon.ico" alt="iOS Dev &amp; Swift Newsletter #1"></div></div><div class="kg-bookmark-thumbnail"><img src="https://tanaschita.com/og/20230116-animations-in-swiftui.png" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr><p>Async/await is great, but it&apos;s even greater if you know how to combine it with the good old completion handlers:</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.danijelavrzan.com/posts/2023/01/completion-handler-async-function/?ref=thomashanning.com"><div class="kg-bookmark-content"><div class="kg-bookmark-title">How to use async/await with completion handlers | Danijela&#x2019;s blog</div><div class="kg-bookmark-description">When the new Swift concurrency model was announced at WWDC 2021 we all wanted to jump on that wagon. However, rewriting your entire codebase might not be the best solution. Instead, you have the option to slowly start adapting the new model by bridging the old code with the new.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.danijelavrzan.com/images/favicon.png" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">Danijela&apos;s blog</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.danijelavrzan.com/images/posts/2023/01/completion-handler-async-function.png" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr><p><a href="https://www.thomashanning.com/building-memory-efficient-apps/">Performance</a> is an important topic and understanding big O notation helps you to write efficient algorithms. Additionally, it&apos;s also important to know about this topic in coding interviews.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://medium.com/@dinozavr2005/big-o-notation-in-swift-a05afc36dc3d?ref=thomashanning.com"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Big O notation in Swift</div><div class="kg-bookmark-description">This article will help novice iOS developers understand the performance of algorithms in Swift.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://cdn-static-1.medium.com/_/fp/icons/Medium-Avatar-500x500.svg" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">Medium</span><span class="kg-bookmark-publisher">Vladimir Buikliskii</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://miro.medium.com/max/1200/1*jv9t9iWK1TbpfYuAJim7cw.png" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr><p>Back in the day, there was no automatic reference counting. Today you have ARC and it&apos;s great. However, that doesn&apos;t mean you cannot make mistakes. For example, it&apos;s still possible to create a so-called <a href="https://www.thomashanning.com/retain-cycles-weak-unowned-swift/">retain cycle</a>. So it&apos;s good to understand how memory management works in Swift:</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://levelup.gitconnected.com/dive-into-swifts-memory-management-2080ac001ace?ref=thomashanning.com"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Dive into Swift&#x2019;s Memory Management</div><div class="kg-bookmark-description">Swift uses ARC to track and deallocate unused objects. Learn about the three types of reference counts and how ARC works&#x200A;&#x2014;&#x200A;in this post</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://cdn-static-1.medium.com/_/fp/icons/Medium-Avatar-500x500.svg" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">Level Up Coding</span><span class="kg-bookmark-publisher">Alex Dremov</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://miro.medium.com/max/1200/1*bsMgghRysHTaZRJaJrH--g.png" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr><div class="kg-card kg-header-card kg-width-full kg-size-small kg-style-accent" style data-kg-background-image><h2 class="kg-header-card-header" id="productivity-and-career">Productivity and Career</h2></div><p>We all know it - we start a shiny new project, but after a few weeks we <a href="https://www.thomashanning.com/how-to-overcome-loss-of-motivation/">don&apos;t work on it anymore</a>. If you want to change that, read this post:</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://betterprogramming.pub/say-goodbye-to-unfinished-pet-projects-1725c0fe1655?ref=thomashanning.com"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Say Goodbye to Unfinished Pet Projects &#x2014; Here&#x2019;s How to Effectively Plan</div><div class="kg-bookmark-description">Stop watching your pet projects collect&#xA0;dust</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://cdn-static-1.medium.com/_/fp/icons/Medium-Avatar-500x500.svg" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">Better Programming</span><span class="kg-bookmark-publisher">Ivan Reznikov</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://miro.medium.com/max/1200/1*fL4ZmeZSQkTiW_FFeZz5wQ.png" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr><p>Everybody likes the idea of becoming an entrepreneur, but how about becoming an intrapreneur?</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.deliberate-diligence.com/achieving-success-in-the-corporate-world-the-first-principal-agent-mindset/?ref=thomashanning.com"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Achieving Success in the Corporate World: The First Principal Agent Mindset</div><div class="kg-bookmark-description">Entrepreneurship may sound appealing, but it is not easy. Working for a company can be great if you find the right fit. Act as the first principal agent to climb the corporate ladder. Think independently, take ownership, build a strong reputation and advance together with your employer.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.deliberate-diligence.com/content/images/size/w256h256/format/png/2022/09/logo-favicon-3.svg" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">Deliberate Diligence - Become the Master of your Agenda</span><span class="kg-bookmark-publisher">Martin</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1444653614773-995cb1ef9efa?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDR8fENvcnBvcmF0ZXxlbnwwfHx8fDE2NzQ4MjkyNTU&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr><div class="kg-card kg-header-card kg-width-full kg-size-small kg-style-accent" style data-kg-background-image><h2 class="kg-header-card-header" id="on-thomashanningcom">On ThomasHanning.com</h2></div><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.thomashanning.com/if-let-shorthand-syntax-in-swift/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">if let shorthand syntax in Swift</div><div class="kg-bookmark-description">Using optional binding is very common in Swift. With the if let shorthand syntax it is easier to write and read. It has been introduced with Swift 5.7 and Xcode 14. if let for optional binding Optional binding is used to access optional in a safe way. For example,</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.thomashanning.com/favicon.ico" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">ThomasHanning.com</span><span class="kg-bookmark-publisher">Thomas Hanning</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1571171637578-41bc2dd41cd2?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDN8fHByb2dyYW1taW5nfGVufDB8fHx8MTY3NDkxOTk1MQ&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.thomashanning.com/swiftui-alert/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">SwiftUI: Alert</div><div class="kg-bookmark-description">Alert is equivalent to UIKit&#x2019;s UIAlertView in SwiftUI. This post is about creating and presenting an alert in SwiftUI. Hint: This post has been updated to Swift 5.7 and Xcode 14.2 Creating an alert in SwiftUI Creating an alert in SwiftUI is very straightforward: Alert(&#x2026;</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.thomashanning.com/favicon.ico" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">ThomasHanning.com</span><span class="kg-bookmark-publisher">Thomas Hanning</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.thomashanning.com/content/images/wordpress/2015/09/alert.jpg" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.thomashanning.com/should-you-still-learn-uikit/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Should You Still Learn UIKit?</div><div class="kg-bookmark-description">SwiftUI is becoming better and better. So the question arises for new iOS developers whether UIKit is still relevant enough to learn it.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.thomashanning.com/favicon.ico" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">ThomasHanning.com</span><span class="kg-bookmark-publisher">Thomas Hanning</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.thomashanning.com/content/images/wordpress/2023/01/1_o03iSVQE7CuGgeup86phig@2x.jpeg" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.thomashanning.com/xcode-for-windows/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Xcode for Windows?</div><div class="kg-bookmark-description">Xcode for Windows doesn&#x2019;t exist. Let&#x2019;s look at the alternatives.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.thomashanning.com/favicon.ico" alt="iOS Dev &amp; Swift Newsletter #1"><span class="kg-bookmark-author">ThomasHanning.com</span><span class="kg-bookmark-publisher">Thomas Hanning</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://images.unsplash.com/photo-1530133532239-eda6f53fcf0f?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDV8fG1pY3Jvc29mdCUyMHdpbmRvd3N8ZW58MHx8fHwxNjc1MDE4ODM1&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="iOS Dev &amp; Swift Newsletter #1"></div></a></figure><hr>]]></content:encoded></item><item><title><![CDATA[Xcode for Windows?]]></title><description><![CDATA[Creating iPhone apps on Windows is not possible because there's no Xcode for Windows. Let's look at the alternatives.]]></description><link>https://www.thomashanning.com/xcode-for-windows/</link><guid isPermaLink="false">63d38b8127e59a003deebe74</guid><category><![CDATA[Xcode]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sun, 29 Jan 2023 20:40:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1530133532239-eda6f53fcf0f?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDV8fG1pY3Jvc29mdCUyMHdpbmRvd3N8ZW58MHx8fHwxNjc1MDE4ODM1&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1530133532239-eda6f53fcf0f?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDV8fG1pY3Jvc29mdCUyMHdpbmRvd3N8ZW58MHx8fHwxNjc1MDE4ODM1&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="Xcode for Windows?"><p><em>This post was originally published on 01/30/18 and updated on 01/29/23</em>.</p><h3 id="what-is-xcode">What is Xcode? </h3><p>Xcode is an IDE (integrated development environment) for iOS app development. That means you can create applications for macOS, iOS, watchOS, and tvOS. Xcode is a macOS application so it is not possible to install Xcode on a Windows system. Xcode is available for download on both the Apple Developer Portal and the macOS App Store.creating iphone apps on windows</p><h3 id="should-you-install-macos-on-a-windows-pc">Should you install macOS on a Windows PC?</h3><p>In theory, it&#x2019;s possible to install macOS on a non-Apple machine, both natively and virtually. Then, Xcode could be installed. However, you shouldn&#x2019;t do that! It&#x2019;s not working very well and it&#x2019;s deemed illegal by Apple&#x2019;s licensing terms, so you must not go this route. And don&#x2019;t be fooled: Many sources on the internet promises you that this was a good idea - it is not.</p><h3 id="renting-a-mac-in-the-cloud">Renting a Mac in the cloud</h3><p>A Mac is a great computer but it&#x2019;s also quite expensive &#x2013; that&#x2019;s probably the main reason many developers wish that there were Xcode for Windows. An alternative for buying a Mac is renting a Mac in the cloud. Several providers offer that service, for example, <a href="https://www.macincloud.com/?ref=thomashanning.com" rel="noopener">this one</a>. In this particular case, Xcode is already installed, so you can start immediately. That&#x2019;s a good way at the beginning. But you cannot &#xA0;deploy the app directly to iOS devices, so in the end, it&#x2019;s still advisable to buy a Mac someday though.</p><h3 id="non-native-ways-for-developing-ios-apps">Non-native ways for developing iOS apps</h3><p>Many people who wish to install Xcode on a Windows machine want to develop iOS applications. There are options to develop iOS apps without using Xcode directly, like Microsoft MAUI and Flutter. You can develop the app once and use the code for both Android and iOS. Depending on the use case, that can be a good way. However, without a Mac, you can&apos;t build and test the app on an iOS device. </p><div class="kg-card kg-product-card"><div class="kg-product-card-container"><div class="kg-product-card-title-container"><h4 class="kg-product-card-title">Subscribe to ThomasHanning.com</h4></div><div class="kg-product-card-description"><ul><li>&quot;iOS Dev &amp; Swift Email Newsletter&quot; - The newsletter of curated iOS development and Swift resources from around the web.&#xA0;</li><li>Get the latest blog posts from ThomasHanning.com directly into your inbox</li><li>Write comments</li></ul></div><a href="https://www.thomashanning.com/#/portal/signup" class="kg-product-card-button kg-product-card-btn-accent" target="_blank" rel="noopener noreferrer"><span>Subscribe</span></a></div></div><h3 id="alternatives-for-learning-swift">Alternatives for learning Swift</h3><p><a href="https://www.thomashanning.com/become-ios-developer/">If you just want to learn iOS development</a>, but you don&apos;t have a Mac yet, then there are good alternatives. In this case, you can start by learning Swift. This is the programming language to choose for developing iOS, macOS, tvOS, and watchOS applications. </p><p>Swift is open source and there are several ways for writing Swift code on a non-Mac machine. First, there is the Swift Playgrounds app for the iPad. You can use it to write Swift code and also learn how to do it. Additionally, it&apos;s even possible to create apps with it. However, you don&apos;t have as many possibilities as with Xcode. So it&apos;s good for learning but in most cases, not enough for building a real-world application.</p><p>Since Swift is open source, it&apos;s possible to run Swift on Windows. For example, you can use <a href="https://code.visualstudio.com/?ref=thomashanning.com">Visual Studio Code</a>. It&apos;s not possible to write an iOS app this way though. There are also options on Linux. As with Swift playgrounds, that&#x2019;s a good way for starting.</p><p>If you want to learn more about Swift, take a look at <a href="https://www.thomashanning.com/category/swift/" rel="noopener">the Swift category on my blog.</a> There are also a lot of other good tutorials out there. For example, you can take a look <a href="https://www.raywenderlich.com/category/swift?ref=thomashanning.com" rel="noopener">here</a>. Swift is a very good programming language and when you are new to programming, it&#x2019;s a good choice for starting.</p><h3 id="buying-a-cheaper-mac">Buying a cheaper Mac</h3><p>If you decide to buy a Mac, you don&#x2019;t have to buy the newest machine. At the time of this writing, the newest Xcode version 14.2 runs on all Macs with at least macOS 12.5. There are nice refurbished devices in the Apple Store, but used devices are also a good alternative. This is a good way to build iOS apps.</p><h3 id="conclusion">Conclusion</h3><p>Unfortunately, there is no Xcode for Windows. And there are no ways to install macOS on a Windows machine. Renting a macOS machine in the cloud is an alternative, but you cannot deploy apps to a device. If it&#x2019;s just about learning Swift, there are alternatives like the Swift Playgrounds Apps for the iPad or running Swift code on Windows or Linux. But if you want to build iOS apps, you should buy a Mac. And on Mac you can build iOS and Android apps.</p><p><br></p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Should You Still Learn UIKit?]]></title><description><![CDATA[SwiftUI is becoming better and better. So the question arises for new iOS developers whether UIKit is still relevant enough to learn it.]]></description><link>https://www.thomashanning.com/should-you-still-learn-uikit/</link><guid isPermaLink="false">63d38b8127e59a003deebe8b</guid><category><![CDATA[SwiftUI]]></category><category><![CDATA[UIKit]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Wed, 18 Jan 2023 19:52:42 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1484069560501-87d72b0c3669?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fHF1ZXN0aW9ufGVufDB8fHx8MTY3NTY4NzkzOQ&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1484069560501-87d72b0c3669?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fHF1ZXN0aW9ufGVufDB8fHx8MTY3NTY4NzkzOQ&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="Should You Still Learn UIKit?"><p>SwiftUI is becoming better and better. So the question arises for new iOS developers whether UIKit is still relevant enough to learn it.</p><p>I started learning iOS development back in 2011. At that time, iOS apps were still developed with Objective-C&#x200A;&#x2014;&#x200A;no automatic reference counting and no auto layout were available at that time. So a lot has changed over the years. Then came Swift and it was a big change. But now there is <a href="https://www.thomashanning.com/tag/swiftui/">SwiftUI</a> and it&#x2019;s an even bigger step. But does that mean that you shouldn&#x2019;t learn UIKit?</p><p>Let&#x2019;s start by looking at a poll I recently made on LinkedIn:</p><figure class="kg-card kg-image-card"><img src="https://www.thomashanning.com/content/images/2023/02/Screenshot-2023-01-18-at-19.51.04.png" class="kg-image" alt="Should You Still Learn UIKit?" loading="lazy" width="1050" height="460" srcset="https://www.thomashanning.com/content/images/size/w600/2023/02/Screenshot-2023-01-18-at-19.51.04.png 600w, https://www.thomashanning.com/content/images/size/w1000/2023/02/Screenshot-2023-01-18-at-19.51.04.png 1000w, https://www.thomashanning.com/content/images/2023/02/Screenshot-2023-01-18-at-19.51.04.png 1050w" sizes="(min-width: 720px) 720px"></figure><p>So more developers would use SwiftUI in a new app project. But the difference is not big&#x200A;&#x2014;&#x200A;at least 41 percent voted for UIKit. There seem to be still good reasons for using UIKit&#x200A;&#x2014;&#x200A;even in a new app project.</p><p>Of course, the topic is also a little bit subjective. Here are the reasons that I believe are the advantages of UIKit and SwiftUI respectively:</p><h4 id="uikit"><strong><strong>UIKit</strong></strong></h4><ul><li>Most existing apps use UIKit. So if you start working as an iOS developer, it&#x2019;s very likely that you will work on projects that use UIKit.</li><li>Over the years many resources like blog posts, open-source libraries, and tutorials have been created. And they use UIKit. Sure, there are more and more resources that use SwiftUI, but it will take some time until the older resources are not relevant anymore.</li><li>For complex layouts, UIKit is still the better choice. SwiftUI is much younger than UIKit and the API coverage is still better in UIKit. Especially when the UI requirements are very strict, you have more options with UIKit.</li><li>For SwiftUI you have to choose a high deployment target. The minimum is iOS 13, but higher is even better. One could argue that this is not a big deal for an iOS app because most users are on the latest iOS version. However, if you have an app that has a big audience you want to have a low deployment target.</li></ul><div class="kg-card kg-product-card"><div class="kg-product-card-container"><div class="kg-product-card-title-container"><h4 class="kg-product-card-title">Subscribe to ThomasHanning.com</h4></div><div class="kg-product-card-description"><ul><li>&quot;iOS Dev &amp; Swift Email Newsletter&quot; - The newsletter of curated iOS development and Swift resources from around the web.&#xA0;</li><li>Get the latest blog posts from ThomasHanning.com directly into your inbox</li><li>Write comments</li></ul></div><a href="https://www.thomashanning.com/#/portal/signup" class="kg-product-card-button kg-product-card-btn-accent" target="_blank" rel="noopener noreferrer"><span>Subscribe</span></a></div></div><h4 id="swiftui">SwiftUI</h4><ul><li>Development is less error-prone: SwiftUI is a declarative UI framework. That means you don&#x2019;t have to handle all possible UI states on your own. As a result, complexity decreases and you will have fewer bugs.</li><li>Development with SwiftUI is faster: Because of its declarative nature, it&#x2019;s also quicker to develop with SwiftUI. Additionally, you have the preview feature in Xcode which saves a lot of compile time.</li><li>SwiftUI is easier to learn than UIKit because you have much less boilerplate code. Just compare the implementation of an UITableView with a List in SwiftUI. It&#x2019;s a huge difference in complexity.</li></ul><h4 id="the-transition">The Transition</h4><p>We see that both frameworks have their place, but obviously, SwiftUI is the future. Therefore, we are in a transition phase. Many people compare this with the transition from <a href="https://www.thomashanning.com/should-you-use-objective-c-or-swift/">Swift to Objective-C</a> because there are a lot of similarities: Both languages can be used in the same project, one is the future and the new one has a lot of advantages. Also worth noting is the fact that Swift was at the beginning difficult to use because of the bad <a href="https://www.thomashanning.com/tag/xcode/">Xcode</a> integration. For example, code completion crashed all the time so it was quite difficult to develop with Swift at the beginning.</p><p>But in the end, the transition from Objective-C to Swift was fast. I believe that the transition from UIKit to Swift will take much more time because the transition is more complex. Probably UIKit will never become as irrelevant as Objective-C is today.</p><h4 id="the-biggest-similarity">The Biggest Similarity</h4><p>Before we conclude let us acknowledge one important fact: Both SwiftUI and UIKit are great frameworks and you can create outstanding and meaningful iOS apps with both of them. So in the end it&#x2019;s not even possible to make a completely wrong decision.</p><h4 id="conclusion">Conclusion</h4><p>SwiftUI is the future of iOS development but UIKit is still very relevant today and will be for some time. So if you want to become an iOS developer you have to learn both. On the other hand, SwiftUI and UIKit are very complex. Therefore, it&#x2019;s tricky to learn both at the same time.</p><p>My advice is to focus on SwiftUI in the beginning because it&#x2019;s easier to learn. After you&#x2019;ve learned the basics and can write simple apps, it&#x2019;s a good time to learn UIKit.</p><p></p>]]></content:encoded></item><item><title><![CDATA[SwiftUI: Alert]]></title><description><![CDATA[Alert is equivalent to UIKit’s UIAlertView in SwiftUI. This post is about creating and presenting an alert in SwiftUI.]]></description><link>https://www.thomashanning.com/swiftui-alert/</link><guid isPermaLink="false">63d38b8127e59a003deebe8a</guid><category><![CDATA[SwiftUI]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sat, 14 Jan 2023 09:37:51 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1624060798683-144bad071963?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fGFsZXJ0fGVufDB8fHx8MTY3NTY4OTA5Mg&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<h2 id="creating-an-alert-in-swiftui"><strong>Creating an alert in SwiftUI</strong></h2><img src="https://images.unsplash.com/photo-1624060798683-144bad071963?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fGFsZXJ0fGVufDB8fHx8MTY3NTY4OTA5Mg&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="SwiftUI: Alert"><p>Creating an alert in <a href="https://www.thomashanning.com/tag/swiftui/">SwiftUI</a> is very straightforward:</p><pre><code class="language-swift">Alert(title: Text(&quot;Hello World!&quot;))</code></pre><p>But how do you present it? Since SwiftUI is a declarative UI framework, you don&#x2019;t present it by reacting to a user action in a callback. Instead, you declare under which state it should be presented. Remember: A SwiftUI view is a function of its state.</p><p>You define the conditions for presenting the alert by using the <code>alert</code> function. It takes two arguments:</p><ol><li>A bool binding (the state) specifies whether the alert should be displayed.</li><li>A closure that returns the actual alert.</li></ol><p>SwiftUI refreshes the view whenever the bool value changes since it is a state. As a consequence, the alert gets displayed if it&#x2019;s set to true. After the alert gets dismissed, the bool value is set automatically to false.</p><p>Take a look at the following example:</p><pre><code class="language-swift">struct ContentView: View {
    
    @State var showAlert = false
    
    var body: some View {
        VStack {
            Button(action: {
                self.showAlert.toggle()
            }) {
                Text(&quot;Show alert!&quot;)
            }
        }.alert(isPresented: $showAlert) { () -&gt; Alert in
            Alert(title: Text(&quot;Hello World!&quot;))
        }
    }
    
}</code></pre><p>The alert has by default an &#x201C;OK&#x201D; button.</p><figure class="kg-card kg-image-card"><img src="https://www.thomashanning.com/content/images/2023/02/Screenshot-2020-08-08-at-18.30.33-1092x2048.png" class="kg-image" alt="SwiftUI: Alert" loading="lazy" width="1092" height="2048" srcset="https://www.thomashanning.com/content/images/size/w600/2023/02/Screenshot-2020-08-08-at-18.30.33-1092x2048.png 600w, https://www.thomashanning.com/content/images/size/w1000/2023/02/Screenshot-2020-08-08-at-18.30.33-1092x2048.png 1000w, https://www.thomashanning.com/content/images/2023/02/Screenshot-2020-08-08-at-18.30.33-1092x2048.png 1092w" sizes="(min-width: 720px) 720px"></figure><p>Of course, it&#x2019;s also possible to add a message by using the <code>message</code> parameter:</p><pre><code class="language-swift">Alert(title: Text(&quot;Hello World!&quot;), message: Text(&quot;An important message&quot;))</code></pre><figure class="kg-card kg-image-card"><img src="https://www.thomashanning.com/content/images/2023/02/Screenshot-2020-08-08-at-18.32.03-1092x2048.png" class="kg-image" alt="SwiftUI: Alert" loading="lazy" width="1092" height="2048" srcset="https://www.thomashanning.com/content/images/size/w600/2023/02/Screenshot-2020-08-08-at-18.32.03-1092x2048.png 600w, https://www.thomashanning.com/content/images/size/w1000/2023/02/Screenshot-2020-08-08-at-18.32.03-1092x2048.png 1000w, https://www.thomashanning.com/content/images/2023/02/Screenshot-2020-08-08-at-18.32.03-1092x2048.png 1092w" sizes="(min-width: 720px) 720px"></figure><div class="kg-card kg-product-card"><div class="kg-product-card-container"><div class="kg-product-card-title-container"><h4 class="kg-product-card-title">Subscribe to ThomasHanning.com</h4></div><div class="kg-product-card-description"><ul><li>&quot;iOS Dev &amp; Swift Email Newsletter&quot; - The newsletter of curated iOS development and Swift resources from around the web.&#xA0;</li><li>Get the latest blog posts from ThomasHanning.com directly into your inbox</li><li>Write comments</li></ul></div><a href="https://www.thomashanning.com/#/portal/signup" class="kg-product-card-button kg-product-card-btn-accent" target="_blank" rel="noopener noreferrer"><span>Subscribe</span></a></div></div><h2 id="adding-buttons-and-actions"><strong>Adding buttons and actions</strong></h2><p>So the alert from the last example is quite appropriate for displaying a message. But in many cases you also want the user to take a decision and you want to define an action. For that, you can add one or two buttons that have completion blocks. An alert with one button can be created as follows:</p><pre><code class="language-swift">.alert(isPresented: $showAlert) { () -&gt; Alert in
            let button = Alert.Button.default(Text(&quot;OK&quot;)) {
                print(&quot;OK Button Pressed&quot;)
            }
            return Alert(title: Text(&quot;Hello World!&quot;), message: Text(&quot;An important message&quot;), dismissButton: button)
 }</code></pre><p>Besides <code>default</code> there are another two button types: <code>destructive</code> and <code>cancel</code>. You should pick the one that fits best to your action.</p><p>Now let&#x2019;s add two buttons:</p><pre><code class="language-swift">.alert(isPresented: $showAlert) { () -&gt; Alert in
            let primaryButton = Alert.Button.default(Text(&quot;Primary&quot;)) {
                print(&quot;primary button pressed&quot;)
            }
            let secondaryButton = Alert.Button.cancel(Text(&quot;Secondary&quot;)) {
                print(&quot;secondary button pressed&quot;)
            }
            return Alert(title: Text(&quot;Hello World!&quot;), message: Text(&quot;An important message&quot;), primaryButton: primaryButton, secondaryButton: secondaryButton)
        }</code></pre><figure class="kg-card kg-image-card"><img src="https://www.thomashanning.com/content/images/2023/02/Screenshot-2020-08-08-at-18.34.01-1092x2048.png" class="kg-image" alt="SwiftUI: Alert" loading="lazy" width="1092" height="2048" srcset="https://www.thomashanning.com/content/images/size/w600/2023/02/Screenshot-2020-08-08-at-18.34.01-1092x2048.png 600w, https://www.thomashanning.com/content/images/size/w1000/2023/02/Screenshot-2020-08-08-at-18.34.01-1092x2048.png 1000w, https://www.thomashanning.com/content/images/2023/02/Screenshot-2020-08-08-at-18.34.01-1092x2048.png 1092w" sizes="(min-width: 720px) 720px"></figure><p>It&#x2019;s not possible to add more than two buttons though. Although that&#x2019;s possible in UIKit, that&#x2019;s not a restriction in SwiftUI: Alerts with more than two buttons could be confusing. Instead, you can use an action sheet.</p><h2 id="creating-multiple-alerts-in-swiftui"><strong>Creating multiple alerts in SwiftUI</strong></h2><p>So far so good. But for a view, it&#x2019;s not so uncommon to have more than one scenario for displaying an alert. So do you just chain the <code>.aler</code>t functions? Let&#x2019;s try it out:</p><pre><code class="language-swift">// DOESN&apos;T WORK:
struct ContentView: View {
    
    @State var showAlert1 = false
    @State var showAlert2 = false
    
    var body: some View {
        VStack {
            Button(action: {
                self.showAlert1.toggle()
            }) {
                Text(&quot;Show alert!&quot;)
            }
            Button(action: {
                self.showAlert2.toggle()
            }) {
                Text(&quot;Show alert!&quot;)
            }
        }.alert(isPresented: $showAlert1) { () -&gt; Alert in
            Alert(title: Text(&quot;Hello World!&quot;))
        }.alert(isPresented: $showAlert2) { () -&gt; Alert in
            Alert(title: Text(&quot;Hello World2!&quot;))
        }
    }
}</code></pre><p>Unfortunately, this doesn&#x2019;t work. The reason is that every view can only have one alert. So one possibility is to call the alert function on the two button views:</p><pre><code class="language-swift">struct ContentView: View {
    
    @State var showAlert1 = false
    @State var showAlert2 = false
    
    var body: some View {
        VStack {
            Button(action: {
                self.showAlert1.toggle()
            }) {
                Text(&quot;Show alert!&quot;)
            }.alert(isPresented: $showAlert1) { () -&gt; Alert in
                Alert(title: Text(&quot;Hello World!&quot;))
            }
            
            Button(action: {
                self.showAlert2.toggle()
            }) {
                Text(&quot;Show alert!&quot;)
            }.alert(isPresented: $showAlert2) { () -&gt; Alert in
                Alert(title: Text(&quot;Hello World2!&quot;))
            }
        }
    }
}</code></pre><p>This works. However, if you have several alerts, this can become quite confusing. Alternatively, you can use an overloaded method of <code>.alert</code>. Instead of a boolean, it takes a binding that confirms to the <code>Identifiable</code> protocol. A type confirms to this protocol if it implements an id so that an instance can be identified uniquely. We create a struct that confirms to this protocol. Furthermore, this struct has an enum that represents all possible alert types:</p><pre><code>struct AlertId: Identifiable {
    
    var id: AlertType
    
    enum AlertType {
        case type1
        case type2
    }
}

struct ContentView: View {

    @State var alertId: AlertId?
    
    var body: some View {
        VStack {
            Button(action: {
                self.alertId = AlertId(id: .type1)
            }) {
                Text(&quot;Show alert!&quot;)
            }
            
            Button(action: {
                self.alertId = AlertId(id: .type2)
            }) {
                Text(&quot;Show alert!&quot;)
            }
        }.alert(item: $alertId) { (alertId) -&gt; Alert in
            return createAlert(alertId: alertId)
        }
    }
    
    private func createAlert(alertId: AlertId) -&gt; Alert {
        switch alertId.id {
        case .type1:
            return Alert(title: Text(&quot;Hello World!&quot;))
        case .type2:
            return Alert(title: Text(&quot;Hello World2!&quot;))
        }
    }
}</code></pre><p>Now, whenever the value of <code>alertId</code> changes, the view gets refreshed (a SwiftUI view is a function of its state!) and displays the alert. To make the code a little bit more clear, we create the alert inside a helper function.</p><h2 id="ios-15-and-above"><strong>iOS 15 And Above</strong></h2><p>In iOS 15 and above there is a new syntax available. You can display the alert directly with the <a href="https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)-8584l?ref=thomashanning.com">alert modifier</a>:</p><pre><code>struct ContentView: View {
    
    @State var showAlert = false
    
    var body: some View {
        VStack {
            Button(action: {
                self.showAlert.toggle()
            }) {
                Text(&quot;Show alert!&quot;)
            }
        }.alert(Text(&quot;Hello World!&quot;), isPresented: $showAlert, actions: {} )
    }
    
}</code></pre><p>It&#x2019;s still possible to use the old syntax though.</p><p></p>]]></content:encoded></item><item><title><![CDATA[if let shorthand syntax in Swift]]></title><description><![CDATA[Using optional binding is very common in Swift. With the "if let" shorthand syntax it is easier to write and read. It has been introduced with Swift 5.7 and Xcode 14.]]></description><link>https://www.thomashanning.com/if-let-shorthand-syntax-in-swift/</link><guid isPermaLink="false">63d38b8127e59a003deebe89</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Mon, 09 Jan 2023 06:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1571171637578-41bc2dd41cd2?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDN8fHByb2dyYW1taW5nfGVufDB8fHx8MTY3NDkxOTk1MQ&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html--><h2>if let for optional binding</h2>



<img src="https://images.unsplash.com/photo-1571171637578-41bc2dd41cd2?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=MnwxMTc3M3wwfDF8c2VhcmNofDN8fHByb2dyYW1taW5nfGVufDB8fHx8MTY3NDkxOTk1MQ&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="if let shorthand syntax in Swift"><p>Optional binding is used to access optional in a safe way. For example, take a look at the following example: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="swift" data-enlighter-theme="dracula" data-enlighter-highlight data-enlighter-linenumbers data-enlighter-lineoffset data-enlighter-title data-enlighter-group>var a: Int? = 5

if let a = a {
    print(a)
}</pre>



<p>Here <em>a</em> is an optional and gets shadowed inside the <em>if let</em> code block. In that block, <em>a</em> is no longer an optional. If <em>a</em> is nil, the code block wouldn&#x2019;t be executed. </p>



<p>However, it is a little bit strange to write and read. </p>



<h2>if let shorthand syntax</h2>



<p>With the <em>if let</em> shorthand syntax, it becomes easier:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="swift" data-enlighter-theme data-enlighter-highlight data-enlighter-linenumbers data-enlighter-lineoffset data-enlighter-title data-enlighter-group>var a: Int? = 5

if let a {
    print(a)
}</pre>



<p>It&#x2019;s not only more clear, but it&#x2019;s also less error-prone: It&#x2019;s common practice to use the same variable for the shadowing variable. However, if the name of the variable is long and difficult, a typo can easily happen. Then, you have two similar named variables accessible inside the code block. With the <em>if let</em> shorthand syntax, this cannot happen.</p>



<h2>guard</h2>



<p>Not only <em>if let</em> is often used for handling optionals, but <em><a href="https://thomashanning.com/swift-2-guard/?ref=thomashanning.com">guard</a></em> as well. Here you have a similar shorthand syntax:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="swift" data-enlighter-theme data-enlighter-highlight data-enlighter-linenumbers data-enlighter-lineoffset data-enlighter-title data-enlighter-group>func doSomething(a:Int?) {
     guard let a else {
          return
     }

     print(a)
}</pre>



<p>If you want to learn more about optionals, take a look at my blog post about <a href="https://thomashanning.com/optionals-in-swift/?ref=thomashanning.com">optionals</a>.</p>



<h3>References</h3>



<p><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0345-if-let-shorthand.md?ref=thomashanning.com" target="_blank" rel="noreferrer noopener"><code>if let</code>&#xA0;shorthand for shadowing an existing optional variable</a></p>



<h3>Do you want to learn more about iOS development?</h3>



<p>Take a look at the following book (affiliate link):</p>



<p align="center">
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=US&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=thblog-20&amp;language=de_DE&amp;marketplace=amazon&amp;region=US&amp;placement=180323704X&amp;asins=180323704X&amp;linkId=804ee9c32e08386610a3ece97cbd2c7b&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe></p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Swift: Property wrappers]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Property wrappers enable you to reuse code that specifies the access pattern of a property.</p>



<!--more-->



<figure class="wp-block-embed-youtube aligncenter wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Swift: Property Wrappers" width="750" height="422" src="https://www.youtube.com/embed/f0loSzQ_Hi8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Often you add behaviour to a property through its observers. For example, you can use the <code>didSet</code> observer to trim a string:</p>



<pre class="wp-block-code"><code>class TestClass {

    var trimmedString: String = &quot;&quot; {
        didSet {
            trimmedString = trimmedString.trimmingCharacters(in: .whitespaces)</code></pre>]]></description><link>https://www.thomashanning.com/swift-property-wrappers/</link><guid isPermaLink="false">63d38b8127e59a003deebe84</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sun, 02 Aug 2020 08:32:33 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2020/06/shutterstock_428426212.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html-->
<img src="https://www.thomashanning.com/content/images/wordpress/2020/06/shutterstock_428426212.jpg" alt="Swift: Property wrappers"><p>Property wrappers enable you to reuse code that specifies the access pattern of a property.</p>



<!--more-->



<figure class="wp-block-embed-youtube aligncenter wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Swift: Property Wrappers" width="750" height="422" src="https://www.youtube.com/embed/f0loSzQ_Hi8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Often you add behaviour to a property through its observers. For example, you can use the <code>didSet</code> observer to trim a string:</p>



<pre class="wp-block-code"><code>class TestClass {

    var trimmedString: String = &quot;&quot; {
        didSet {
            trimmedString = trimmedString.trimmingCharacters(in: .whitespaces)
        }
    }
    
}

var test = TestClass()
test.trimmedString = &quot;    test&quot;
print(test.trimmedString) //&quot;test&quot;</code></pre>



<p>This is very useful. However, if you want to add this behaviour to several properties, you have to implement this behaviour separately for each property. Instead, you can define a so called property wrapper. </p>



<p>You create a property wrapper by creating a struct, class or enum that uses the <code>@propertyWrapper</code> annotation. Inside the property wrapper you have to implement the <code>wrappedValue</code> property. By implementing property observers of <code>wrappedValue</code> you can add custom behaviour.</p>



<p>Note that observers of stored properties (<code>didSet</code>, <code>willSet</code>) get not called at initialisation time. Hence, you also have to implement the <code>init</code> method.</p>



<p>Let&#x2019;s create a property wrapper for the use case of trimming a string:</p>



<pre class="wp-block-code"><code>@propertyWrapper struct WhiteSpacesTrimmed {
        
    var wrappedValue: String {
        didSet {
            print(&quot;propertyWrapper didSet&quot;)
            wrappedValue = wrappedValue.trimmingCharacters(in: .whitespaces)
        }
    }
    
    init(wrappedValue:String) {
        self.wrappedValue = wrappedValue.trimmingCharacters(in: .whitespaces)
    }
    
}</code></pre>



<p>A property wrapper can then be applied to every property that has the corresponding type:</p>



<pre class="wp-block-code"><code>class TestClass {
    @WhiteSpacesTrimmed var test = &quot;&quot;
    @WhiteSpacesTrimmed var test2 = &quot;&quot;
}

let testClass = TestClass()
testClass.test = &quot;    test&quot;
print(testClass.test) //&quot;test&quot;</code></pre>



<p>As you can see, you just have to add the annotation <code>@WhiteSpacesTrimmed. </code></p>



<h3>wrappedValue as a computed property</h3>



<p>In the last example, the wrapped value was a stored property. It&#x2019;s also possible to use a computed value:</p>



<pre class="wp-block-code"><code>@propertyWrapper struct Max100 {
    
    private var value: Int = 0
    
    var wrappedValue: Int {
        get {
            return value
        }
        set {
            value = min(100, newValue)
        }
    }
    
    init(wrappedValue: Int) {
        self.wrappedValue = wrappedValue
    }
    
}

class TestClass2 {
    @Max100 var test = 0 
}

let testClass2 = TestClass2()
testClass2.test = 300
print(testClass2.test)</code></pre>



<p>In this example we created a property wrapper that limits an integer property to the maximum value of 100. </p>



<h3>Customizing a property wrapper</h3>



<p>As you have seen in the last example, a property wrapper can have properties of its own. But it&#x2019;s also possible to initialise these properties with custom values every time you use the property wrapper. </p>



<p>In the following example we create a property wrapper that writes and saves a string value to the user defaults. The name of the user defaults key is customizable:</p>



<pre class="wp-block-code"><code>@propertyWrapper
struct UserDefaultsWrapper {
    
    var key: String
    
    var wrappedValue: String? {
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
        get {
            UserDefaults.standard.string(forKey: key)
        }
    }
    
}

class TestClass3 {
    @UserDefaultsWrapper(key: &quot;testKey&quot;) var test: String?
}</code></pre>



<p>If your property wrapper has properties, they can be initialised. If they have an initial value, they&#x2019;re are optional. If they lack an initial value, they are mandatory.</p>



<h3>Projected values</h3>



<p>Besides <code>wrappedValue</code> there is another special property inside a property wrapper: <code>projectedValue</code>. This value is accessible from the outside by using the symbol <code>$</code>. Hence, you can use it to provide additional functionality.</p>



<p>In the following example we again create a property wrapper that trims a string. But in this case we save the initial value inside the <code>projectedValue</code> property:</p>



<pre class="wp-block-code"><code>@propertyWrapper struct WhiteSpacesTrimmed {
        
    var projectedValue: String
    
    var wrappedValue: String {
        didSet {
            self.projectedValue = wrappedValue
            wrappedValue = wrappedValue.trimmingCharacters(in: .whitespaces)
        }
    }
    
    init(wrappedValue:String) {
        self.projectedValue = wrappedValue
        self.wrappedValue = wrappedValue.trimmingCharacters(in: .whitespaces)
    }
    
}

class TestClass5 {
    @WhiteSpacesTrimmed var test = &quot;       test&quot;
}

print(&quot;projected Values&quot;)
var testClass5 = TestClass5()
print(testClass5.test) //&quot;test&quot;
print(testClass5.$test) //&quot;       test&quot;</code></pre>



<h4>References</h4>



<p>Title image: @ Foxys Forest Manufacture / shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[The Advantages of SwiftUI]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Almost a year ago Apple introduced SwiftUI at WWDC 2019. It&#x2019;s still a very young technology but it&#x2019;s quite clear that it&#x2019;s the future not only of iOS development, but of macOS, watchOS, and tvOS development as well. What are the advantages of using</p>]]></description><link>https://www.thomashanning.com/the-advantages-of-swiftui/</link><guid isPermaLink="false">63d38b8127e59a003deebe83</guid><category><![CDATA[SwiftUI]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sun, 24 May 2020 11:19:50 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2020/05/shutterstock_616650677.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html-->
<img src="https://www.thomashanning.com/content/images/wordpress/2020/05/shutterstock_616650677.jpg" alt="The Advantages of SwiftUI"><p>Almost a year ago Apple introduced SwiftUI at WWDC 2019. It&#x2019;s still a very young technology but it&#x2019;s quite clear that it&#x2019;s the future not only of iOS development, but of macOS, watchOS, and tvOS development as well. What are the advantages of using SwiftUI?</p>



<h3>Development is faster</h3>



<p>Let&#x2019;s face it: time matters. We love our craft but we also want to be fast in order to satisfy customer demands and to be more productive. One essential part of SwiftUI is preview. It enables you to see the graphical result of your UI code at development time.</p>



<p>To a certain degree that holds true for developing with UIKit by using the interface builder as well. However, with SwiftUI you can define test data for preview. Consider a tableview: you don&#x2019;t see just a single prototype cell, but the whole table view with realistic data. Additionally, you can see different screen sizes at the same time. Also other states as localisation and dark mode can be observed.</p>



<p>You can also use live preview. After starting it, you can interact with your UI. It&#x2019;s like using the simulator with the big difference that you don&#x2019;t have to recompile after applying changes.</p>



<p>This safes a lot of build time. When projects becomes huge, long build times can decrease productivity massively.</p>



<h3>Development is less error prone</h3>



<p>There is one thing though, that&#x2019;s even more important than time: quality. The complexity of building an UI with a lot of interaction possibilities is huge. Handling all these different states (i.e. logged in / not logged in) is very difficult and can be compared to handling multithreading code. </p>



<p>With SwiftUI, this complexity decreases dramatically. UIKit is imperative programming, whereas SwiftUI is declarative programming. So what&#x2019;s the difference? As the names imply, by using an imperative approach, you tell the framework what should happen and also how. On the other hand, by using a declarative approach, you just describe the desired result.</p>



<p>An example: Imagine a screen with a login form. When the users has successfully logged in, you update the UI in the network callback according to the &#x2018;logged in&#x2019;&#xA0; state. For example, you change the text of the button (&#x2018;log in&#x2019; -&gt; &#x2018;log out&#x2019;), display the user&#x2019;s name and show other menu options. When the user ever gets logged out, it&#x2019;s your responsibility to react and change the UI state. On the other hand, if you are using a declarative approach, you just describe the whole UI dependent on the login state. If the variable with the login state ever changes, the UI will be updated automatically without any manual action. </p>



<p>And that&#x2019;s just one state. The screen can have many others states and depending on the order of the user actions there can be unpredictable outcomes. Of course there are also good practices to handle this with an imperative approach. However, SwiftUI makes it automatically and easy.</p>



<h3>Swift UI is exciting</h3>



<p>For me as a long term iOS developer, it&#x2019;s very exciting to use a completely new technolgy for developing apps. And it&#x2019;s not like using a different framework. It&#x2019;s a different approach of programming. As explained in the last paragraph, switching from imperative to declarative programming is a huge deal.&#xA0;</p>



<p>For us developers technology is not just a tool for creating an app. Instead, the technology as such matters. And learning a new technology is like unboxing the shiny new iPhone.&#xA0;</p>



<h3>SwiftUI is the future anyway</h3>



<p>In my opinion, the previous reasons are sufficient to justify the switch to SwiftUI. But even if you are not convinced yet that developing with SwiftUI is faster and less error prone, it&#x2019;s still necessary for every iOS developer to learn SwiftUI. </p>



<p>Apple is pushing SwiftUI heavily and the developer community is also impressed by SwiftUI. So SwiftUI will go the same way as Swift did: Yes, Objective-C is still a great programming language and alive, but Swift is THE language for iOS development. And the same will happen to SwiftUI as well.&#xA0;</p>



<p>The doesn&#x2019;t mean that you don&#x2019;t need UIKit anymore! There are millions of apps in the App Store using UIKit and it doesn&#x2019;t make sense to migrate existing code to SwiftUI. And sometimes it&#x2019;s not even possible because the deployment target is lower than iOS 13.</p>



<p>Also, there are UIKit features, that are not yet available for SwiftUI, like collection views. </p>



<p>So if you wanna be a serious iOS developer, you have to be both an UIKit and SwiftUI expert.</p>



<h4><strong>References&#xA0;</strong></h4>



<p>Title image: @ &#xA0;Vadym Sh / Shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Swift: The differences between structs and classes]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Compared to many other programming languages, structs are very powerful in Swift. Hence, they should be used more often.</p>



<!--more-->



<p><em>Hint: This post is using Swift 5</em></p>



<h3><strong>Similarities</strong></h3>



<p>First, let&#x2019;s start by talking about the similarities between structs and classes. They actually have a lot in common:</p>



<ul><li>they have</li></ul>]]></description><link>https://www.thomashanning.com/swift-differences-between-structs-and-classes/</link><guid isPermaLink="false">63d38b8127e59a003deebe81</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Mon, 10 Jun 2019 15:01:37 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2019/05/differences-structs-classes.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html-->
<img src="https://www.thomashanning.com/content/images/wordpress/2019/05/differences-structs-classes.jpg" alt="Swift: The differences between structs and classes"><p>Compared to many other programming languages, structs are very powerful in Swift. Hence, they should be used more often.</p>



<!--more-->



<p><em>Hint: This post is using Swift 5</em></p>



<h3><strong>Similarities</strong></h3>



<p>First, let&#x2019;s start by talking about the similarities between structs and classes. They actually have a lot in common:</p>



<ul><li>they have methods and initializers</li><li>they have stored and computed properties</li><li>they can be extended&#xA0;</li><li>they can implement protocols&#xA0;</li></ul>



<p>There are some differences how you use these features, but those are minor and are not the main part of this post. For example, initializers for structs are created automatically, whereas for classes you have to do that manually.</p>



<h3><strong>Differences</strong></h3>



<p>There are three main differences between structs and classes:</p>



<ul><li>Structs are value types, whereas classes are reference types.&#xA0;</li><li>Classes can be inherited. This is not possible for structs.&#xA0;</li><li>Objective-C interoperability for structs is very bad, whereas it&#x2019;s very good for classes.</li></ul>



<p>Let&#x2019;s look at these differences in detail.</p>



<h3><strong>Value types vs reference types</strong></h3>



<p>So what is the difference between a value type and a reference type? An instance of a reference type cannot be accessed directly, but only by using a so-called reference. Therefore, multiply references can point to the same instance. Take a look at the following example:</p>



<pre class="wp-block-code"><code>class TestClassA {
    
    var a: Int
    
    init(a: Int) {
        self.a = a
    }
    
}

let testA = TestClassA(a: 5)
let testB = testA

print(testA.a) //5
print(testB.a) //5

testA.a = 10

print(testA.a) //10
print(testB.a) //10</code></pre>



<p>As you can see, just one instance of <em>TestClassA</em> has been created, but two references are pointing to it. If you change the property <em>a</em> of <em>testA</em>, the same happens for <em>testB</em> because it&#x2019;s the same instance.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" loading="lazy" width="245" height="300" src="http://3.124.110.105/wp-content/uploads/2019/04/differences-between-structs-classes-1-245x300.png" alt="Swift: The differences between structs and classes" class="wp-image-1530" srcset="https://www.thomashanning.com/content/images/wordpress/2019/04/differences-between-structs-classes-1-245x300.png 245w, https://www.thomashanning.com/content/images/wordpress/2019/04/differences-between-structs-classes-1.png 646w" sizes="(max-width: 245px) 100vw, 245px"></figure></div>



<p>Now let us look at a struct:</p>



<pre class="wp-block-code"><code>struct TestStruct {
    var a: Int
}

var testC = TestStruct(a: 5)
var testD = testC

print(testC.a) //5
print(testD.a) //5

testC.a = 10

print(testC.a) //10
print(testD.a) //5
</code></pre>



<p>Again, we have two values (<em>testC</em> and <em>testD</em>). If a property of one value gets changed, this doesn&#x2019;t happen for the other one because it&#x2019;s not the same instance.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" loading="lazy" width="300" height="124" src="http://3.124.110.105/wp-content/uploads/2019/04/differences-between-structs-classes-2-300x124.png" alt="Swift: The differences between structs and classes" class="wp-image-1531" srcset="https://www.thomashanning.com/content/images/wordpress/2019/04/differences-between-structs-classes-2-300x124.png 300w, https://www.thomashanning.com/content/images/wordpress/2019/04/differences-between-structs-classes-2-768x318.png 768w, https://www.thomashanning.com/content/images/wordpress/2019/04/differences-between-structs-classes-2.png 846w" sizes="(max-width: 300px) 100vw, 300px"></figure></div>



<p>Note also that <em>testC</em> and <em>testD</em> has to be declared as variable by using the keyword <em>var</em>. It is not possible to change a property of a struct, if the struct itself is a constant.</p>



<p>It&#x2019;s exactly the same as with some Swift types, like <em>Int</em>, <em>String</em> and <em>Array</em> &#x2013; they are also value types. But not only that, they are also structs!</p>



<p>The corresponding example to the one above with <em>Int</em> values:</p>



<pre class="wp-block-code"><code>var testE = 5
var testF = testE

print(testE) //5
print(testF) //5

testE = 10

print(testE) //10
print(testF) //5</code></pre>



<p>If you haven&#x2019;t worked with structs yet, the last example is probably much more natural for you. Just remind yourself that a struct works just as an <em>Int</em> value because an <em>Int</em> <strong>is</strong> a struct.</p>



<p>Reference types and value types behave quite differently. Imagine you have an instance of a reference type and you have multiple references pointing to it within your app. If you change the value by using one of these references, all of these references point to the same new value. This can be a wanted behavior. But if that&#x2019;s not the case, this can be the source of major bugs.&#xA0;</p>



<p>Because of the differences between value and reference types, memory management is quite different as well. The most important point is that so-called retain cycles can occur for reference types. That is not possible for value types. Take a look <a href="https://www.thomashanning.com/retain-cycles-weak-unowned-swift/">at this post</a> for more details about this topic.</p>



<h3><strong>Objective-C interoperability&#xA0;</strong></h3>



<p>Structs in Swift don&#x2019;t have a good Objective-C interoperability. If you define a struct in Swift, you can&#x2019;t expose it to Objective-C source code. That means for example that a delegate or datasource of UITableView must not be a struct but a class because UIKit is still written in Objective-C. This sounds like a major obstacle, but in reality these cases are rarer than you might think.&#xA0;</p>



<h3><strong>Inheritance&#xA0;</strong></h3>



<p>To make it short: There is no inheritance for structs. However, there are other ways to implement similar behaviour for structs. The most common way is using protocols.&#xA0;</p>



<h3><strong>Use structs by default&#xA0;</strong></h3>



<p>So the general guideline is that you should structs by default. The reason is that they are easier and safer to use: Retain cycles cannot occur and you cannot change the value for another part of the app by accident.&#xA0;</p>



<p>Only if you need class specific features like inheritance, Objective-C interoperability, or you want the specific behaviour of a reference type, you should use classes.&#xA0;</p>



<h4><strong>References&#xA0;</strong></h4>



<p>Title image: @ &#xA0;Stepan Kapl / Shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Swift: Reference Equality and Value Equality For Classes ​]]></title><description><![CDATA[<!--kg-card-begin: html--><p>There are two ways for testing the equality of class instances: reference equality and value equality. In this post we will discuss both of them.</p>
<p><!--more--></p>
<p><em>Hint: This post is using Swift 4</em></p>
<h3>The Identity Operator ===</h3>
<p>By using the identity operator <span class="lang:swift decode:true crayon-inline ">===</span>&#xA0; you can compare the references pointing to the instances</p>]]></description><link>https://www.thomashanning.com/swift-reference-equality-value-equality-for-classes/</link><guid isPermaLink="false">63d38b8127e59a003deebe7f</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Sun, 03 Feb 2019 00:00:52 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2019/02/apple_orange.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html--><img src="https://www.thomashanning.com/content/images/wordpress/2019/02/apple_orange.jpg" alt="Swift: Reference Equality and Value Equality For Classes &#x200B;"><p>There are two ways for testing the equality of class instances: reference equality and value equality. In this post we will discuss both of them.</p>
<p><!--more--></p>
<p><em>Hint: This post is using Swift 4</em></p>
<h3>The Identity Operator ===</h3>
<p>By using the identity operator <span class="lang:swift decode:true crayon-inline ">===</span>&#xA0; you can compare the references pointing to the instances of a class. If these references are pointing to the same instance, the operator returns true. Take a look at the following example:</p>
<pre class="striped:false lang:swift decode:true">Class TestClassA { }

let test1 = TestClassA()
let test2 = TestClassA()
let test3 = test1

print(&quot;test1 and test2 pointing to the same instance: \(test1===test2)&quot;) //false
print(&quot;test1 and test3 pointing to the same instance: \(test1===test3)&quot;) //true</pre>
<p>As you can see, <span class="lang:swift decode:true crayon-inline ">test1</span>&#xA0;and <span class="lang:swift decode:true crayon-inline">test3</span>&#xA0;are pointing to the same instance, whereas <span class="lang:swift decode:true crayon-inline ">test1</span>&#xA0;and <span class="lang:swift decode:true crayon-inline ">test2</span>&#xA0;are not pointing to the same instance.</p>
<p><a href="http://3.124.110.105/wp-content/uploads/2019/02/equality-references.jpg?ref=thomashanning.com"><img decoding="async" loading="lazy" class="aligncenter size-full wp-image-1522" src="http://3.124.110.105/wp-content/uploads/2019/02/equality-references.jpg" alt="Swift: Reference Equality and Value Equality For Classes &#x200B;" width="1564" height="830" srcset="https://www.thomashanning.com/content/images/wordpress/2019/02/equality-references.jpg 1564w, https://www.thomashanning.com/content/images/wordpress/2019/02/equality-references-300x159.jpg 300w, https://www.thomashanning.com/content/images/wordpress/2019/02/equality-references-1024x543.jpg 1024w, https://www.thomashanning.com/content/images/wordpress/2019/02/equality-references-768x408.jpg 768w, https://www.thomashanning.com/content/images/wordpress/2019/02/equality-references-1536x815.jpg 1536w" sizes="(max-width: 1564px) 100vw, 1564px"></a></p>
<p>You can also check for inequality by using the <span class="lang:swift decode:true crayon-inline ">!==</span>&#xA0;operator:</p>
<pre class="striped:false lang:swift decode:true">print(&quot;test1 and test3 are not pointing to the same instances: \(test1!==test3)&quot; //true</pre>
<p>Note that the identity operator is not available for enums, structs and primitive data types. This makes sense because in these cases it&#x2019;s not possible that two values are pointing to the same instance.</p>
<h3>The equality operator ==</h3>
<p>The equality operator on the other hand works differently. It compares whether two instances are equal. This doesn&#x2019;t sound very concrete and in fact it&#x2019;s not defined what that means. Instead, each class has to define what equality means for it. If the class doesn&#x2019;t do this, it&#x2019;s not possible to use the equality operator:</p>
<pre class="striped:false lang:swift decode:true">Class TestClassA { }

let test1 = TestClassA()
let test2 = TestClassA()

print(&quot;test1 is equal to test2 \(test1==test2)&quot;) //Compiler error</pre>
<p>The last line produces a compiler error. Instead, you have to implement the Equatable protocol:</p>
<pre class="lang:swift decode:true">class TestClassA: Equatable {

     let a: Int

     init(a:Int) {
          self.a = a
     }

     public static func == (lhs: TestClassA, rhs: TestClassA) -&gt; Bool {
          return lhs.a == rhs.a
     }

}

let test1 = TestClassA(a:5)
let test2 = TestClassA(a:6)
let test3 = TestClassA(a:5)

print(&quot;test1 is equal to test2 \(test1==test2)&quot;) //false
print(&quot;test1 is equal to test3 \(test1==test3)&quot;) //true</pre>
<p>As you can see, in this example two instances of <span class="lang:swift decode:true crayon-inline ">TestClass</span>&#xA0;are equal if the properties <span class="lang:swift decode:true crayon-inline ">a</span>&#xA0; are equal.</p>
<h3>The comparable protocol</h3>
<p>It&#x2019;s not only possible to define the value equality for two instances of a class but an order as well. For that, you have to implement the Comparable protocol. It extends the Equatable protocol, so that the <span class="lang:swift decode:true crayon-inline ">==</span>&#xA0;function has to be implemented as explained in the last section. In addition, the <span class="lang:swift decode:true crayon-inline ">&lt;</span>&#xA0;function also has to be implemented:</p>
<pre class="striped:false lang:swift decode:true">class TestClassA: Equatable, Comparable {

     let a: Int

     init(a:Int) {
          self.a = a
     }

     public static func &lt; (lhs: TestClassA, rhs: TestClassA) -&gt; Bool {
          return lhs.a &lt; rhs.a
     }

     public static func == (lhs: TestClassA, rhs: TestClassA) -&gt; Bool {
          return lhs.a == rhs.a
     }

}

let test1 = TestClassA(a:5)
let test2 = TestClassA(a:6)
let test3 = TestClassA(a:5)

print(&quot;test1 &lt; test2 \(test1&lt;test2)&quot;) //true
print(&quot;test1 &lt; test3 \(test1&lt;test3)&quot;) //false
print(&quot;test1 &lt;= test3 \(test1&lt;=test3)&quot;) //true
print(&quot;test1 &gt; test3 \(test1&gt;test2)&quot;) //false</pre>
<p>As you can see, it&#x2019;s very straight forward.</p>
<p>Title image: @ MShipphoto / shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[How iOS Development Has Evolved Over The Past 8 Years]]></title><description><![CDATA[<!--kg-card-begin: html--><p class="p1">I&#x2019;ve been a full-time iOS developer for over 6 years now and I started learning iOS development 8 years ago. A lot has changed over the years. In this post I want to talk about the biggest changes I&#x2019;ve experienced.</p>
<p><!--more--></p>
<h3 class="p3"><b>Swift</b></h3>
<p class="p1">Obviously one of the biggest</p>]]></description><link>https://www.thomashanning.com/how-ios-development-has-evolved-over-the-past-8-years/</link><guid isPermaLink="false">63d38b8127e59a003deebe7e</guid><category><![CDATA[iOS development]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Fri, 04 Jan 2019 10:15:52 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2019/01/progress-1-1.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html--><img src="https://www.thomashanning.com/content/images/wordpress/2019/01/progress-1-1.jpg" alt="How iOS Development Has Evolved Over The Past 8 Years"><p class="p1">I&#x2019;ve been a full-time iOS developer for over 6 years now and I started learning iOS development 8 years ago. A lot has changed over the years. In this post I want to talk about the biggest changes I&#x2019;ve experienced.</p>
<p><!--more--></p>
<h3 class="p3"><b>Swift</b></h3>
<p class="p1">Obviously one of the biggest changes in iOS development over the last 8 years is the introduction of Swift at WWDC 2014. And for me it was the biggest surprises I&#x2019;ve ever experienced watching an Apple event because there are was absolutely no leak beforehand. So Swift was a real surprise and for a developer it was just huge. Don&#x2019;t get me wrong: Objective-C is a great language and there is still a lot of value in learning Objective-C, but in my opinion Swift is just better and now it&#x2019;s the primary programming language for developing iOS apps.</p>
<p>Wherever there is light, there is shadow. So at the beginning there was also a lot of criticism about Swift. Compile times were very slow, the Xcode integration was not very good and there were a lot of code breaking changes with every new Swift version. And not all of these problems are solved yet. For example, there&#x2019;s still no ABI stability (but it will come with Swift 5 hopefully) and I still have the impression that compile times are far away from being optimal.</p>
<p>But let&#x2019;s face it: All the obstacles are worth it. Compared to the Objective-C times, iOS development has been become both easier and more powerful. And the most important part: It has become more fun.</p>
<h3 class="p3"><b>Memory Management</b></h3>
<p class="p1">When I began developing iOS apps, you still had to count references manually. If you haven&#x2019;t witnessed that time, here&#x2019;s a small overview:</p>
<p>By default, each reference, that points to an instance of a class, is a so-called strong reference. As long as there is at least one strong reference pointing to an instance, this instance will not be deallocated. When&#xA0;there&#x2019;s no strong reference pointing to that instance left, the instance will be deallocated. These references have to be counted.</p>
<p>So far so easy. But before the introduction of ARC (Automatic Reference Counting), you had to do the counting manually by using code. Although it sounds simple, it was the root cause of many bugs. And debugging these bugs was even more difficult. But then ARC&#xA0; has been introduced with Xcode 4.2 in October 2011. ARC is a compile time feature: It inserts the reference counting code automatically, so that you don&#x2019;t have to deal with it anymore in most cases.</p>
<p>However, there are still situations, that ARC cannot handle correctly. In these situations a so-called retain cycles can occur. And here it&#x2019;s an advantage if you have witnessed the manual reference counting time.<span class="Apple-converted-space">&#xA0; This is a very important topic and i</span>f you want to learn more about it, take a look <a href="https://www.thomashanning.com/retain-cycles-weak-unowned-swift/">at this blog post</a>&#xA0;about retain cycles.</p>
<h3 class="p3"><b>Auto Layout</b></h3>
<p class="p1">Implementing a layout used to be very easy in the early days of iOS development because there was just one screen size (the iPhone). So you could just work pixel perfect. Over time though, there were more and more screen sizes like the iPhone 5, 6 and 6 plus and even different iPad sizes.<span class="Apple-converted-space">&#xA0;&#xA0;</span>It was very clear that it was not possible to handle this with the with the original layout system.</p>
<p class="p1">So Apple introduced Auto Layout, which was already in use for Mac OS development. It&#x2019;s very powerful but also a little bit complicated. With the introduction of the StackView and the possibility to <a href="https://www.thomashanning.com/xcode-8-mixing-auto-autoresizing-masks/">mix Auto Layout and Autoresizing Masks</a>, Apple took account of this. I used to assume that there will be another new layout system at some point, but meanwhile I do believe that Auto Layout is the best solution, especially if there are classes like StackView, that makes life much easier. By the way: In Android development there has been a constraint layout introduced as well.</p>
<h3 class="p3"><b>Community </b></h3>
<p class="p1">At the time of writing, there are 586,576 questions tagged with &#x2018;iOS&#x2019; on <a href="https://stackoverflow.com/questions/tagged/ios?ref=thomashanning.com" target="_blank" rel="noopener">Stack Overflow</a>. In the list of the most used tags, this is place ten. There are also a lot of blogs, YouTube channels and Twitter accounts, that focus on iOS development. Also on GitHub there a lot of repositories concerning iOS development. So if you have a question or a problem, it&#x2019;s very likely that you will find the answer very quickly. And even if that is not the case, you will probably find someone, who can help you. That is a very important aspect for choosing a platform you want to develop for because it makes your life much easier and you become much more productive as well.</p>
<p>When I started iOS development, there was of course already a community. However, it has grown massively since then, which makes a big difference.</p>
<h3 class="p3"><b>Ecosystem </b></h3>
<p class="p1">The iOS ecosystem has grown massively as well over the years: There are more than 1.3 billion active iOS devices out there, so that you as an iOS developer have access to one of the biggest and most important software markets in the world. iOS development used to be called a gimmick, but now it&#x2019;s a serious business. And that holds not only true for the consumer market, but for the business market as well. Many companies have their own In-House iOS apps to support their business processes. 8 years ago the story was completely different. Sure, the iPhone was already a big success, but how big the ecosystem eventually would become was not predictable.</p>
<p>And now there is not only the iPhone, but the iPad and the Apple Watch as well. It&#x2019;s quite interesting that the Apple Watch is not viewed as such a big success, but in fact it really is. And it&#x2019;s still growing. Although the iPhone sales are stagnant at the moment, Apple&#x2019;s service area (which includes for example the App Store, iTunes and iCloud) has been growing massively over the last years. This shows that the platform is very vibrant.&#xA0;And in my opinion this trend will not stop in the next years. iOS has come to stay.</p>
<h4>Resources</h4>
<p>Title Image: @ Sergey Tinjakov / shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Sets in Swift]]></title><description><![CDATA[<!--kg-card-begin: html--><p>Sets are one of Swift&#x2019;s collection types. A set stores an amount of unique values, that have no particular order. You can imagine a set to be like a box of billiard balls: They are all unique in terms of color and number, but they don&#x2019;t</p>]]></description><link>https://www.thomashanning.com/sets-in-swift/</link><guid isPermaLink="false">63d38b8127e59a003deebe7d</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Tue, 06 Nov 2018 17:27:22 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2018/11/billiard-1.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html--><img src="https://www.thomashanning.com/content/images/wordpress/2018/11/billiard-1.jpg" alt="Sets in Swift"><p>Sets are one of Swift&#x2019;s collection types. A set stores an amount of unique values, that have no particular order. You can imagine a set to be like a box of billiard balls: They are all unique in terms of color and number, but they don&#x2019;t have a certain order inside the box.</p>
<p><!--more--></p>
<p><em>Hint: This post is using Swift 4 and Xcode 10</em></p>
<p>[toc]</p>
<h3>Creating sets</h3>
<p>Creating a set is very straightforward:</p>
<pre class="lang:swift decode:true">let setA: Set&lt;String&gt; = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</pre>
<p>In this example, a set called <span class="lang:swift decode:true crayon-inline ">setA</span>&#xA0; of strings has been created. It stores the values <span class="lang:swift decode:true crayon-inline">a</span>, <span class="lang:swift decode:true crayon-inline ">b</span>&#xA0; and <span class="lang:swift decode:true crayon-inline">c</span>. In contrast to an array, the elements are not ordered. By using type interference, the set can also be created like this:</p>
<pre class="lang:swift decode:true">let setB: Set = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]</pre>
<p>It&#x2019;s also possible to use the initialiser of the set type:</p>
<pre class="lang:swift decode:true">let setC = Set([&quot;a&quot;,&quot;b&quot;,&quot;c&quot;])</pre>
<p>Like an array, a set is not mutable, if it&#x2019;s declared as a constant by using <span class="lang:swift decode:true crayon-inline">let</span>. For mutable sets, you can use the keyword <span class="lang:swift decode:true crayon-inline">var</span>:</p>
<pre class="lang:swift decode:true">var setD = Set([&quot;a&quot;,&quot;b&quot;])</pre>
<p>We will learn more about mutable sets later on.</p>
<h3>Accessing the values of a set</h3>
<p>You can access the values of a set by using a loop:</p>
<pre class="lang:swift decode:true">for value in setA {
     print(value)
}</pre>
<p>Note that the order of the values in the loop can be different every time you run the code. From the outside it looks like they the values are picked randomly.</p>
<h3>Analysing sets</h3>
<p>First of all, you can check whether a set is empty:</p>
<pre class="lang:swift decode:true">print(setA.isEmpty)</pre>
<p>Also the number of elements of a set can be checked:</p>
<pre class="lang:swift decode:true">print(setA.count)</pre>
<p>Both of these operations are also available for arrays. More typical for a set is the question, whether a certain element is a member of a set. For that, you can use the method contains:</p>
<pre class="lang:swift decode:true">print(setA.contains(&quot;a&quot;))</pre>
<h3>Adding and removing values from a set</h3>
<p>Mutable sets can be changed. You can add and remove values:</p>
<pre class="lang:swift decode:true">setD.insert(&quot;c&quot;)
setD.remove(&quot;a&quot;)</pre>
<p>Since the values of a set are unique, a value can only be added once to the same set. The insert method can be called with the same values multiple times, but the set won&#x2019;t change:</p>
<pre class="lang:swift decode:true">var setE: Set = [1,2,3,4]

setE.insert(5)
setE.insert(5)
setE.insert(5)

print(setE) //[4,5,1,2,3]</pre>
<p>As before, the order of the output can be different every time you run the code since sets are not ordered.</p>
<h3>Comparing sets</h3>
<p>Sets can be compared. Obviously, comparing the equality of two sets is possible:</p>
<pre class="lang:swift decode:true">let setA: = [&#x201C;a&#x201D;, &#x201C;b&#x201D;, &#x201C;c&#x201D;]
let setB: = [&#x201C;a&#x201D;, &#x201C;b&#x201D;, &#x201C;c&#x201D;]

if setA == setB {
     print(&#x201C;the sets are equal&#x201D;)
}</pre>
<p>In this case, the sets are equal.</p>
<p>There is no useful definition for a smaller and bigger comparison of two sets, but you can check whether a set is a subset of another set:</p>
<pre class="lang:swift decode:true">let intSetA: Set = [1,2,3,4,5,6,7,8,9,0]
let intSetB: Set = [1,2,3]
intSetB.isSubset(of: intSetA) //true</pre>
<p>It&#x2019;s also possible to check whether it&#x2019;s a strict subset. In that case, it has to be a subset but must not be equal:</p>
<pre class="lang:swift decode:true">let intSetA: Set = [1,2,3,4,5,6,7,8,9,0]
let intSetB: Set = [1,2,3,4,5,6,7,8,9,0]
let intSetC: Set = [3,4,5]

intSetB.isSubset(of: intSetA) //true
intSetB.isStrictSubset(of: intSetA) //false
intSetC.isSubset(of: intSetA) // true
intSetC.isStrictSubset(of: intSetA) //true</pre>
<p>The opposite principle is a superset:</p>
<pre class="lang:swift decode:true">let intSetA: Set = [1,2,3,4,5,6,7,8,9,0]
let intSetC: Set = [3,4,5]
intSetA.isSuperset(of: intSetC) //true
intSetA.isStrictSuperset(of: intSetC) //true</pre>
<p>Two sets are disjoint, if they don&#x2019;t have any element in common:</p>
<pre class="lang:swift decode:true">let intSetA: Set = [1,2,3,4,5,6,7,8,9,0]
let intSetC: Set = [3,4,5]
let intSetD: Set = [13,14,15]

intSetA.isDisjoint(with: intSetC) //false
intSetA.isDisjoint(with: intSetD) //true</pre>
<h3>Combining sets</h3>
<p>You can combine two sets to create a new one. A union of two sets contains all elements from both sets:</p>
<pre class="lang:swift decode:true">let stringSetA: Set = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]
let stringSetB: Set = [&quot;c&quot;,&quot;d&quot;,&quot;e&quot;]

let unionSetAB = stringSetA.union(stringSetB)
print(unionSetAB) //[&quot;d&quot;, &quot;b&quot;, &quot;c&quot;, &quot;a&quot;, &quot;e&quot;]</pre>
<p>An intersection on the other hand contains only the elements, that are in both sets:</p>
<pre class="lang:swift decode:true">let stringSetA: Set = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]
let stringSetB: Set = [&quot;c&quot;,&quot;d&quot;,&quot;e&quot;]

let intersectionAB = stringSetA.intersection(stringSetB)
print(intersectionAB) //[&#x201C;c&#x201D;]</pre>
<h3>Using sets with custom types</h3>
<p>Of course you can also store values of your own type in a set. This type could be for example a struct or a class. However, in order for the set to work properly, this type has to conform to the hashable protocol.</p>
<pre class="lang:swift decode:true">class Movie: Hashable {

     var title: String
     var year: Int

     init(title: String, year: Int) {
          self.title = title
          self.year = year
     }

     static func == (lhs: Movie, rhs: Movie) -&gt; Bool {
          return lhs.title == rhs.title &amp;&amp;
          lhs.year == rhs.year
     }

     var hashValue: Int {
          return title.hashValue ^ year.hashValue
     }

}

let terminator = Movie(title: &quot;Terminator&quot;, year: 1980)
let backToTheFuture = Movie(title: &quot;Back to the Future&quot;, year: 1985)

let movieSetA: Set = [terminator,backToTheFuture]</pre>
<h3>References:</h3>
<p>Title image: @ LaineN / shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[MFMailComposeViewController - sending emails from an iOS app]]></title><description><![CDATA[<!--kg-card-begin: html--><p class="p3">MFMailComposeViewController provides an easy way to present a view controller, that allows to write, edit and send an email. It&#x2019;s presented modally, so the context of the app won&#x2019;t be left.</p>
<p><!--more--></p>
<p><em>Hint: This post is using Swift 4 and iOS 9</em></p>
<p><iframe loading="lazy" title="MFMailComposeViewController (Xcode 9, iOS 11, Swift 4)" width="750" height="422" src="https://www.youtube.com/embed/Q50dxDzAekc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br>
<script src="https://apis.google.com/js/platform.js"></script></p>
<div class="g-ytsubscribe" data-channelid="UCrVQS7c6AkTke-EjWxx0gjw" data-layout="full" data-count="default"></div>
<h3 class="p4">Creating and presenting MFMailComposeViewController</h3>
<p class="p3">It&</p>]]></description><link>https://www.thomashanning.com/mfmailcomposeviewcontroller/</link><guid isPermaLink="false">63d38b8127e59a003deebe7c</guid><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Wed, 15 Aug 2018 20:56:17 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2018/08/mails-1.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html--><img src="https://www.thomashanning.com/content/images/wordpress/2018/08/mails-1.jpg" alt="MFMailComposeViewController - sending emails from an iOS app"><p class="p3">MFMailComposeViewController provides an easy way to present a view controller, that allows to write, edit and send an email. It&#x2019;s presented modally, so the context of the app won&#x2019;t be left.</p>
<p><!--more--></p>
<p><em>Hint: This post is using Swift 4 and iOS 9</em></p>
<p><iframe loading="lazy" title="MFMailComposeViewController (Xcode 9, iOS 11, Swift 4)" width="750" height="422" src="https://www.youtube.com/embed/Q50dxDzAekc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br>
<script src="https://apis.google.com/js/platform.js"></script></p>
<div class="g-ytsubscribe" data-channelid="UCrVQS7c6AkTke-EjWxx0gjw" data-layout="full" data-count="default"></div>
<h3 class="p4">Creating and presenting MFMailComposeViewController</h3>
<p class="p3">It&#x2019;s very easy. First, you have to import the <span class="lang:swift decode:true crayon-inline ">MessageUI</span>&#xA0;framework:</p>
<pre class="lang:swift decode:true">import MessageUI</pre>
<p class="p3">Then, you just have to create an instance of <span class="lang:swift decode:true crayon-inline">MFMailComposeViewController</span>, set some parameters and present it. The rest is taken care of by that controller.</p>
<pre class="lang:swift decode:true">if MFMailComposeViewController.canSendMail() {

     let mailComposeViewController = MFMailComposeViewController()
     mailComposeViewController.mailComposeDelegate = self
     mailComposeViewController.setToRecipients([&quot;abc@abc.abc&quot;])
     mailComposeViewController.setSubject(&quot;Subject&quot;)
     mailComposeViewController.setMessageBody(&quot;Hello!!!&quot;, isHTML: false)

     present(mailComposeViewController, animated: true, completion: nil)

}</pre>
<p class="p3">The static&#xA0;<span class="lang:swift decode:true crayon-inline ">canSendMail()</span>&#xA0;method of <span class="lang:swift decode:true crayon-inline ">MFMailComposeViewController</span>&#xA0;is called to check if an email account is set up on the device. Note that this doesn&#x2019;t include email accounts of third party apps like Gmail or Outlook.</p>
<p class="p3">It&#x2019;s important to set the <span class="lang:swift decode:true crayon-inline">MFMailComposeViewControllerDelegate</span>&#xA0;as well to handle the dismissal of the controller. There&#x2019;s just one method to implement:</p>
<pre class="lang:swift decode:true">func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {

     controller.dismiss(animated: true, completion: nil)

}</pre>
<p class="p3">It&#x2019;s called when the user dismisses the controller, either by sending the email or canceling the action. Either way, you have to dismiss the controller manually.</p>
<p class="p3">Setting the recipients, subject and message body are the most obvious parameters you can set. However, it&#x2019;s also possible to set CC and BCC recipients:</p>
<pre class="lang:swift decode:true">mailComposeViewController.setCcRecipients([&quot;cc@cc.cc&quot;])
mailComposeViewController.setBccRecipients([&quot;bcc@bcc.bcc&quot;])</pre>
<p class="p3">It&#x2019;s also possible to set an attachment:</p>
<pre class="lang:swift decode:true">if let image = UIImage(named: &quot;Test&quot;), let imageData = UIImageJPEGRepresentation(image, 1.0) {

     mailComposeViewController.addAttachmentData(imageData, mimeType: &quot;image/jpeg&quot;, fileName: &quot;Image.jpeg&quot;)

}</pre>
<p class="p3">In this example, an image called Test.jpeg from the asset bundle gets attached to the email.</p>
<h3 class="p4">Open Mail app</h3>
<p class="p3">There&#x2019;s also another way to sent emails from an iOS app. Instead of presenting the <span class="lang:swift decode:true crayon-inline ">MFMailComposeViewController</span>, you can open the mail app:</p>
<pre class="lang:swift decode:true">if let url = URL(string: &quot;mailto:abc@abc.abc&quot;) {

&#xA0; &#xA0; &#xA0;UIApplication.shared.open(url, options: [:], completionHandler: nil)

}</pre>
<p>There is also the possibility to use the <a href="https://developer.apple.com/documentation/uikit/uiactivityviewcontroller?ref=thomashanning.com" target="_blank" rel="noopener">UIActivityViewController</a>. However, then the user can choose from different types of channels, not only email.</p>
<h3>References</h3>
<p>Title image: @ Andrey Bayda / shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Properties in Swift]]></title><description><![CDATA[<!--kg-card-begin: html--><p><strong>There are two types of properties in Swift: stored properties and computed properties. Stored properties store values (constant or variable) as part of an instance or type, whereas computed properties don&#x2019;t have a stored value.</strong></p>
<p><!--more--></p>
<p><em>Hint: This post has been updated to Swift 4&#xA0;</em></p>
<p>[toc]</p>
<h3>Video</h3>
<p><iframe loading="lazy" title="Properties in Swift" width="750" height="563" src="https://www.youtube.com/embed/-3N_B-v0NQA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br>
<script src="https://apis.google.com/js/platform.js"></script></p>
<div class="g-ytsubscribe" data-channelid="UCrVQS7c6AkTke-EjWxx0gjw" data-layout="full" data-count="default"></div>
<h3>Stored</h3>]]></description><link>https://www.thomashanning.com/properties-in-swift/</link><guid isPermaLink="false">63d38b8127e59a003deebe79</guid><category><![CDATA[Swift]]></category><dc:creator><![CDATA[Thomas Hanning]]></dc:creator><pubDate>Thu, 15 Mar 2018 17:49:14 GMT</pubDate><media:content url="https://www.thomashanning.com/content/images/wordpress/2015/06/properties-1.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html--><img src="https://www.thomashanning.com/content/images/wordpress/2015/06/properties-1.jpg" alt="Properties in Swift"><p><strong>There are two types of properties in Swift: stored properties and computed properties. Stored properties store values (constant or variable) as part of an instance or type, whereas computed properties don&#x2019;t have a stored value.</strong></p>
<p><!--more--></p>
<p><em>Hint: This post has been updated to Swift 4&#xA0;</em></p>
<p>[toc]</p>
<h3>Video</h3>
<p><iframe loading="lazy" title="Properties in Swift" width="750" height="563" src="https://www.youtube.com/embed/-3N_B-v0NQA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br>
<script src="https://apis.google.com/js/platform.js"></script></p>
<div class="g-ytsubscribe" data-channelid="UCrVQS7c6AkTke-EjWxx0gjw" data-layout="full" data-count="default"></div>
<h3>Stored properties</h3>
<p>Let&#x2019;s start by looking at stored properties. Imagine you have a class named circle:</p>
<pre class="lang:swift decode:true">class Circle {
    
    var radius: Double = 0
    
}

let circle = Circle()
circle.radius = 10

print(&quot;radius: \(circle.radius)&quot;) //radius: 10.0</pre>
<p>Circle has an instance variable called&#xA0;<span class="lang:swift decode:true crayon-inline ">radius</span>&#xA0; with a default value of 0. In Swift, every instance variable is automatically a property. So now you have the possibility to add so called property observers. In Swift there a two types of property observers: One is called before the new value is assigned and the other one afterwards.</p>
<p>The property observer, which is called after the assignment, is marked with the keyword&#xA0;<span class="lang:swift decode:true crayon-inline">didSet</span>. In our example, you can use it for example to check the new assigned value:</p>
<pre class="lang:swift decode:true">class Circle {
    
    var radius: Double = 0 {
        didSet {
            if radius &lt; 0 {
                radius = oldValue
            }
        }
    }
    
}

let circle = Circle()

circle.radius = -10
print(&quot;radius: \(circle.radius)&quot;) //radius: 0.0

circle.radius = 10
print(&quot;radius: \(circle.radius)&quot;) //radius: 10.0</pre>
<p>In the property observer you can access the old value of the property through the variable&#xA0;<span class="lang:swift decode:true crayon-inline">oldValue</span>.</p>
<p>You can also use the property observer&#xA0;<span class="lang:swift decode:true crayon-inline">willSet</span>, which is called before the new value is assigned:</p>
<pre class="lang:swift decode:true">class Circle {
    
    var radius: Double = 0 {
        willSet {
            print(&quot;About to assign the new value \(newValue)&quot;)
        }
        didSet {
            if radius &lt; 0 {
                radius = oldValue
            }
        }
    }
    
}

let circle = Circle()

circle.radius = 10 //About to assign the new value 10.0</pre>
<p>In&#xA0;<span class="lang:swift decode:true crayon-inline ">willSet</span>&#xA0; you have access to the new value of the property through the variable&#xA0;<span class="lang:swift decode:true crayon-inline">newValue</span>.</p>
<h3>Computed Properties</h3>
<p>Contrary to stored properties, computed properties don&#x2019;t&#xA0;have a stored value. So each time you call a computed property, the value needs to be calculated. In the class&#xA0;<span class="lang:swift decode:true crayon-inline ">Circle</span>&#xA0; you can define the property&#xA0;<span class="lang:swift decode:true crayon-inline">area</span>&#xA0;as a computed property:</p>
<pre class="lang:swift decode:true">class Circle {
    
    var radius: Double = 0 {
        didSet {
            if radius &lt; 0 {
                radius = oldValue
            }
        }
    }
    
    var area: Double {
        get {
            return radius * radius * Double.pi
        }
    }

}

let circle = Circle()
circle.radius = 5

print(&quot;area: \(circle.area)&quot;) //area: 78.5398163397448</pre>
<p>A computed property always needs a getter. If it lacks a setter, the property is called a read-only property. In our example, there is a good application for a setter though:</p>
<pre class="lang:swift decode:true">import Foundation

class Circle {
    
    var radius: Double = 0 {
        didSet {
            if radius &lt; 0 {
                radius = oldValue
            }
        }
    }
    
    var area: Double {
        get {
            return radius * radius * Double.pi
        }
        set(newArea) {
            radius = sqrt(newArea / Double.pi)
        }
    }
    
}

let circle = Circle()

circle.area = 25

print(&quot;radius: \(circle.radius)&quot;) //radius: 2.82094791773878</pre>
<p>Now, after assigning a new value to <span class="lang:swift decode:true crayon-inline ">area</span>&#xA0;,&#xA0;<span class="lang:swift decode:true crayon-inline ">radius</span>&#xA0; will be&#xA0;calculated.</p>
<h3>Initilization of stored properties</h3>
<p>Every stored property has to have a value after its instance has been created. There are two ways:</p>
<ul>
<li>initialize the value inside the <span class="lang:swift decode:true crayon-inline ">init</span>&#xA0;method</li>
<li>set a default value for the property</li>
</ul>
<p>The following example covers both cases:</p>
<pre class="lang:swift decode:true ">class Circle {
    
    var radius: Double
    var identifier: Int = 0
    
    init(radius: Double) {
        self.radius = radius
    }
    
}

var circle = Circle(radius: 5)</pre>
<p>If a stored property doesn&#x2019;t have a value after its instance has been created, the code will not compile.</p>
<h3>Lazy Properties</h3>
<p>If a stored property with a default value is marked with the keyword&#xA0;<span class="lang:swift decode:true crayon-inline">lazy</span>, its default value will not be&#xA0;initialized immediately, but when the property is called for the very first time.</p>
<p>So if the property gets never called, it will never be initialized. You could use this feature for example, if the initialization is expensive in terms of memory or CPU usage.</p>
<p>Let&#x2019;s take a look at the following (very simple) example:</p>
<pre class="lang:swift decode:true ">class TestClass {
    
    lazy var testString: String = &quot;TestString&quot;
    
}

let testClass = TestClass()
print(testClass.testString) //TestString</pre>
<p>The property will not initalized until it gets accessed. In this example this is not very obivious though. But since the initialization can also happen inside a block, we can make it a little bit more obvious:</p>
<pre class="lang:swift decode:true">class TestClass {
    
    lazy var testString: String = {
        print(&quot;about to initialize the property&quot;)
        return &quot;TestString&quot;
    }()
    
}

let testClass = TestClass()
print(&quot;before first call&quot;)
print(testClass.testString)
print(testClass.testString)</pre>
<p>The output of this example is:</p>
<pre class="lang:swift decode:true">before first call
about to initialize the property
TestString
TestString</pre>
<p>So that means that the block is only called once &#x2013; when the property is accessed for the very first time. Since this is stored property is variable, the initial value can be changed afterwards.</p>
<h3>Type Properties</h3>
<p>Type properties are part of an type but not of an instance &#x2013; also know as static properties. Both stored and computed properties can be type properties. For that, you use the keyword&#xA0;<span class="lang:swift decode:true crayon-inline">static</span>:</p>
<pre class="lang:swift decode:true">class TestClass {
    
    static var testString: String = &quot;TestString&quot;
    
}

print(&quot;\(TestClass.testString)&quot;) //TestString</pre>
<p>As you can see, they are accessed by using the type name but not an instance. Furthermore, type properties always need a default value because there is not initialization.</p>
<h3>Public Properties With Private Setters</h3>
<p>As I&#x2019;ve pointed out in more details <a href="https://www.thomashanning.com/public-properties-with-private-setters/">in this post</a>, it&#x2019;s a common scenario that you don&#x2019;t want to provide a public getter, but a private setter. This is a basic principle of encapsulation. By doing this, only the class itself can manipulate that property, but can still be accessed and read from outside of the class.</p>
<p>Take a look at the following example:</p>
<pre class="lang:swift decode:true">public class Circle {
    
    public private(set) var area: Double = 0
    public private(set) var diameter: Double = 0
    
    public var radius: Double {
        didSet {
            calculateFigures()
        }
    }
    
    public init(radius:Double) {
        self.radius = radius
        calculateFigures()
    }
    
    private func calculateFigures() {
        area = Double.pi * radius * radius
        diameter = 2 * Double.pi * radius
    }
}

let circle = Circle(radius: 5)

print(&quot;area: \(circle.area)&quot;) //area: 78.5398163397448
print(&quot;diameter: \(circle.diameter)&quot;) //diameter: 31.4159265358979

circle.area = 10 //Compiler Error: cannot assign to property: &apos;area&apos; setter is inaccessible</pre>
<p>Here the properties area and diameter can be read from outside of the class, but only be set inside the class. For that you have to use the combination&#xA0;<span class="lang:swift decode:true crayon-inline">public private(set)</span>. In my experience this feature is very rarely used in iOS development, but it&#x2019;s very useful to create code, that has fewer bugs.</p>
<h3>References</h3>
<p>Title Image: @&#xA0;Fabrik Bilder / shutterstock.com</p>
<!--kg-card-end: html-->]]></content:encoded></item></channel></rss>