<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by SHAD MZUMDER on Medium]]></title>
        <description><![CDATA[Stories by SHAD MZUMDER on Medium]]></description>
        <link>https://medium.com/@shadmazumder?source=rss-9437ba03af17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AGKSexOEBiJHp7-9xf7yUg.jpeg</url>
            <title>Stories by SHAD MZUMDER on Medium</title>
            <link>https://medium.com/@shadmazumder?source=rss-9437ba03af17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:19:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shadmazumder/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[mobidevtalk]]></title>
            <link>https://medium.com/mobidevtalk/deep-dive-22c6f8ebe0a1?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/22c6f8ebe0a1</guid>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Wed, 06 Mar 2019 05:12:17 GMT</pubDate>
            <atom:updated>2019-03-06T05:15:04.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning through case study</h3><h4>DEEP DIVE</h4><p>The tagline <strong>deep dive</strong> has a symbolic representation here on mobidevtalk.</p><p>There is no shortcut of learning, none something like quick and dirty way.</p><p>There is one and only one way, learn each nodes of a topic unless all the decomposed part of that topic is crystal clear.</p><p>Learning is a divide and conquer process, divide a larger topic into decomposed part and then conquer each of them by learning.</p><h4>GOAL</h4><p>The goal is simple. Dig as deep as needed, to make a topic such familiar as the back of own hand is.</p><h4>SECRET MASSAGE:</h4><p>Becoming better developer when you leave this blog. One step closer to be a pro.</p><h4>SCOPE</h4><p>Sorry, but have to limit the scope. It is only iOS development. We will set a more concrete scope once we pass some more month.</p><h4>WHY Q/A</h4><p>On the learning process there will be questions, do not shy to ask. Because asking question will ease the learning. That’s where we have some Q/A sections.</p><h4>PUTTING A LIMIT FOR DIGGING</h4><p>A boundary should be set to stop the digging. On mobidevtalk it is always application layer related talk and dive. We can have talk on memory footprint but not on memory layout.</p><h4>WHY WE</h4><p>Throughout mobidevtalk there is abundant use of we, rather than you or I. Because <strong>we </strong>represents a team. And it is always a team to achieve a great goal. Because of single individual goal fade out in-front of a team, I was intentionally dropped except inevitable situation.</p><h4>DIFFERENCE</h4><p>What is the difference between the other site/blog with this one. Well the very first thing is, case study. We put our topic on a problem and fit our topic on the solution of that problem. Secondly, we ask question to get the answer. We move to deepest cave for finding the holy water.</p><h4>FINALLY THE HOST</h4><p>So at the end, I am Shad Rayhan Mazumder, iOS apps developer, having some 6 years of expertise on this field.</p><p>I do not get comfortable on a topic read, unless I start to visualise it. And to get that visualisation I have to deep dive. Finally it is a great joy, once I am able to put my learning on some practical case study. That is how and why mobidevtalk is initiated.</p><p>It took me 6 years to start a blog, because of the feelings that I am not good enough, and probably may not be. Once I pushed myself to the break the initial barrier it start to make sense, I also have a lot to share. Even my failure so others can evade.</p><p>By the way, I am good listener, not a very good talker, though trying to be here</p><p>. Drop me a mail on <a href="/service/mailto:talk@mobidevtalk.com">talk@mobidevtalk.com</a> for further talk.</p><p>You can find me on your network. I am available at <a href="https://stackoverflow.com/users/680757/shad?tab=profile">StackOverflow</a>, <a href="https://github.com/shadmazumder">GitHub</a>, <a href="https://www.linkedin.com/in/shad-mazumder-27653aa">linkedIn</a>, <a href="https://twitter.com/shadmazumder?source=user_profile---------------------------">twitter</a> or even on <a href="https://www.facebook.com/shad.mazumder">facebook</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22c6f8ebe0a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/deep-dive-22c6f8ebe0a1">mobidevtalk</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift closure, Starting of being creative | mobidevtalk]]></title>
            <link>https://medium.com/mobidevtalk/swift-closure-starting-of-being-creative-mobidevtalk-38252b2d01db?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/38252b2d01db</guid>
            <category><![CDATA[closure-shorthand-syntax]]></category>
            <category><![CDATA[closures-functions]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Sun, 27 Jan 2019 16:34:28 GMT</pubDate>
            <atom:updated>2019-11-09T04:22:55.002Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Originally published at </em><a href="https://mobidevtalk.com/closure-starting-of-being-creative/"><em>https://mobidevtalk.com</em></a><em> on January 27, 2019.</em></p><p><strong>Coding is an art</strong> irrespective of this mindset, we all will agree that structural code is a pleasure to eye and joyful to work with. But why Swift yet not been so fluent to us? Why are we yet not been so impressed with Swift as others say so? Why we can’t see the beautification of Swift code? Actually we need not to have any special eye or any extraordinary viewing angle for enjoying the beauty of Swift code. Rather we need to extend our knowledge to have a good grab on Swift closure so that we can start understanding the code flow and the concise construction of that flow.</p><h3>Why closure is essential</h3><p>No doubt, closure is one of the fundamental component of Swift code. One who understands the closure, understands the whole code flow. The understanding of closure does not come up by chance. We have to have some study, have to spend some time on this topic. But it is certain that, <strong>the spent time on closure is a career booster</strong>. How?</p><ul><li>Code written by professional suddenly becomes easier to digest.</li><li>One will start writing professional clear concise code, which co-worker will love.</li><li>Time is saved, tends to more productive hour for the employer.</li></ul><p>Improved knowledge only on closure will move us far more further than that of which we think of, on the initial state of closure knowledge gaining. We have to travel a lot, have to listen a lot of talking. So let us not delaying any more. Les us dive deep.</p><h3>Background</h3><ul><li><a href="https://mobidevtalk.com/closure-starting-of-being-creative/#Introduction-of-closure">closure, intro part</a></li><li><a href="https://mobidevtalk.com/closure-starting-of-being-creative/#First-class-citizen-support">First class citizen support for closure</a></li><li><a href="https://mobidevtalk.com/closure-starting-of-being-creative/#Different-variants-of-closure-expression">Different variants of closure expression</a></li></ul><p>On <strong>Different variants of closure expression</strong> we will talk about:</p><ul><li><a href="https://mobidevtalk.com/closure-starting-of-being-creative/#Elaborated-expression">Elaborated expression</a></li><li><a href="https://mobidevtalk.com/closure-starting-of-being-creative/#Inferring-type-from-context">Inferring type from context</a></li><li><a href="https://mobidevtalk.com/closure-starting-of-being-creative/#Implicit-return">Implicit return</a></li><li><a href="https://mobidevtalk.com/closure-starting-of-being-creative/#Shorthand-Argument-Names">Shorthand Argument Names</a></li></ul><h3>Introduction of closure</h3><p>closure is simply a chunk of code, start with a { and ends with a }. Yes that much simpler concept.</p><p>Only a code block within a pair of curly brackets! Then why it seem so difficult to understand? Well the reason is, the variances of closure. closure on Swift comes up in different forms and shapes which make the reader of the code, at least on the initial state, confused and even sometimes fearful for closure. But fear not. We gonna get ourself out from the unknown part of the closure. Once we know the variances of closure, life will become far more smoother 🍹.</p><p>So do we want an example? Sure why not.</p><pre>let sum = { (first: Int, second: Int) -&gt; Int in return first + second } sum(10, 20) //30</pre><p>Above is a very simple example of closure, this closure will just return the sum of two Int. Ya ya we have a lot of questions. Those answers will come one after another. For the time being let us have some basic understanding of closure.</p><h3>Explanation</h3><p>As we said closure is contained with a pair of curly brackets, { }. So both the lines (first: Int, second: Int) -&gt; Int in and return first + second makes the closure.</p><p>The very first line just after the first curly bracket or the opening curly bracket, {, is the closure declaration.</p><p>Ahhh one question, <strong>closure declaration</strong> sounds like a function declaration, is there any similarities? Well of-course there is. We will talk about this on the Function vs closure, the true face.</p><p>Back to our closure declaration talk, so ya we have the params and the return declaration just as the same way we used to have for function. Now the interesting part is the in. Seems like a very tiny word, but it has its value in closure. The in acts like a barrier among the closure body and the closure declaration. In other words, in makes the separation of closure declaration from its body. Now there will be closure where in will not be used. We will talk about those on the upcoming section.</p><p>Now the second line is very easy to understand. returning the sum of two Int. Wait wait return? Can closure returns just like function? Yes they can. Just like function, the return for a closure is not a certain occurrence. Some closure will return some will not.</p><p>This was the generic format of closure.</p><p>On Swift the power of closure comes from its flexible. The flexibility becomes a blessing for those who understand the ins and outs of closure. But for those a nightmare whom have knowledge gap on closure. So let us have some knowledge gaining on closure.</p><h3>First class citizen support</h3><p>So closure is a first class citizen on Swift realm. How? Because we can use closure as</p><ul><li>params of function</li><li>returned value of function</li><li>stored property</li></ul><h3>Different variants of closure expression</h3><p>As we said earlier, closure comes in on different forms and shapes. So we will have multiple expression of a closure. We will start from the very basic expression of a closure and then we will move forward gradually to a more advance expression. In other words we will start from the very elaborated expression of a closure and then we will make that closure more concise.</p><p><strong>Question</strong>: Why we need to make the closure more concise?<br><strong>Answer</strong>: Because concise is <strong>exact to the point in few words</strong>. Concise code saves a lot of time and energy of the developer. Plus it also beautify the code. Profession guys love the concise code as it contains no unnecessary junk.</p><p>We already have a prep talk on our <a href="https://mobidevtalk.com/drilling-hof-higher-order-function/#Things-need-to-be-known-before-using-HOF">Drilling HOF, Higher order Function</a> blog post. Here we will have a more detail talk on closure expression.</p><h3>Closure explanation through HOF</h3><p>Here we will use one of the easily digestible HOF, Higher Order Function, to build up the case study of closure expression. We will use the forEach(_:).</p><p>Why easily digestible? So that we can concentrate only on closure.</p><p>Why HOF? Because HOF will take a closure to process the requirement, so it is ready-made. Moreover HOF like forEach(_:) takes a simple closure, makes it easy for us to grab the concept easily.</p><p>Now the declaration of forEach(_:) is as following:</p><pre>func forEach(_ body: (Base.Element.Element) throws -&gt; Void) rethrows</pre><p>Ok not so simple one for a starter, but it will be. If there is any confusion on throw and/or rethrow we can always visit the <a href="https://mobidevtalk.com/error-handling-through-try-variance/">Error Handling blog post</a> for a clear concept on those two.</p><p>Let us remove the throw and rethrow from the expression, as this two are not our concern here on this blog post.</p><pre>func forEach(_ body: (Base.Element.Element) -&gt; Void)</pre><p>Far more simpler now. As we can see forEach(_:) is a function which takes a closure as the param.Wait!</p><p><strong>Question</strong>: what is the Base.Element.Element?<br><strong>Answer</strong>: Base.Element.Element is actually a generic type element of the corresponding collection. We will have some future post on generic. As later down the road we will replace this generic type element with a more concrete type element.</p><p><strong>Question</strong>: Is (Base.Element.Element) -&gt; Void means a closure? Seems like a function definition.<br><strong>Answer</strong>: Theoretically yes. Yes means, yes it is a closure. And also yes, this is like a function definition. Actually function is a special type of closure. We will have that talk very soon.</p><p>Now what is the plan with the closure in forEach(_:)? The plan is simple. We will feed the closure of the forEach(_:) with different closure-expression and will explain <strong>why and how</strong> of those closure expression.</p><p>We will use the prime array for our case study. And total is used to hold the sum of the prime.</p><pre>let prime = [ 2, 3, 5, 7, 11, 13, 17, 19] <br>var total = 0</pre><h3>Elaborated expression</h3><p>The elaborated expression or the most basic expression of closure for forEach(_:) is as following:</p><pre>prime.forEach { (element: Int) in <br>    total += element <br>}</pre><p>Let us break it down. As we said in breaks the body from the params, so here element is the param and total += element is the body. Moreover element represents the elements of prime, so element is Int as prime is Int. We are replacing the generic type with a more concrete type, Int.</p><p>Now can we make it more concise? Yes we can, continue…</p><h3>Inferring type from context</h3><p>We can drop the type Int from the closure param like following:</p><pre>prime.forEach { (element) in <br>    total += element <br>}</pre><p>Same as the previous section but this time no Int is present on the param. How this was possible? Because Swift can infer the type from the context. As prime is a type of Int so the element, elements of prime, will also be type of Int.</p><h3>Implicit return</h3><p>Let us consider another HOF, filter(_:), which has a return part with it.</p><pre>func filter(_ isIncluded: (Base.Element.Element) throws -&gt; Bool) rethrows -&gt; [Base.Element.Element]</pre><p>After removing throw and rethrow:</p><pre>func filter(_ isIncluded: (Base.Element.Element) -&gt; Bool) -&gt; [Base.Element.Element]</pre><p>So the isIncluded, (Base.Element.Element) -&gt; Bool), is the closure part. And the [Base.Element.Element] is the return part of the filter(_:).</p><p>Now if we want to filter out the prime, greater than 7 then we will code as following:</p><pre>prime.filter { (element) -&gt; Bool in <br>    return element &gt; 7 <br>}</pre><p>Have a look at the return statement. We already know the return will be a Bool from the closure declaration, (element) -&gt; Bool. So can we omit the return from the closure body? Yes we can. So after omitting the return keyword from the closure body:</p><pre>prime.filter { (element) -&gt; Bool in <br>    element &gt; 7 <br>}</pre><p>no return keyword 😃.</p><h3>Shorthand Argument Names</h3><p>What does Shorthand Argument Names means? Well shorthand means short and simple way of presenting. Argument is the synonym of parameter. And the Names is the title. So Shorthand Argument Names is a pre-formatter short way of expressing the closure params. If a closure has a single param then it can be represented as $0, for two param it will be first and second as $0 and $1 respectively and so on.</p><p>So our forEach(_:) and filter(_:) will be as following:</p><pre>prime.forEach( { total += $0 } ) <br>prime.filter( { $0 &gt; 7 } )</pre><p>Wow!!! tough to believe, right? so simple so concise. But those are the most simplest form of closure. Should we have something more challenging? Wait wait, we still have some others parts to cover to have a good understand on closure.</p><h3>End Talk</h3><p>Swift closure plays a very important role in Swift learning. This initial talk will start to synch us on that path.</p><p>All the source code used on this blog post are available of <a href="https://github.com/mobidevtalk/closure/blob/master/Closure.playground/Pages/closureStarting.xcplaygroundpage/Contents.swift">GitHub</a>.</p><p>Stay tunes, we will have two more blog post on closure. The <a href="https://mobidevtalk.com/gaining-last-minute-knowledge-on-closure/">second blog post</a> is a continue version of this one plus answering the relationship between closure and/or function. We will talk some more on that. Till then Happy talking.</p><p><em>Originally published at </em><a href="https://mobidevtalk.com/closure-starting-of-being-creative/"><em>https://mobidevtalk.com</em></a><em> on January 27, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38252b2d01db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/swift-closure-starting-of-being-creative-mobidevtalk-38252b2d01db">Swift closure, Starting of being creative | mobidevtalk</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drilling HOF, Higher order Function]]></title>
            <link>https://medium.com/mobidevtalk/drilling-hof-higher-order-function-da9adafbe3bf?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9adafbe3bf</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[case-study]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Thu, 10 Jan 2019 18:02:30 GMT</pubDate>
            <atom:updated>2019-01-10T18:02:30.939Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://mobidevtalk.com/drilling-hof-higher-order-function/">Drilling HOF, Higher order Function</a></p><p>Oh ya!!! you saw it exactly. <strong>Drilling:</strong> not the “making a hole” thingy, but the military version of training. Here on this two blog-post series, we gonna drill on Higher order Function aka HOF. So tighten the boots, it will be muddy.</p><p>If you are the guy or gal who can use the HOF; ahhh pretty much I guess 😉.<br>But you are interested on what happens behind the scene, then you are on the proper pool.</p><p>We will break down the HOF drill into two parts.</p><h3>Content:</h3><ul><li><a href="#">The first part, means this blog-post, will have the detail talk on HOF.</a></li><li><a href="https://mobidevtalk.com/case-studies-of-hof/">On the second part, we will generate a complex case study which we will solve by using HOF. So that at the end we will have some good grab on HOF.</a></li></ul><h3>Background:</h3><ul><li><a href="#Hello-I-am-HOF">What is really HOF !!!</a></li><li><a href="#Why-do-we-Care-for-HOF">Why to use</a></li><li><a href="#Things-need-to-be-known-before-using-HOF">Pre knowledge</a></li><li><a href="#So-Swift-what-HOF-do-you-have">Some HOF on Swift</a></li></ul><h3>Hello I am HOF</h3><p>Though the name HOF seems to be a tough bite to digest, actually on reality it is not. The only tough thing on HOF is the understanding of when to use which HOF.<br>HOF is a very simple concept. HOF, Higher Order Function, basically is a function having the following two property:</p><ul><li>Takes a closure with/without other param as argument</li><li>Returns a function or some Cumulative value</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*fMXusYvUhs8uVgFf.png" /></figure><p>In a nutshell, HOF will facilitate a <em>repetitive</em> <em>operation</em>. Now what does this two keywords repetitive and operation means?<br>The keyword repetitive; you already have guessed it, right? Yes it will only be functional on collection types, like Array Dictionary Set. Each of the element of a collection will be included.<br>And the second thing, operation which is basically a mathematical operation. We can define the operation as f(x). So a simple example of HOF comes down to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*WJWvXaUUqM05jUxq.png" /></figure><p>Yeah thats it. Simple isn’t it? <br>I am sure this simple concept break down, now makes you think that HOF is not a UFO after-all. 😏</p><h3>Why do we Care for HOF</h3><ul><li>Not being an Alien among, some <strong>smart Software Engineer</strong>. Because those guys already using the HOF and expect others to be knowledgeable or at least has the will to know.</li><li>Producing good precise clean code.</li><li>Functional programming.</li></ul><h3>Things need to be known before using HOF</h3><ul><li>HOF will only operate on Collection-type ie Array, Dictionary and Set.</li><li>The most important thing we have to know before using HOF, is the closure. <br>A side note: Function are special type of closure.</li></ul><p>We will drive to some properties and formats of closure to facilitate HOF study.</p><h4>Closure Properties needed for HOF:</h4><ol><li><a href="#Inferring-param-and-return-type">Can infer the type of param &amp; return from surround context</a></li><li><a href="#Removing-return">return keyword is unnecessary for a single-expression closure</a></li><li><a href="#Shorthand-argument-name">Shorthand argument name</a></li></ol><p><strong>Closure expression</strong></p><pre>{ (params) -&gt; return-type in<br>    //Code<br>}</pre><p>For this section on closure we will use the following array of Jedi.</p><pre>let jedi = [&quot;Yoda&quot;, &quot;Obi-Wan Kenobi&quot;, &quot;Anakin Skywalker&quot;, &quot;Luke Skywalker&quot;]</pre><p><strong>Regular Closure</strong>, having both param type as String and return as Bool</p><pre>jedi.sorted { (firstJedi: String, secondJedi: String) -&gt; Bool in<br>    return firstJedi &lt; secondJedi<br>}</pre><h4>Inferring param and return type:</h4><pre>jedi.sorted { (firstJedi, secondJedi) in<br>    return firstJedi &lt; secondJedi<br>}</pre><h4>Removing return</h4><pre>jedi.sorted { (firstJedi, secondJedi) in<br>    firstJedi &lt; secondJedi<br>}</pre><h4>Shorthand argument name</h4><p><strong>Shorthand argument name</strong> is provided by Swift for inline closure. The values of closure’s argument/param can be referred as $0 $1 $2and so on.</p><pre>jedi.sorted(by: { $0 &lt; $1 })</pre><p>Form now on we will use the shorthand way when ever possible. We can come back to the above discussion always when we are having some confusion about closure on HOF.</p><h3>So Swift what HOF do you have?</h3><p>On this section we will talk about some of the popular HOF on Swift.</p><ul><li><a href="#map">map</a></li><li><a href="#compactMap">compactMap</a></li><li><a href="#filter">filter</a></li><li><a href="#reduce">reduce</a></li></ul><h3>map:</h3><p>map are used to perform a common operation to all the element of a collection.</p><pre>[1, 2, 3].map({ $0 + 5 })<br>//[6, 7, 8]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*XZgws_PP2nCDGxNe.png" /></figure><p>We can always revisit the <a href="#Closure-Properties-needed-for-HOF">closure properties needed for HOF</a> if we are having any confusion for closure.</p><p><strong>When to use</strong> <strong>map</strong>:<br>A common operation need to perform on a collection.</p><h3>compactMap:</h3><p>Lets consider the following example and state the use of compactMap from there:</p><pre>let jedi = [nil, &quot;Obi-Wan Kenobi&quot;, &quot;Anakin Skywalker&quot;, &quot;Luke Skywalker&quot;]<br>print( jedi.map({ &quot;Name: \($0)&quot; }) )<br>//[nil, Optional(&quot;Obi-Wan Kenobi&quot;), Optional(&quot;Anakin Skywalker&quot;), Optional(&quot;Luke Skywalker&quot;)]</pre><pre>print( jedi.compactMap({ $0 }))<br>//[&quot;Obi-Wan Kenobi&quot;, &quot;Anakin Skywalker&quot;, &quot;Luke Skywalker&quot;]</pre><p>So as you can see, its simple compactMap will return an array of non-nil instance, typed instance, in this case [String]. Whereas map will return non-nil and nil instance, optional type, in this case [String?].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*d6N6c9N5dZdEHWot.png" /></figure><p>So we can consider compactMap as a map function which has a builtin nil filter.</p><p><strong>When to use compactMap</strong> :<br>When a common operation need to perform on a collection, optionally-typed or not, and the final result need to be typed collection.</p><p>compactMap is extremely useful on the case of failable initializer, where the init can fail and return a nil instance. On some future post we will cover the failable initializer.</p><pre>[&quot;40&quot;, &quot;unknown&quot;, &quot;28&quot;].compactMap({ Int($0) })<br>//[40, 28]</pre><p>You can always refer to <a href="#Closure-Properties-needed-for-HOF">closure details</a> for clarification.</p><p>We can find the Int&#39;s failable initializer from the Documentation. The declaration is convenience init?(_ description: String). Again we will talk about the convenience init? on some future post.</p><p>So by using the compactMap we can eliminate the nil ones and get the proper instance of Int.</p><p>flatMap is now <a href="https://developer.apple.com/documentation/swift/sequence/2907182-flatmap">deprecated</a>. We need to use compactMap instead of flatMap.</p><h3>filter:</h3><p>As the name suggests the filter HOF will filter a collection. We need to feed the filter with a closure which will act as a filter constrain. <br>If we put it simply filter will operate on a collection with some filter-operation and finally will give us a filtered collection. <br>Lets see an example.</p><pre>let jedi = [&quot;Yoda&quot;, &quot;Obi-Wan Kenobi&quot;, &quot;Anakin Skywalker&quot;, &quot;Luke Skywalker&quot;]</pre><pre>jedi.filter({ $0.contains(&quot; &quot;) })<br>// [&quot;Obi-Wan Kenobi&quot;, &quot;Anakin Skywalker&quot;, &quot;Luke Skywalker&quot;]</pre><p>Here $0 is the <a href="#Shorthand-argument-name">shorthand argument name</a> and the contains() is the regular closure/function of String. <br>On the above example we are filtering-out the names which does not have two part separated by a space. So at the end we are getting a collection on two part Jedi names.</p><p>Let us see another example.</p><pre>[20, 23, 21, 5, 0, 45].filter({ $0 % 5 == 0 })<br>//[20, 5, 0, 45]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*31NxEoRCC8vGTE4H.png" /></figure><p>Here we are filtering the Int array as if the reminder of 5 is equal to zero.</p><p><strong>When to use filter</strong> :<br>When ever we need to filter on a collection.</p><h3>reduce:</h3><p>The feature of reduce is to combine the elements of a collection into a cumulative return. <br>Kind of reducing multiple elements into one. <br>Among the HOF we discussed here, the reduce will be the toughest one. Oh Don&#39;t tens we got it cover. 👌</p><p>Let us jump-in with some simple example and the longer format of closure to get it first. Then gradually we will move to optimal format.</p><p>So here is the reduce signature.</p><pre>func reduce&lt;Result&gt;(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -&gt; Result) rethrows -&gt; Result</pre><p>Result is a generic type instance, we gonna cover it up on some future post. But for now informed that generic type represents a set of types, which may or may not be bounded by a or multiple protocol. <br>The &lt;Result&gt; at the start of the first bracket tells the compiler that the Result is a generic instance.</p><p>On the other hand Element is the associatedtype instance which represents the elements of the corresponding collection. Again we will have some future post for associatedtype.</p><p>And the throws and rethrows are used for exception handling. Please have a visit to our <a href="https://mobidevtalk.com/error-handling-through-try-variance/#throws-and-rethrows">error handling blog post</a> if you are interested.</p><p>So on the following section we will forget the Result, Element, throw and rethrow.</p><p>We will now replace the generic type with our well-known type like Int and Double, our input will be an Int array and the cumulative result will be be Double. Now reduce becomes more easier to digest, at-least for the very first time.</p><pre>func reduce(_ initialResult: Double, _ nextPartialResult: (Double, Int) throws -&gt; Double) rethrows -&gt; Double</pre><p>A bit easy for eye. Let us make it more easier. Now let us remove the throw and rethrow, just for the understanding !!!</p><pre>func reduce(_ initialResult: Double, _ nextPartialResult: (Double, Int) -&gt; Double) -&gt; Double</pre><p>Now lets reduce the reduce to even granular level. Basically we can now find these three sections on this method signature.</p><ul><li>initialResult which is Double type.</li><li>nextPartialResult which is a closure, the signature is (Double, Int) -&gt; Double. So thats mean the first argument is a Double type second one is Int type and the return of the closure is Double type.</li><li>The final part is, the return of reduce which is Double type.</li></ul><p>🤓</p><p>Things are very easy now. So whats now. Yes must be an example. Lets start with the easy one.</p><pre>let numbers = [0, 1, 2, 4]<br>let initialResult = 1.9</pre><pre>numbers.reduce( initialResult, { (result: Double, num: Int) -&gt; Double in<br>    var total = result<br>    (total += Double(num))<br>    return total<br>})<br>// 8.9</pre><p>Remember as we said closure are smart when we said closure <a href="#Inferring-param-and-return-type">Can infer the type of param &amp; return from surround context</a>. So by removing the types, next version will be:</p><pre>numbers.reduce( initialResult, { (result, num) in<br>    var total = result<br>    (total += Double(num))<br>    return total<br>})<br>//8.9</pre><p>Also closure can have <a href="#Shorthand-argument-name">shorthand form</a>. So:</p><pre>numbers.reduce(initialResult, { $0 + Double($1) })<br>// 8.9</pre><p>Ahem smarter. 🕶️</p><p>Image image image please !!! give me some image…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*WjBdP5tTl7wILDb7.png" /></figure><p>Now there is another version of reduce . It looks like nearly the same.</p><pre>func reduce&lt;Result&gt;(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -&gt; ()) rethrows -&gt; Result</pre><p>The first difference between the previous version of reduce and the current version of reduce is the inout version of Result. So what is inout? When an argument is labeled as inout thats mean we can overwrite that argument.<br>The second one is the closure updateAccumulatingResult which does not return, rather assign the result to the Result typed instance.<br>And obviously the method signature is a bit different among two, this one has the into.</p><p>And I know we can break down this one as we did for the previous version. Go ahad and break it down. Believe me it is worthy 👩‍💻.</p><p>So lets update our sum of numbers with the inout version of reduce</p><pre>numbers.reduce(into: initialResult) { (result, num) in<br>    result += Double(num)<br>}<br>// 8.9</pre><p>Aha suddenly it becomes short. Have a look at the changes from the previous version. <br>Yep you got it, the inout version of result. As we can write on result, so we are directly using the addition assignment operator, += to update result. For the same reason, inout, we are not returning any result from the closure.</p><p>Ok, we are not forgetting the shorthand form on closure, right? Here it is:</p><pre>numbers.reduce(into: initialResult, { $0 += Double($1) })</pre><p>So every thing is clear now.</p><p><strong>When to use </strong><strong>reduce</strong>:<br>When we need a cumulative result from a collection.</p><p>We know how the reduce HOF works. But are we forgetting something? Come on... Jedi</p><pre>let jedi = [&quot;Yoda&quot;, &quot;Obi-Wan Kenobi&quot;, &quot;Anakin Skywalker&quot;, &quot;Luke Skywalker&quot;]<br>jedi.reduce(into: &quot;Available Jedi: &quot;, { $0 += &quot;\n \($1)&quot; })<br>/*<br>Available Jedi: <br> Yoda<br> Obi-Wan Kenobi<br> Anakin Skywalker<br> Luke Skywalker<br>*/</pre><p>Now it is complete. ⌛</p><p>Just remember when ever you have confusion about HOF, just go and break down that HOF. Then come up with the longer version of closure, then gradually move to shorter closure format.</p><p>See you soon on the next post. Till then Happy Mobi Dev talks.</p><p>This story is basically the first one of a two series blog post from <a href="https://mobidevtalk.com/">mobidevtalk.com</a></p><p><a href="https://mobidevtalk.com/drilling-hof-higher-order-function/">Drilling HOF, Higher order Function</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9adafbe3bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/drilling-hof-higher-order-function-da9adafbe3bf">Drilling HOF, Higher order Function</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[tuple & typealias, the little buddies on Swift | mobidevtalk.com be a pro]]></title>
            <link>https://medium.com/mobidevtalk/tuple-typealias-the-little-buddies-on-swift-mobidevtalk-com-be-a-pro-7845b53d8106?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/7845b53d8106</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[tuples]]></category>
            <category><![CDATA[typealias]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Tue, 08 Jan 2019 17:24:23 GMT</pubDate>
            <atom:updated>2019-10-13T15:36:32.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CxTabDno1kQ1Ghk4.png" /></figure><p>Tuple may seems like a non-important topic to talk about on Swift. But smart dudes knows the benefit of using tuple. Mixing tuple with typealias on Swift can make our code more joyful to our coworker. So let us dive deep.</p><h3>Background</h3><ul><li><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/#Who-are-you-tuple">What is tuple</a></li><li><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/#tuple-declaration-and-usage">tuple declaration and usage</a></li><li><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/#When-to-use">When to use</a></li><li><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/#Why-to-use">Why to use</a></li><li><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/#typealias-with-tuple">typealias with </a><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/#typealias-with-tuple">tuple</a></li><li><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/#Difference-from-an-Array">Difference from an Array</a></li></ul><h3>Who are you tuple</h3><p>tuple is just a group of types. What types? any types such as Int, String etc even custom type. Any limitation on number of type? Nope there is none.</p><pre>let greetings = (&quot;Hola&quot;, &quot;Spanish&quot;) <br>greetings.0 // &quot;Hola&quot;</pre><p>On the above (&quot;Hola&quot;, &quot;Spanish&quot;) is a tuple. Here it is constructed with two String. Simple right?</p><h3>tuple declaration and usage</h3><p>There are two ways of creating the tuple.</p><p>Without any name of the elements or types. As we saw on the previous section’s example:</p><pre>let greetings = (&quot;Hola&quot;, &quot;Spanish&quot;)</pre><p>Here greetings has a tuple of type (String, String). As the individual String type does not have a name, we have to access them by using the chronology of their appearance on the tuple type. So to access the &quot;Spanish&quot; we have to use the index 1.</p><pre>greetings.1 / &quot;Spanish&quot;</pre><p>On the other hand we can use some kind of name on each of the elements or type of a tuple.</p><pre>let organisedGreetings = (phrase: &quot;Hej&quot;, locale: &quot;Swedish&quot;) organisedGreetings.phrase //&quot;Hej&quot;</pre><p>Now we can access the Hej by using the name, phrase, of the tuple type. Though We will loose the ability to use the index, as we did on the previous greetings, if we use the name typed tuple. But names on tuple have more code readability.</p><h3>When to use</h3><p>Well there can be two common place to use tuple.</p><ul><li>When we need to group multiple types in a single place</li><li>when a function needs to returns multiple Types.</li></ul><pre>func info()-&gt;(name: String, age: Int){ <br>    return (&quot;mobidevtalk&quot;, 0) <br>} <br>let mobiDevTalkInfo = info() <br>mobiDevTalkInfo.name <br>mobiDevTalkInfo.age</pre><p>Here the function info() is returning a Tuple.</p><h3>Why to use</h3><p>The reason is very simple:</p><ul><li>Simplicity</li><li>Lightweight</li><li>Clarity</li></ul><p>Let us consider the function info() on the previous section. So if we did not use the tuple then we have to find some other alternative way, like creating another Type, like as following:</p><pre>struct Info{ <br>    let name: String l<br>    et age: Int <br>} </pre><pre>func modifiedInfo() -&gt; Info{ <br>    return Info(name: &quot;mobidevtalk&quot;, age: 0) <br>}</pre><p>As we can see it is an overhand of a simple task when we do not use the tuple.</p><h3>typealias with tuple</h3><p>Sometimes we mix tuple with typealias. But those two are entirely different and used for two separated purpose. So what is typealias?</p><p>typealias is a redeclaration of an existing type, more appropriately named alias.</p><pre>typealias Amount = Int <br>typealias Execute = (Int)-&gt;(String)</pre><p>As we can see the Amount is representing Int. But if we are working with some financial concepts then the Amount makes more sense than the Int. Similarly Execute also a named alias of a function.</p><p>Now those simple example can not infer the importance of typealias.</p><p>typealias with tuple can makes our code more concise with better readability and simplicity. Example please:</p><pre>typealias Age = (month: Int, year: Int) </pre><pre>struct Profile{ <br>    let name: String <br>    let age: Age <br>} <br>let profile = Profile(name: &quot;mobidevtalk&quot;, age: Age(month: 4, year: 0)) <br>profile.age.month // 4 let </pre><pre>shortProfile = Profile(name: &quot;mobidevtalk&quot;, age: (4, 0)) shortProfile.age.year // 0</pre><p>As we can see the Age is a typealias of the tuple (month: Int, year: Int). Later down the code we are using Age as the alternative of that tuple. At the same time the tuple is holding a combined type of (Int, Int). So those two concepts are making the code more concise. Giving us a far more better readability and simplicity in our current, profile based context.</p><h3>Difference from an Array</h3><p>This may not be an obvious topic, but let us face it. Array is a collection type of object. tuple is also a group of objects. So are they similar? Ha ha, silly question.</p><p>No they are not the same. Array is a collection of same typed object. So all the elements of an array must be the same type, either all need to be Int or String or any other of same type.</p><p>On the other hand tuple is obviously a group of types but it is definitely not a collection of objects.</p><h3>End talk</h3><p>So this was our small talk on tuple &amp; typealias on Swift. As always all the codes are available on <a href="https://github.com/mobidevtalk/tuples/blob/master/tuples.playground/Contents.swift">GitHub</a>.</p><p>We also have some talks on enum. All the talks over enum are available on <a href="https://mobidevtalk.com/swift-enum-hub/">Enum Hub</a>.</p><p>Hope to see you in our next talk. Till then Happy talking.</p><p><em>Originally published at </em><a href="https://mobidevtalk.com/swift-typealias-tuple-the-little-smart-dude/"><em>https://mobidevtalk.com</em></a><em> on January 8, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7845b53d8106" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/tuple-typealias-the-little-buddies-on-swift-mobidevtalk-com-be-a-pro-7845b53d8106">tuple &amp; typealias, the little buddies on Swift | mobidevtalk.com be a pro</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift error handling through try variance using enum | @mobidevtalk.com]]></title>
            <link>https://medium.com/mobidevtalk/swift-error-handling-through-try-variance-using-enum-mobidevtalk-com-654f5ce74706?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/654f5ce74706</guid>
            <category><![CDATA[do-catch]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[try-catch]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Sun, 30 Dec 2018 01:42:29 GMT</pubDate>
            <atom:updated>2019-09-01T00:15:08.577Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/">Swift error handling through try variance using enum | @mobidevtalk.com</a></p><p>Each and every system has erroneous state, smart system handle those error and fall gracefully, so that the end user don’t just freakout. Swift also provides us with some cool error handling system which can be really worthy when used with try and enum.</p><p>On this short blog post we will talk about Swift error handling mechanism. We will concentrate on try to handle those error. Also the reason for choosing enum as the first choice for defining error model.</p><p>For the best reading experience read the <a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/">original blog post mobidevtalk</a>.</p><h3>Background</h3><ul><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Pretalk-on-Error-handling">Pretalk on Error handling ?</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Error">What is </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Error">Error?</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#enum-as-Error-why?">Why </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#enum-as-Error-why?">enum is the first choice for Error definition?</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#throws-and-rethrows">What </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#throws-and-rethrows">throws </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#throws-and-rethrows">rethrows keywords mean?</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Error-Handling">How to handling Error?</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Propagation-of-Error">Propagation of Error</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#try-with-do-catch-block">try with </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#try-with-do-catch-block">do-catch block</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Usage-of-try-with-do-catch-block">Usage of </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Usage-of-try-with-do-catch-block">try with </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Usage-of-try-with-do-catch-block">do-catch block</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Optional-value-through-try?">Optional value through </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Optional-value-through-try?">try?</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Usage-of-try?">Usage of </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Usage-of-try?">try?</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Disabling-Error-propagation-through-try!">Disabling Error propagation through </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Disabling-Error-propagation-through-try!">try!</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Usage-of-try!">Usage of </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Usage-of-try!">try!</a> 🧨</li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Result">Result&lt;T&gt;</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#enum-conforming-Error-protocol,-with-associated-value">enum conforming </a><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#enum-conforming-Error-protocol,-with-associated-value">Error protocol, with associated value</a></li><li><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/#Best-practices-becoming-pro">Best practices to follow.</a></li></ul><p>We already have some talk over enum. On the <a href="https://mobidevtalk.com/swift-enum-hub/">enum hub page</a> we can find the details on enum arena.</p><h3>Pretalk on Error handling</h3><p>So why do we want Error handling? Well error can happens at any stage even on the most well defined and well architectural app. We have to move on by understanding one true thing, error will occur. How will we handle that error is the important part. Because how would you like an app, which crashes often or regular? No one likes that.</p><p>We used to spend some good weeks or even months to build up a moderated app. Just putting some more hours on error handling would make that app a good one. User will get a smooth feelings with the app. Even on the most erroneous situation the app does not crash, this gets the trust from the valuable user. And we all know gaining user’s trust is a crucial part for the long run.</p><p>Enough talk, think we all understand the simple thing. Adding proper error handling won’t take long, but give a very high return. Worth investing?</p><h3>Error</h3><p>On Swift Error is an empty protocol, with no requirements to fill. So any type can adapt the Error protocol.</p><p>On Swift only an instance of Error can be thrown. So we need to adopt the Error protocol, if we want to use that type as an throwable when error occurs.</p><p>Thinks will be more clear on the next section.</p><h3>enum as Error why?</h3><p>A lot of times we will/had listen that, enum are perfect for Error conformation. But why? What is the relation thats makes enum suitable for Error.</p><p>We can always visits the enum blog series for more in-depth knowledge on enum.</p><ul><li><a href="https://mobidevtalk.com/love-for-enum/">Love for Enum</a></li><li><a href="https://mobidevtalk.com/love-for-enum-continuing/">Love for Enum, continuing</a></li><li><a href="https://mobidevtalk.com/tic-tac-toe-through-enum/">Tic tac toe, through enum</a></li></ul><p>Back to our original topic. As we know enum are pre defined case based architecture, and at a time only one value/case is true for an enum instance. This goes pretty much same for an Error. At a time only one error can occur among pre define Error set.</p><p>Also additional information for a specific error sometimes may be needed. As an example: for age limit verification failure there cloud be overaged or underaged Error. enum &#39;s associated value cloud serve this extra information. We will have an example on this issue later on this blog post.</p><h3>throws and rethrows</h3><p>Let us talk with the throws keyword first. When a function has throws keyword on the definition, that means the function can throw error and the function is called throwing function.</p><p>On the other side, when a function has rethrows keyword on the definition then that function is called rethrowing function. Now to be a rethrowing function that function, should have a functional parameter which is a throwable function. Let us have an example:</p><pre>enum ReminderError: Error{ <br>    case invalidParam <br>} <br>var divisor = 0 </pre><pre>func hundredReminder() throws -&gt; Int{ <br>    if divisor == 0 { <br>        throw ReminderError.invalidParam <br>    } <br>    return 100 % divisor <br>} </pre><pre>func absReminder(input: Int, reminder: () throws -&gt; Int) rethrows -&gt; Int{ <br>    divisor = input &lt; 0 ? abs(input) : input <br>    return try reminder() <br>} </pre><pre>do { <br>    try absReminder(input: -0, reminder: hundredReminder) <br>} <br>catch ReminderError.invalidParam { &quot;Check ur input&quot; }</pre><p>On the above example hundredReminder() is a throwing function as it has the throws keyword on the definition. And absReminder(input: Int, reminder: () throws -&gt; Int) rethrows -&gt; Int is a rethrowing function. Have a look at the reminder params which states that it is a throwing function, thats why the absReminder needed to be a rethrowing function.</p><p>If there is some confusion, don’t tense. I will be clear on this blog post. It is step by step learning. We just clear the throws and rethrows concepts. Now lets move to our next topic.</p><h3>Error Handling</h3><p>We already have some idea on how to handle errors, and those errors are recoverable error. So the thing is pretty straight forward. We will throw an error if something goes wrong and on the caller we will handle those error to prevent a disaster crash, graceful fall may be . So there are some ways we can handles the error. We will talk about those in the upcoming sections.</p><h3>Propagation of Error</h3><p>The concept of throwing an error is called propagating of Error or Error propagation. So each time a throwing function throws an error it is actually propagating the error. Simple 🤗.</p><h3>try with do-catch block</h3><p>On this approach the throwing function is marked with try and is surrounded by a do-catch block. Example follows:</p><pre>enum PrintError: Error{ <br>    case InvalidName case EmptyName <br>} </pre><pre>func validate(name: String?) throws{ <br>    guard let name = name else { throw PrintError.InvalidName } </pre><pre>    if name.isEmpty { throw PrintError.EmptyName } <br>} </pre><pre>func print(name: String?){ <br>    do { <br>        try validate(name: name) <br>        print(&quot;Name is: \(name!)&quot;) <br>    } catch PrintError.InvalidName { <br>        print(&quot;Got an Invalid Name&quot;) <br>    } catch PrintError.EmptyName { <br>        print(&quot;Got an Empty Name&quot;) <br>    }catch {<br>        &quot;Other error \(error.localizedDescription)&quot;<br>    } <br>} </pre><pre>print(name: &quot;&quot;) //Prints: Got an Empty Name <br>print(name: nil) //Prints: Got an Invalid Name <br>print(name: &quot;Mobi Dev Talk&quot;) //Prints: Name is: Mobi Dev Talk</pre><p>Here validate(name: String?) is the throwing function and on the print(name: String?) we are handling the error. Inside the do-catch block we are getting all the defined error of PrintError including a final catch case, &quot;Other error \(error.localizedDescription)&quot;. So now the question is where did the error comes from? Well error is an instance of Error, more appropriately local error constant. This default error is provided by the Swift error handling system. If none of the above error-patterns matches then this final catch case with error will execute. Hmm smart move.</p><p><strong>One crucial point</strong>: if we do not provide the final catch case ,with builtin error var, then there is a potential crash possibility of unhandled error. So we always should provide the final catch case.</p><h3>Usage of try with do-catch block</h3><ul><li>When safety is the major concern.</li><li>When we need to know what specific type of error occurred.</li></ul><h3>Optional value through try?</h3><p>Using try? will provide an optional value, so either there will be a proper value or there will be nil. The try? will not provide any error details, rather will provide nil if any error occurs.</p><pre>func possiblePrint(name: String?) throws -&gt; String{ <br>    guard let name = name else { throw PrintError.InvalidName } </pre><pre>    if name.isEmpty { throw PrintError.EmptyName } </pre><pre>    return name <br>} </pre><pre><strong>var</strong> possibleName = <strong>try</strong>? possiblePrint(name: &quot;&quot;) possibleName?.capitalized // nil  </pre><pre>possibleName = <strong>try</strong>? possiblePrint(name: nil) possibleName?.capitalized // nil  </pre><pre>possibleName = <strong>try</strong>? possiblePrint(name: &quot;mobi dev talk&quot;) possibleName?.capitalized // Mobi Dev Talk</pre><p>On the above example possiblePrint(name: String?) is a throwing function. It will returns a String if no error is thrown.</p><p>We declare possibleName as a var for reusability. Each time we are assigning possibleName we are using the try?. As a result possibleName is optional String, String?, even though possiblePrint(name: String?) returns a String instance not a String?. The try? is converting the proper value of String to optional string, String?.</p><h3>Usage of try?</h3><p>When we have no concern about the error. We are only interested on the operation or on the value, if the throwing function succeeded.</p><h3>Disabling Error propagation through try!</h3><p>This option is the most dangerous one. try! will disable any error propagation. So if any error occurs immediately the app will crash.</p><pre>var unwrappedName = try! possiblePrint(name: &quot;mobi dev talk&quot;) unwrappedName.capitalized // Mobi Dev Talk </pre><pre>//unwrappedName = try! possiblePrint(name: &quot;&quot;) //unwrappedName.capitalized // crashs the app </pre><pre>//unwrappedName = try! possiblePrint(name: nil) //unwrappedName.capitalized // crashs the app</pre><p>The unwrappedName has a type of String as the try! will forcefully unwrapped the returned value, cloud be either String or an instance of Error.</p><p>For a valid name the app will not crash but for an empty or a nil value the app will surely crash 💥.</p><h3>Usage of try!</h3><p>💣 When the developer wants to nuke the code base 🔥</p><h3>Result&lt;T&gt;</h3><p>There is a common patterns to extract success or fail result. Very useful on asynchronous call. The syntax as follows:</p><pre>enum Result&lt;Value, Error: Swift.Error&gt;{ <br>    case success(Value) <br>    case fail(Error) <br>}</pre><p>Here the Value is a generic type. We can use the above Result enum as our functional parameter to handle error when we are doing an asynchronous call. The target of this section is to have an introduction with the patterns. For more info we can visit Sundell&#39;s blog which has <a href="https://www.swiftbysundell.com/posts/the-power-of-result-types-in-swift">a beautiful descriptive blog post</a> covering this topic.</p><h3>enum conforming Error protocol, with associated value</h3><p>One last thing to talk about, before wrapping up this blog post. How associated value can help to provide the additional information for a specific error.</p><p>Say we have a registration workflow which has an age limitation, the limit is over 18 and under 30. We want to know why a registration request would fail? Is it because of an invalid username or is it because of an improper age of the user. If the reason is improper age then we would like to know, if the user is overaged or underaged.</p><p>So here goes the code:</p><pre>enum AgeError : String{ <br>    case underaged <br>    case overaged <br>} </pre><pre>enum RegistrationError : Error{ <br>    case invalidUserName <br>    case improperAge(AgeError) <br>} </pre><pre>func registration(userName: String, age: Int) throws { <br>    if userName.isEmpty { <br>        throw RegistrationError.invalidUserName <br>    } <br>  <br>    if age &lt; 18 { <br>        throw RegistrationError.improperAge(.underaged)    <br>    }else if age &gt; 30{ <br>        throw RegistrationError.improperAge(.overaged) <br>    } <br>} </pre><pre>do { <br>    try registration(userName: &quot;mobidevtalk&quot;, age: 0) <br>} catch RegistrationError.improperAge(let age) { <br>   age //underaged <br>   } </pre><pre>do { <br>   try registration(userName: &quot;mobidevtalk&quot;, age: 90) <br>} catch RegistrationError.improperAge(let age) {<br>    age //overaged <br>}</pre><p>As we can see the improperAge of RegistrationError has an associated value. On current time it is an enum, AgeError, having a String raw type.</p><p>Here the associated value of improperAge is providing the additional information, underaged or overaged, when there is an age violation on the registration flow.</p><h3>Best practices, becoming pro</h3><ul><li>Choose try with do-catch block as default error handler. Always provide the final catch case for handling the unspecified errors.</li><li>If and only if, you do not need the error then use the Optional value type through try?.</li><li>Are you expecting some advice to use try!? I have only one. Pray to God. God dammit !!! never ever use try! on production code.</li></ul><p>So that is it for today. The source is used here are shared at <a href="https://github.com/mobidevtalk/error_handling/blob/master/ErrorHandlingThroughTryVariance.playground/Contents.swift">GitHub</a>.Our error handling with try variance is now completed. Happy Error Handling. 🖖</p><p><em>Originally published at </em><a href="https://mobidevtalk.com/swift-error-handling-through-try-and-enum/"><em>https://mobidevtalk.com</em></a><em> on December 30, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=654f5ce74706" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/swift-error-handling-through-try-variance-using-enum-mobidevtalk-com-654f5ce74706">Swift error handling through try variance using enum | @mobidevtalk.com</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Swift enum case study, Tic tac toe, through example | @mobidevtalk]]></title>
            <link>https://medium.com/mobidevtalk/enum-case-study-tic-tac-toe-97eeb284105f?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/97eeb284105f</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[tic-tac-toe-game]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 06:33:07 GMT</pubDate>
            <atom:updated>2019-07-26T20:01:01.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msJAmOc1QbKCBvWUpvciSQ.jpeg" /><figcaption>Tic tac toe at <a href="https://mobidevtalk.com/swift-enum-case-study-example/">mobidevtalk.com</a></figcaption></figure><p>On the last two blog post, <a href="https://mobidevtalk.com/love-for-enum/">Love for enum</a> &amp; <a href="https://mobidevtalk.com/love-for-enum-continuing/">continue…</a>, we build our base for a more advance talk. Which leads us to this blog post were we will implement our already learned knowledge from those two blog post to build a case study here. No doubt enum plays an important role on Swift learning. A case study buildup through step by step cloud guide us to the why and how of enum in Swift, study through example and real time implementation will solidify our enum learning. So let us not delay any further. Let’s build the case study, A simple Tic tac toe game.</p><p><strong>For the best Experience we can always visit the original </strong><a href="https://mobidevtalk.com/swift-enum-case-study-example/"><strong>blog post on mobidevtalk.com</strong></a><strong>.</strong></p><p><strong>Special note: </strong>To build up this case study our first choice was always enum among other options, struct or class. We can always go through the <a href="https://developer.apple.com/swift/blog/?id=10">apple blog</a> on which the choosing among <strong>Value Type</strong> and <strong>Reference Type</strong> are beautifully describe. If you haven&#39;t read that one, I will request you do.</p><p>So we gonna build a very basic game Tic tac toe. Ok no UI, sorry! Logic part only. Come on we are building a Swift enum based case study not a full phase Tic tac toe with example UI. And if you have the brain part then how long to build the UI. Ready?</p><h3>Background</h3><ul><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Player">Player</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-not-class">Why Player not a </a><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-not-class">class</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-not-struct">Player not a </a><a href="https://mobidevtalk.com/wp-admin/post.php?post=367&amp;action=edit#Why-not-struct">struct, why</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-not-Bool">Why Player not a </a><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-not-Bool">Bool</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Square">Square</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Square-to-be-a-RawRepresentable">Square to be a </a><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Square-to-be-a-RawRepresentable">RawRepresentable</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Winning-streak">Winning streak</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Game-states">Game states</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-associated-Value">Why to use associated Value</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Game-state-as-CustomStringConvertible">Game state as </a><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Game-state-as-CustomStringConvertible">CustomStringConvertible</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Game-logic">Logical part of game</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#Game-play">Game play</a></li><li><a href="https://mobidevtalk.com/swift-enum-case-study-example/#TDD-teaser">TDD teaser</a></li></ul><h3>Player</h3><p>Tic tac toe is a two player game. So two cases, Perfect for enum:</p><pre>enum Player { <br>    case First <br>    case Second<br>}</pre><p><strong>Q/A</strong>:</p><ul><li>Why do we choose enum over struct and class?</li><li>How about Bool as it has only two possibilities?</li></ul><h3>class, Why not</h3><p>We do not need any instance of NSObject and also we are not to change the status of a player, first player will not be second and vice versa. So class is not an option.</p><h3>struct, why not</h3><p>Ok from the above assertion it should be a value type object. Now we can clearly see it has two state, First and Second, and at a time only one will be active, so this makes it very simple to choose. struct can be used if there are some vars or state which will live together. So struct not a good option.</p><h3>Bool, Why not</h3><p>Player has two state, First and Second. So isFirstPlayer: Bool instead of Player is a good option, ahh cloud be! But wait, will we always use something like isFirstPlayer? doSomething : doAnotherThing whenever we need to make a decision? even to assign a var? Bool type checking is not pretty 😉.</p><h3>Square</h3><p>On 3X3 Tic tac toe, there will be total of 9 square. We can define them as follows:</p><pre>enum Square { <br>    case One_One, One_Two, One_Three <br>    case Two_One, Two_Two, Two_Three <br>    case Three_One, Three_Two, Three_Three <br>}</pre><p>Again we do not want <a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-not-class">value mutability, </a>. And Square will have only one instance and that instance do not have any other <a href="https://mobidevtalk.com/swift-enum-case-study-example/#Why-not-struct">var/instance to live together, </a>.</p><p>Additional <strong>Q/A</strong><br>Why Array or any other collection type was not chosen instead of the enum, Square? <br>We already answered that on<a href="https://mobidevtalk.com/love-for-enum/#other-collection-types"> Love for Enum</a> blog post.</p><h3>Square to be a RawRepresentable</h3><p>So far we have only declared the nine squares, but have not assign any value to those squares. We need to have some kind of identifier to uniquely identify each square.</p><p>So can we use Int as the RawRepresentable of Square?</p><p>Hmm it solves the unique identifier issue. But there is more. We also need to compare the values among square to find the winning streak. And one of them is the diagonal winning streak. Single value Int will not be enough. The winning streak is always a two dimensional value to be compared, unless someone wants to write down all the winning combination/streak one after another on a static way.</p><p>So now we know we need to have a two dimensional value, that mean tuple. We can call this tuple as Position. So here we go:</p><pre>extension Square: RawRepresentable{ <br>    typealias Position = (row: Int, column: Int) <br>    var rawValue: Position{ <br>        switch self { <br>            case .One_One: <br>                return (row: 1, column: 1) <br>            case .One_Two: <br>                return (row: 1, column: 2) <br>            case .One_Three: <br>                return (row: 1, column: 3) <br>            case .Two_One: <br>                return (row: 2, column: 1) <br>            case .Two_Two: <br>                return (row: 2, column: 2) <br>            case .Two_Three: <br>                return (row: 2, column: 3) <br>            case .Three_One: <br>                return (row: 3, column: 1) <br>            case .Three_Two: <br>                return (row: 3, column: 2) <br>            case .Three_Three: <br>                return (row: 3, column: 3) <br>            } <br>    } </pre><pre>init?(rawValue: Position) { <br>    switch rawValue { <br>        case (row: 1, column: 1): <br>            self = .One_One <br>        case (row: 1, column: 2): <br>            self = .One_Two <br>        case (row: 1, column: 3): <br>            self = .One_Three <br>        case (row: 2, column: 1): <br>            self = .Two_One <br>        case (row: 2, column: 2): <br>            self = .Two_Two <br>        case (row: 2, column: 3): <br>            self = .Two_Three <br>        case (row: 3, column: 1): <br>            self = .Three_One <br>        case (row: 3, column: 2): <br>            self = .Three_Two <br>        case (row: 3, column: 3): <br>            self = .Three_Three <br>        default: <br>            return nil <br>    } <br>}</pre><p>On the above Square is conforming the RawRepresentable protocol. As a result Square need to provide the conversion from and into the rawValue, Position. We had a detail talk on previous <a href="https://mobidevtalk.com/love-for-enum/#rawValue-of-custom-type">enum blog post</a>.</p><h3>Winning streak</h3><p>We can have one of the three winning streak, horizontal or vertical or diagonal. So by considering two thing, immutable values(discard class) and only one among three case will be active(discard struct), we can use enum.</p><pre>enum WinningStreak: String{ <br>    case horizontal <br>    case vertical <br>    case diagonal <br>}</pre><p>We are setting String as the raw type of WinningStreak, because later down the road we will print the winning combination. BTB we already published the <a href="https://mobidevtalk.com/love-for-enum/#rawValue">raw value blog talk</a>.</p><p>horizontal WinningStreak can happen either on the first, second or third row. Similarly vertical and diagonal has multiple possibilities. We are discarding those possibilities for making this blog post concise.</p><h3>Game states</h3><p>We can have either inProgress, draw or a win state for a game. Again one of three options/case. And immutable value is not needed. So what do you think? It should be an enum:</p><pre>enum GameState { <br>    case inProgress <br>    case draw <br>    case win(Player, WinningStreak) <br>}</pre><p>The win case have an associated value and it is a tuple of Player and WinningStreak.</p><h3>Why associated Value</h3><p><strong>Q/A: </strong>Why the associated value on win case and why others don&#39;t have the associated value?</p><p>Hmm seems like a silly question, but not so. Answer to this question will help us to add associated value to our case when needed.<br>The functionality of associatedValue is to provide a way to that corresponding case to have an extra storage for additional info. You can read more on our <a href="https://mobidevtalk.com/love-for-enum/#associated-Values">previous blog post</a>.</p><p>Now the inProgress and draw do not need any more info. Because both of these two cases are stating the game state where both the Payer s are involved. Also the game state is self explanatory for those two cases.</p><p>But on the case of win two obvious question comes up. Who win? and which combination was used? So these two questions are pointing to Player and WinningStreak.</p><h3>Game state as CustomStringConvertible</h3><p>GameState is the end of game, once we got either draw or win, we can publish the game result on a String format. For inProgress we can just say the game is still going. The CustomStringConvertible protocol will serve us the best on this regard. It has a description var, which we need to implement for all the cases of GameState.</p><pre>extension GameState: CustomStringConvertible{ <br>    var description: String{ <br>        switch self { <br>            case .inProgress: <br>                return &quot;Game is running&quot; <br>            case .draw: <br>                return &quot;Game ended up in a draw&quot; <br>            case .win(let player): <br>                return &quot;\(player) won on \(streak) combination&quot; <br>         } <br>    } <br>}</pre><h3>Game logic</h3><p>Now we need to calculate the WinningStreak. First We will write down a function to calculate the result. We will feed this function with the sequence of a single player.</p><pre>func result(for sequence: [Square]) -&gt; WinningStreak?{ <br>    guard sequence.count == 3, sequence[0] != sequence [1]<br>      , sequence[1] != sequence[2], sequence[2] != sequence[0] <br>    else { <br>        return nil <br>    }</pre><pre>    if sequence[0].rawValue.row == sequence[1].rawValue.row <br>      &amp;&amp; sequence[1].rawValue.row == sequence[2].rawValue.row { <br>        return .horizontal <br>    } </pre><pre>    if sequence[0].rawValue.column == sequence[1].rawValue.column <br>      &amp;&amp; sequence[1].rawValue.column == sequence[2].rawValue.column{           <br>        return .vertical <br>    } </pre><pre>    if (sequence[0].rawValue.row == sequence[0].rawValue.column <br>      &amp;&amp; sequence[1].rawValue.row == sequence[1].rawValue.column <br>      &amp;&amp; sequence[2].rawValue.row == sequence[2].rawValue.column) <br>      || Set(arrayLiteral: sequence) == <br>      Set(arrayLiteral: [Square.One_Three, .Two_Two, .Three_One]){<br>        return .diagonal <br>    } </pre><pre>    return nil <br>}</pre><p>We will return nil on three situation.</p><ul><li>If the sequence is lower or higher than 3.</li><li>If any two of the sequence elements are same.</li><li>And if no WinningStreak can be formed from the sequence.</li></ul><p>The horizontal and vertical checking is pretty simple. Same row for all three combination will result on horizontal win, on the other hand three same column will result on vertical win.</p><p>For diagonal win, there are two possibilities. On one possibility all the elements of sequence will have the same row and column individually. And another possibility is kind of a static check of the square.</p><p>For the static check we are using Set because we do not want any fixed chronology of elements, they can appear on any combination.</p><h3>Game play</h3><p>This is the last part of our Tic tac toe. We already laid down the necessary parts of the game. Now Game On 👊.</p><p>We will call our game play as TicTacToe. We will put one Square at a time. And will get the GameState immediately. Once we have a win we will also get that.</p><pre>class TicTacToe{ <br>    private var sequence = [Square]() <br>    <br>   func progress(_ square: Square) -&gt; GameState? { <br>       guard sequence.count &lt; 9 else { <br>           return nil <br>       } <br>       sequence.append(square) </pre><pre>       guard sequence.count &gt; 4 else { <br>           return .inProgress <br>       } </pre><pre>       var firstPlayerSequence = [Square]() <br>       var secondPlayerSequence = [Square]() <br>   <br>       for (index, square) in sequence.enumerated(){ <br>           index % 2 == 0 ? firstPlayerSequence.append(square) :<br>             secondPlayerSequence.append(square) <br>       } </pre><pre>       if let streak = result(for: firstPlayerSequence) { <br>           return .win(Player.First, streak) <br>       }<br>       else if let streak = result(for: secondPlayerSequence){   <br>           return .win(Player.Second, streak) }else{ return .draw <br>       } <br>    } <br>}</pre><p>We used class here rather than enum or struct. Because we need to mutate the sequence var. So as it is mutating it&#39;s own state we need to use class.</p><p>Now let us move our focus to progress function. As sequence will have max 9 elements so any more than that will result in nil. Once sequence got the 4 elements we will start calculating the WinningStreak. On the process of calculating the WinningStreak we are separating the elements into two array. Even index element goes to firstPlayerSequence and odd populates the secondPlayerSequence.</p><h3>End talk</h3><p>So that is it. Tic tac toe is ready. Again our main concern here was to watch the use of enum, not the Tic tac toe game. So there are still some works can be done to improve this game. You can find the source code on <a href="https://github.com/mobidevtalk/enum/blob/master/TicTacToe.playground/Contents.swift">GitHub</a>. This Swift enum case study based talk will not be successful unless the example code been studied. So please go through the example code of this case study to have a solid idea on Swift enum implementation.</p><h3>TDD teaser</h3><p>If you already saw the code on GitHub, you will see a lot of test codes, Actually 1.4 times than the source code. What happens there !!!</p><p>Well it was TDD. This project was started using TDD and continue till the end. To be honest it is always thrilling to write test code first then the production code. If you are interested then you can have a look at the <a href="https://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html">Cycles of TDD on Robert C. Martin (Uncle Bob)’s blog</a>.</p><p>On some future we will have a TDD series on iOS using Swift. And I can guarantee you one thing, it will not be a blog series it will be a video series. So much talk is not possible to be written down on just one or two blog post. Best possible way is to describe through video series. Also the short code to run the test on a playground file directly taken from <a href="https://www.swiftbysundell.com/posts/writing-unit-tests-in-a-swift-playground">Writing unit tests on playground</a> blog post written by Sundell.</p><p>So that&#39;s actually ends our talk with enum. See you around. Till then take care. 🖖</p><p><em>Originally published at </em><a href="https://mobidevtalk.com/swift-enum-case-study-example/"><em>https://mobidevtalk.com</em></a><em> on December 27, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97eeb284105f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/enum-case-study-tic-tac-toe-97eeb284105f">A Swift enum case study, Tic tac toe, through example | @mobidevtalk</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Enum Advance | mobidevtalk, Learning through case study]]></title>
            <link>https://medium.com/mobidevtalk/enum-advance-36ec834de2e1?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/36ec834de2e1</guid>
            <category><![CDATA[enumeration]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobidevtalk]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Wed, 26 Dec 2018 06:23:24 GMT</pubDate>
            <atom:updated>2019-07-19T20:01:04.160Z</atom:updated>
            <content:encoded><![CDATA[<p>On our previous <a href="https://mobidevtalk.com/love-for-enum/">blog post</a> we had some talk, which covers the surface of enum. Here we will dive a bit deeper for familiarizing ourself with some more advanced concepts of enum. And Finally on the <a href="https://mobidevtalk.com/tic-tac-toe-through-enum/">next case study blog post, tic tac toe through enum,</a> we will wrap it up by using our gained enum knowledge to implement a real life problem. So let&#39;s get started on our swift enum advance talk.</p><h4>For a better experience we can alway go back to the original blog post on <a href="https://mobidevtalk.com/">mobidevtalk.com</a>.</h4><h3>Background</h3><ul><li><a href="https://mobidevtalk.com/swift-enum-advance/#Generic-enum">Generic enum</a></li><li><a href="https://mobidevtalk.com/swift-enum-advance/#Error-definition-through-enum">Error definition</a></li><li><a href="https://mobidevtalk.com/swift-enum-advance/#Enum-mutation,-code-smelling">Why to avoid mutation on enum</a></li><li><a href="https://mobidevtalk.com/swift-enum-advance/#Recursive-enum">Recursive enum, when and how to use? Should be used? simplicity</a></li><li><a href="https://mobidevtalk.com/swift-enum-advance/#allCases-of-CaseIterable">allCases</a></li></ul><h3>Generic enum</h3><p>Generic itself is a big topic. We will cover generic on some future blog series. But here we can have a glimpse of Generic usage on enum. So what is the generic concepts? Generic basically broader the boundary of types, ie String Int etc, So that a larger number of types can be target of some task. In other words we can use multiple types all together when we put those types under Generic. We can also shorter the boundary by applying some constraints. On the following code T itself is generic, but we are setting a constraint CustomStringConvertible.</p><pre>enum Status&lt;T: CustomStringConvertible&gt;{ <br>    case success(T) <br>    case failed <br>} </pre><pre>extension Status{ <br>    var description: String{ <br>        switch self { <br>            case .success(let text): <br>              return text.description <br>            case .failed: <br>              return &quot;Failed....&quot; <br>         } <br>    } <br>} </pre><pre>Status.success(&quot;Good to go&quot;).description /&quot;Good to go&quot; Status.success(5).description // &quot;5&quot;</pre><h3>Error definition through enum</h3><p>On the Swift ecosystem enum are the best candidate for defining Error. The Error itself does not have any requirements. And this Error instance can be thrown by Swift error handling system.</p><p>Say we have an enum Mismatched</p><pre>enum Mismatched : String{ <br>    case notFound <br>    case undefined <br>    case invalid <br>}</pre><p>We can confirm the Error protocol to make Mismatched throwable.</p><pre>extension Mismatched: Error{}</pre><p>So our throwable function:</p><pre>func find(text: String?, on sentence: String?) throws { <br>    guard let text = text, text.count &gt; 0 else { <br>        throw Mismatched.undefined <br>    } </pre><pre>    guard let sentence = sentence, sentence.count &gt; 0 else { <br>        throw Mismatched.invalid <br>    } </pre><pre>    if !sentence.contains(text) { <br>        throw Mismatched.notFound <br>    } <br>}</pre><p>As we can see, if the target text is not set, then we will throw an undefined error. Similarly for the invalid sentence we will throw an invalid error. And finally notFound if not found.</p><pre>do { <br>    try find(text: nil, on: &quot;Some input&quot;) <br>} <br>catch Mismatched.undefined { <br>    Mismatched.undefined.rawValue <br>} //undefined </pre><pre>do { <br>    try find(text: &quot;any&quot;, on: nil) <br>} <br>catch Mismatched.invalid { <br>    Mismatched.invalid.rawValue <br>} //invalid</pre><p>Now for those two input we will get the corresponding error.</p><p>enum makes it much easier. 😊</p><p>For a far more details talk on Swift’s Error handling, we can always visit another swift enum advance talk, <a href="https://mobidevtalk.com/error-handling-through-try-variance/">Error handling through try variance</a>.</p><h3>Enum mutation, code smelling!!!</h3><p>The concept is very clear. enum is a value-based instance and it is been chosen by us for its immutability property. Thats mean always there will be only a single entity of that enum. If we need another instance of different value for that enum it has to be created. The previous was will not be modified.That&#39;s it, full-stop.</p><p>If we saw something other that, an enum is being modified, then we can be sure there is a code smelling.</p><p><strong>value types</strong>, such as enum, struct or tuple, are not used for mutation. If we need mutation then class is the way to go.</p><p>Now, how will we find an enum is being modified/mutated. Simple the instance method which mutate the enum will be prefixed with mutate keyword. Example coming through:</p><pre>enum State{ <br>    case notConnected <br>    case connecting <br>    case disconnected <br>    case connected(String) <br>    indirect case currentState(State) <br>} </pre><pre>extension State{ <br>    mutating func updateCurrentState(state: State) { <br>        self = .currentState(state) <br>    } <br>} </pre><pre>var state = State.connecting state.updateCurrentState(state: .connected(&quot;Oh ya&quot;))</pre><p>We will talk about the indirect just on the <a href="https://mobidevtalk.com/swift-enum-advance/#Recursive-enum">next section</a>. As we can see the updateCurrentState(state: State) modified the self or the enum instance.</p><p>We already talked about <a href="https://mobidevtalk.com/mutating-keyword-what-how/">mutating of value types, have a look</a>.</p><h3>Recursive enum</h3><p>The name suggest it all. Yes this type of enum is recursive, so they can call themselves. We express the recursive enum with the indirect keyword, placed either in front of case declaration or in front of enum declaration.</p><pre>indirect enum Buffer{ <br>    case data(String) <br>    case append(Buffer, Buffer, Buffer) }</pre><p>On the above we can see the append case will take three of its sibling Buffer case. Now we can write:</p><pre>let mobi = Buffer.data(&quot;Mobile&quot;) <br>let dev = Buffer.data(&quot;development&quot;) <br>let talk = Buffer.data(&quot;talk&quot;) <br>let mobiDevTalk = Buffer.append(mobi, dev, talk)</pre><p>The mobiDevTak takes three Buffer instance, mobi, dev and talk. Hmm ok no deal. But what to do with that. Lets convert the Buffer to String .</p><pre>extension Buffer{ <br>    func convert() -&gt; String { <br>        switch self { <br>            case .data(let text): <br>                return text <br>            case .append(let appendedBuffer): <br>                return appendedBuffer.0.convert() + &quot; &quot; +    appendedBuffer.1.convert() + &quot; &quot; + appendedBuffer.2.convert() <br>        } <br>    } <br>}</pre><p>As we can see for .data(let text) case we are just returning the String. But on the .append(let appendedBuffer)we are recursively calling convert()to get the full string. Just a note: Swift is smart enough to define appendedBuffer as Tuple 😉.</p><p>Now we can get the full string for append(Buffer, Buffer, Buffer).</p><pre>mobiDevTalk.convert() //&quot;Mobile development talk&quot;</pre><p>On the above we saw how to use recursive enum. Now the most important question should we use recursive enum? Well it may add some complexity to our code, but gives us the ability encapsulate the similar concerns. So it depends on the situation.</p><h3>allCases of CaseIterable</h3><p>We will found this feature of enum very useful when we need to do some common operation over all the case of that enum and definitely on the TDD, Test Driven Development, time. This feature was added on Swift 4.2 with Xcode 10.0+. Prior to allCases there was some weird ways to list all the cases of an enum.</p><p>As we can already understand, this feature will list all the cases of an enum. So an example please:</p><pre>enum Direction{ <br>    case north <br>    case south <br>    case east <br>    case west <br>} </pre><pre>extension Direction: CaseIterable{} </pre><pre>Direction.allCases //[north, south, east, west]</pre><p>Pretty simple. Now why do we write the CaseIterable on the extension of Direction. It is kind of a good practice to have separated implementation for different protocol. So what will happen if there is another protocol? Probably another extension. &quot;Separation of concerns&quot; or &quot;Single responsibility&quot; fits well with this type of extension based implementation of different concern aka protocol.</p><h4>At the end</h4><p>We talked about swift enum advance topic. But still a lot of things to talk about, they are not cover on this blog post, something like patterns matching needs separated blog series. And there are more. But we have to move on. On the next blog post we will go with the case study of Tic-tac-toe using enum. See you around.</p><p>The code used for this blog post can be found on <a href="https://github.com/mobidevtalk/enum/blob/master/Love%20for%20Enum%2C%20continuing.playground/Contents.swift">Github</a></p><p><em>Originally published at </em><a href="https://mobidevtalk.com/swift-enum-advance/"><em>https://mobidevtalk.com</em></a><em> on December 26, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36ec834de2e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/enum-advance-36ec834de2e1">Swift Enum Advance | mobidevtalk, Learning through case study</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift enum basic Introductory | mobidevtalk, Learning through case study]]></title>
            <link>https://medium.com/mobidevtalk/enum-introduction-b71d782c5a5a?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71d782c5a5a</guid>
            <category><![CDATA[mobidevtalk]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[enumeration]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Mon, 24 Dec 2018 18:51:29 GMT</pubDate>
            <atom:updated>2019-07-11T19:01:02.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_gO4GWYs8AfSRdSxqfg1g.jpeg" /><figcaption>Swift enum Basic introduction <a href="https://mobidevtalk.com/">mobidevtalk.com</a></figcaption></figure><p>In Swift enum holds a first class citizen badge. enum provides so many facilities on Swift that you have to book a special place for it. If we yet don’t feel that special affection for enum in Swift, I believe we will sooner or later. This blog series will direct us to fall in a love with enum. 🥰</p><h4>For a better experience of this blog post we can always visit the original Blog post on <a href="https://mobidevtalk.com/">mobidevtalk.com</a>.</h4><h3>Background</h3><ul><li><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#enum-look">enum as a first class citizen on </a><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#enum-look">Swift</a></li><li><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#other-collection-types">When to choose </a><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#other-collection-types">enum over other collection types</a></li><li><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#rawValue">rawValue</a></li><li><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#rawValue-of-custom-type">rawValue of custom type</a></li><li><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#associated-Values">associated Value</a></li><li><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#hashValue">hashValue</a></li><li><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#associated-Values-&amp;-rawValue">associatedValue &amp; </a><a href="https://mobidevtalk.com/swift-enum-basic-introduction/#associated-Values-&amp;-rawValue">rawValue</a></li></ul><h4>enum in a 😎 look</h4><p>enum or Enumerations are not some new concept. Other languages, including Objective-C, always have enum. On Swift, enum is a first class citizen. How? Because on Swift enum can have</p><ul><li>computed property. stored property is not allowed as enum is value-typed</li><li>instance method</li><li>additional initializer</li><li>extension</li><li>protocol extension</li></ul><h4>How enum differs from other collection types?</h4><ul><li><strong>Static elements</strong>: all the cases/elements of enum is defined on declaration time, which facilitate low memory footprint and type-safety.</li><li><strong>Named elements</strong>: all the cases/elements of enum are named. Provides the clarity.</li></ul><p>For simplicity if we have a collection of known options and at the end we need to choose only one among those options then enum is the preferred building block.</p><p>Btw we are intentionally dropping the definition part of enum because it&#39;s very obvious.</p><h4>Basic enum usage concepts</h4><p>When we will start using enum on a professional level, we will see a lot use of rawValue. So what is rawValue? We will have that answer, but to be more solid we need to find out from where the rawValue comes from. Well it comes from a behavioral type of protocol, RawRepresentable.</p><pre>enum Fractions: Float{<br>  case whole = 1 <br>  case half = 0.5 <br>  case quarter = 0.25 <br>} <br>Fractions.quarter.rawValue * Fractions.half.rawValue //0.125</pre><pre>enum Fractions: String{ <br>  case whole <br>  case half <br>  case quarter <br>} <br>Fractions.quarter.rawValue //&quot;quarter&quot;</pre><p>Interesting but what is happening on the background? Well on the background the following happens:</p><pre>enum Fractions{ <br>  case whole <br>  case half <br>  case quarter <br>}</pre><pre>extension Fractions : RawRepresentable{ <br>typealias RawValue = String </pre><pre>var rawValue: String{ <br>switch self { <br>  case .whole: <br>    return &quot;whole&quot; <br>  case .half: <br>    return &quot;half&quot; <br>  case .quarter: <br>    return &quot;quarter&quot; <br>  }<br>} </pre><pre>init?(rawValue: Fractions.RawValue) { <br>switch rawValue { <br>  case &quot;whole&quot; : <br>    self = .whole <br>  case &quot;half&quot; : <br>    self = .half <br>  case &quot;quarter&quot; : <br>    self = .quarter <br>  default: <br>    return nil <br>  } <br> } <br>} <br>Fractions.half.rawValue //&quot;half&quot;</pre><p>[Think we can infer the Int raw typed enum]</p><p>Now the obvious question what we need to do when we need a raw type for a enum that is not String Int or Float. Hmm simple and we know the answer. We need to confirms the RawRepresentable protocol for that enum using the custom/desire type as the RawValue. Example please...</p><p>So we will use the following struct, Rectangle, as the RawValue of RectFractions. We will implement the rawValue of custom type on RectFractions.</p><pre>struct Rectangle : Equatable{ <br>  let width: Float <br>  let height: Float <br>}</pre><p>Now why we confirms the Equatable here? Because later down the road we will need the <strong>comparison of</strong> <strong>value equality</strong> of Rectangle to construct the enum. Will be a lot clear on some mins.</p><p>Following is our enum</p><pre>enum RectFractions{ <br>  case whole <br>  case half <br>  case quarter <br>}</pre><p>Now let us confirm RawRepresentable for RectFractions.</p><pre>extension RectFractions: RawRepresentable{ <br>    typealias RawValue = Rectangle <br>    var rawValue: Rectangle{ <br>    switch self { <br>        case .whole: <br>            return Rectangle(width: 1, height: 1) <br>        case .half: <br>            return Rectangle(width: 0.5, height: 0.5) <br>       case .quarter: <br>            return Rectangle(width: 0.25, height: 0.25) <br>       } <br>    } </pre><pre>init?(rawValue: RectFractions.RawValue) { <br>    switch rawValue { <br>        case Rectangle(width: 1, height: 1) : <br>            self = .whole <br>        case Rectangle(width: 0.5, height: 0.5) : <br>            self = .half <br>        case Rectangle(width: 0.75, height: 0.75) : <br>            self = .quarter <br>        default: <br>            return nil <br>     } <br>  } <br>}</pre><p>On the very beginning we are declaring Rectangle as the typealias of RawValue. After that we are translating the enum to Rectangle value on var rawValue: Rectangle. And finally we are constructing the enum from Rectangle. Pretty straight forward, right? Now we can do the following:</p><pre>let halfRect = RectFractions.half.rawValue <br>halfRect.width //0.5 <br>halfRect.height //0.5 <br>RectFractions(rawValue: Rectangle(width: 0.75, <br>height: 0.75))//quarter</pre><h4>associated Values</h4><p>associated Value basically extends the corresponding case to have an extra value of an enum. Example will ease the concept.</p><p>Think about a login state of an app. The login state can have only two case, either logged in or logged out. Now we want to have the user name whenever a user is logged in. On this scenario associated value is the right option. So how we can define an associated value. Simply by defining the type just after the case.</p><pre>enum LoginState{ <br>case loggedOut <br>case loggedIn(String) <br>}</pre><p>Now how to get the user name of the logged in user. Let’s define userName.</p><pre>extension LoginState{ <br>var userName : String?{ <br>    switch self { <br>        case .loggedIn(let name): return name <br>        case .loggedOut: return nil <br>    }<br> } <br>}</pre><p>Now the next question is why we are defining the userName as computed property? Why not in the main body of the enum. Well that&#39;s a choice, we could have. There is no such strict rules what to do what not to do. The target was separation of concern. userName is not a case of LoginState. And also userName will be calculated after all the cases of LoginState are defined. So it makes no sense to define userName as stored property on the main body.</p><p>So finally we can get the user name.</p><pre>let state = LoginState.loggedIn(&quot;mobiDevTalk&quot;) <br>state.userName //mobiDevTalk</pre><h4>hashValue</h4><p>Prior to Swift 4.2 hashValue for enum was like 1 ,2 or 3. But now it is not like that and rightfully so. How?</p><p>Because hashValue comes from</p><p>The very first obvious question is what is hashValue?</p><p>hashValue can be think of a unique identifier to identify an element among same typed elements.</p><p>A very regular use of hashValue is the git commit hash, which is different from any other commits. A hash will indicate only a single git commit.</p><pre>enum Suits{ <br>    case clubs <br>    case diamonds <br>    case hearts <br>    case spades <br>} <br>Suits.clubs.hashValue //8039695594957265170</pre><p>Wait this is not that much smooth. The hash value we are seeing will not be same for the next run 😕. <a href="https://developer.apple.com/documentation/swift/hashable/1540917-hashvalue">Apple docs</a> says not to save hashValue for future execution.</p><p>hashValue itself has a lot of ground to cover. But for enum the hashValue has lost its usage. Previous on the earlier versions of Swift, prior to Swift 4.2, hashValue would act like an Int raw Valued enum. So someEnum.someCase.hashValue would return some Int number like 1, 2 etc. But those days are long gone. It will be an obvious choice not to use hashValue depended operations on enum. Be safe. ⛑</p><h4>associated Values vs rawValue</h4><pre>enum ErrorCode : String{ <br>    case https(Int) <br>//Enum with raw type cannot have cases with arguments case generic <br>}</pre><p>What happens here? Why this error.</p><p>We are saying, the ErrorCode has a rawValue of String. Thats mean each of the case will have a String type value. But on the case https(Int)we don&#39;t have any specific representation of Int type, right? It can be 1, can be 100 who knows! So we can&#39;t have an associated value on a raw-typed enum. But wait can we have the other way? What do you think? Do read on...</p><h4>associated Values &amp; rawValue</h4><p>We can have an enum with associated value and later on we can confirm the RawRepresentable to set our desire type. Better explained with example</p><p>Let us assume we have a enum of department like following:</p><pre>enum Department: String{ <br>    case manufacturing <br>    case rnd <br>    case marketing <br>}</pre><pre>enum Hierarchy{ <br>    case chairman <br>    case ceo <br>    case manager(Department) <br>}</pre><p>So now we need to have a rawValue of String. For that we need to confirms RawRepresentable and implement the var rawValue and init?(rawValue: RawValue).</p><pre>extension Hierarchy: RawRepresentable{ <br>    var rawValue: String{ <br>        switch self { <br>            case .chairman: return &quot;Chairman&quot; <br>            case .ceo: return &quot;CEO&quot; <br>            case .manager(let department): <br>                return &quot;\(department.rawValue.capitalized) Manager&quot; <br>        }<br>} </pre><pre>init?(rawValue: RawValue) { <br>    switch rawValue { <br>        case &quot;Chairman&quot;: self = .chairman <br>        case &quot;CEO&quot;: self = .ceo <br>        default: <br>            let splitted = rawValue.split(separator: &quot; &quot;) <br>            if let deptVal = splitted.first, <br>               let department = Department(<br>                 rawValue:String(deptVal)), <br>               splitted.last == &quot;Manager&quot; { <br>                   self = .manager(department) <br>               }else{ return nil } <br>       } <br>  } <br>}</pre><h4>End, nope not yet</h4><p>We have talked a lot. But for being a pro on enum can&#39;t be gain in a single blog post. So stay tuned. We will be back on our <a href="https://mobidevtalk.com/love-for-enum-continuing/">Continue blog post</a>.Till then happy talk. 😌</p><p>Source code for this blog post is shared on <a href="https://github.com/mobidevtalk/enum/tree/master/LoveForEnum.playground">Github</a></p><p><em>Originally published at </em><a href="https://mobidevtalk.com/swift-enum-basic-introduction/"><em>https://mobidevtalk.com</em></a><em> on December 24, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71d782c5a5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/enum-introduction-b71d782c5a5a">Swift enum basic Introductory | mobidevtalk, Learning through case study</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Date Formatter | mobidevtalk, Learning through case study]]></title>
            <link>https://medium.com/mobidevtalk/swift-date-formatter-mobidevtalk-learning-through-case-study-5e54c506ab8?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e54c506ab8</guid>
            <category><![CDATA[dateformatter]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Fri, 02 Nov 2018 16:29:16 GMT</pubDate>
            <atom:updated>2019-06-01T08:12:06.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFvU6K8eWR1Fw21p8AOo9w.png" /></figure><p>How dashing you look; is the key factor when you have Date[s] 😜. Same goes with our Date also when we are in the Swift arena. Although dashing may not be the proper term, rather presenting thyself is more appropriate. DateFormatter comes into play on this occasion. Swift Date formatter is one of the confusing item that we pass by regularly. At the end of this blog post we will make ourself dashing when it comes to Swift Date formatter 😎.</p><h4>Background:</h4><ul><li><a href="https://mobidevtalk.com/swift-date-formatter/#date-formatter">What type of formatter are you, </a><a href="https://mobidevtalk.com/swift-date-formatter/#date-formatter">DateFormatter?</a></li><li><a href="https://mobidevtalk.com/swift-date-formatter/#pre-date-formatter">Preparation of using </a><a href="https://mobidevtalk.com/swift-date-formatter/#pre-date-formatter">DateFormatter.</a></li><li><a href="https://mobidevtalk.com/swift-date-formatter/#such-as">Example, Example…. want it now !!!!</a></li><li><a href="https://mobidevtalk.com/swift-date-formatter/#pictorial-view">Graphical representation of </a><a href="https://mobidevtalk.com/swift-date-formatter/#pictorial-view">DateFormatter.</a></li><li><a href="https://mobidevtalk.com/swift-date-formatter/#homie">DateFormatter says: “Do you mind, homie”?</a></li><li><a href="https://mobidevtalk.com/swift-date-formatter/#format-style">Defining Skeleton of </a><a href="https://mobidevtalk.com/swift-date-formatter/#format-style">DateFormatter</a></li></ul><h3>DateFormatter</h3><p>As we can guess from the <strong>formatter</strong> keyword of DateFormatter, that it formats the Date into some representing way and that way is textual representation. It turns out that we can also construct Date from a textual representation also. So basically DateFormatter is the converter of Date and textual representation.</p><p>We already talked in details on Date on <a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/">our love or hate talk</a> 😉. Free fell to pay a visit.</p><h3>Pre talk of DateFormatter()</h3><p>We have to set the following two, after initializing and before using DateFormatter.</p><ol><li>set the locale for the DateFormatter. If not set, then it will use the system provided locale.</li><li>set the format style. Now there is two way to do this.</li></ol><ul><li>By setting the dateFormat property.</li><li>Or by setting the dateStyle and/or timeStyle. One or both need to be set based on the provided input.</li></ul><h3>Such as:</h3><p>On the following code we will format some random date.</p><pre>let date = Date(timeIntervalSinceReferenceDate: 60*60*60*24*30*3.5) //&quot;Apr 2, 2018 at 6:00 AM&quot; <br>let formatter = DateFormatter() <br>formatter.locale = Locale(identifier: &quot;BD&quot;) // BD stands for Bangladesh <br>formatter.dateStyle = .medium <br>formatter.timeStyle = .medium <br>formatter.string(from: date) <br>formatter.date(from: &quot;Apr 2, 2018 at 6:00:00 AM&quot;)</pre><p>We can always visit the <a href="https://mobidevtalk.com/dates-love-or-hate-it-you-just-cant-ignore-it/">First blog post</a> to read more about ReferenceDate.</p><h3>Pictorial view</h3><p>If we want have a pictorial view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*phnQ1WF1f2BK9Gwf" /></figure><p>Pretty self explanatory. Though last two methods need some attention. .string(from:) converts Date to String, on the other hand date(from:) converts String to Date.<br>And also date(from:) returns an optional Date, Date?.</p><h3>yo homie</h3><p>Localization is a must have for DateFormatter. Because without knowing the locale the formatter can not represent the Date on String or make a Date from String formatted date.</p><p>In a nutshell: Local is basically a structure; which provides necessary formatters and symbols, those are define for a specific Locale. Example $ is the currency code on USA and for UK it is £. On Sweden it is common to have , as a decimal separator <strong>example 123,23</strong> where on Asia it is . <strong>example 123.23</strong>. Local provides us all those and also many others. May be on some future post we will have some more talk on Locale.</p><p>Now back to our Localization discussion on Date: So on worst case scenario we did not set the locale for our DateFormatter, as a result the DateFormatter will use the system-provided-locale.</p><p>And we can imagine the consequences: In some distinct future there is a <strong>probable</strong> <strong>Date related bug</strong> which <strong>happens to some user</strong>; if lucky we know that it is a group of people having this bug. Too difficult to find out among such possibilities.<br>OH Come on, we are better than this. We always know, how our program gonna behave. We don&#39;t let other programs to do some uninvited operation on our own program; thats become a guess based bug for us.</p><h3>Always set the locale just after DateFormatter initialization and must be before using that DateFormatter. Setting the locale should be the very second line of our DateFormatter task.</h3><h3>dateFormat vs dateStyle with/without timeStyle</h3><p>To retrieve or relinquish Date, we need to have a skeleton based on which we can get and set the date. <br>There are two ways to achieve this.</p><ul><li>One was is to respect the locale and set the formatter style by defining dateStyle and/or timeStyle.</li><li>Another way is to use a fixed format irrespective of locale.</li></ul><p>For the next section discussion, I am confident that we already set the local for our Date instance. 🧐</p><p>Let’s talk about the first option first.</p><h3>dateStyle and timeStyle</h3><p>Example is the best way to start. You can find the date format by countries on <a href="https://en.wikipedia.org/wiki/Date_format_by_country">wikipedia</a>. What does this list means? It means, a specific country follows a/multiple fixed format for Date. Let’s pick Iceland and Panama, as our example. We can list the following:</p><p>Now dateStyle and timeStyle both are enum. Having values like none, short, medium, long, full.<br>So after setting the corresponding locale, Iceland or Panama, if we set the dateStyle according to the value such as short long then we should be able to represent the Date into String and vice versa using our dateFormatter.</p><pre>let date = Date(timeIntervalSinceReferenceDate: 60*60*60*24*30*3.5) let icelandFormatter = DateFormatter() <br>icelandFormatter.locale = Locale(identifier: &quot;IS&quot;) // IS stands for Iceland <br>icelandFormatter.dateStyle = .short <br>let stringDate = icelandFormatter.string(from: date) // &quot;2.4.2018&quot; let formattedDate = icelandFormatter.date(from: &quot;5.11.2018&quot;) //&quot;Nov 5, 2018 at 12:00 AM&quot;</pre><p>We are skipping the TimeStyle here.</p><p>Now the good thing about using the dateStyle is: the end user is happy, because he/she is seeing the comfortable date presentation. The user need not to look for another round to figure out the date.</p><h3>dateFormatter</h3><p>But the happy story will not be same for all the requirements. In some times we need to have a fixed format of date regardless on the user Locale. In this case we have to use the fixed-date-formatter, dateFormatter.</p><p>For dateFormatter we will use a fixed String , EEEE, MMM d, yyyy, for identifying the date-string. EEEE stands for day name. There is the <a href="https://mobidevtalk.com/swift-date-formatter/#ref">ref section</a> at the bottom if we need some help with the symbolic representation of Date component.</p><pre>let date = Date(timeIntervalSinceReferenceDate: 60*60*60*24*30*3.5) let formatter = DateFormatter() <br>formatter.locale = Locale(identifier: &quot;BD&quot;) <br>formatter.dateFormat = &quot;EEEE, MMM d, yyyy&quot; <br>formatter.string(from: date) // &quot;Monday, Apr 2, 2018&quot; formatter.date(from: &quot;5.11.2018&quot;) // nil</pre><p>Just small note: as the 5.11.2018 does not have a format of EEEE, MMM d, yyyy, thus calling the formatter.date(from: &quot;5.11.2018&quot;) yields nil.</p><h3>When to use which one</h3><p>The choice among dateFormat and dateStyle is actually based on requirement.</p><ul><li>When the requirement is to have the user preferred way or respecting the user locale then we must use dateStyle.</li><li>On the other hand if the requirement is some fixed format irrespective of user’s locale, then we have no other choice but to use the dateFormat.</li><li>Another case we have to consider, when the format is locale to a group of people and also the format is fixed then again we have to use dateFormat.</li></ul><p>So on the next time we gonna work with date, we have to ask the question of, will we support the locale for date? If not then what is the fixed format of date?</p><p>Also keep in mind that, probably we will always need multiple DateFormatter for our apps, so be prepared for that. Also DateFormatter are expensive to create, so we will try to reuse them as much as we can.</p><h3>Conclusion</h3><p>So here we are at the end of Swift Date formatter talk. This blog post comes to an end of our Date talk on Swift. Inshallah In recent future we will have another case study based talk where we will implement our knowledge on Swift Date and Swift Date formatter. Till then be dashed with your Date[s] 🤓.</p><h3>References for future</h3><ul><li><a href="http://nsdateformatter.com/">Online Date Formatter for iOS</a></li><li><a href="https://countrycode.org/">ISO country codes</a></li><li><a href="https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.admin.nls.doc/doc/r0004572.html">Date formats based on country</a></li></ul><p><em>Originally published at </em><a href="https://mobidevtalk.com/swift-date-formatter/"><em>https://mobidevtalk.com</em></a><em> on November 2, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e54c506ab8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/swift-date-formatter-mobidevtalk-learning-through-case-study-5e54c506ab8">Swift Date Formatter | mobidevtalk, Learning through case study</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Dates Love or Hate it, you just can’t ignore it | @mobidevtalk]]></title>
            <link>https://medium.com/mobidevtalk/swift-dates-love-or-hate-it-you-just-cant-ignore-it-mobidevtalk-a48f84fe329a?source=rss-9437ba03af17------2</link>
            <guid isPermaLink="false">https://medium.com/p/a48f84fe329a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[date]]></category>
            <dc:creator><![CDATA[SHAD MZUMDER]]></dc:creator>
            <pubDate>Sun, 28 Oct 2018 17:55:20 GMT</pubDate>
            <atom:updated>2019-05-19T00:45:06.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oo-mC9HhQtrkrplqBUcow.jpeg" /></figure><p>At some point of our career we say it <strong>Enough</strong> !!! We say it loudly, no more evading from <strong>Date</strong>. Prior to this understanding; we used to find some cunning corners to keep our some hours study for later time and embrace some SO, stackoverflow, answers that just do the work we wanted. Right or Wrong, we don’t judge it. It’s a solution that gonna work.And ya…, the rest is mostly common for all of us. We fall hard and realize: we need talk some more details on Date. Love it or Hate it, doesn’t matter Dates gonna bite you if you are not prepared, so Let us have some introductory talk on Date[s] through some Swift code.</p><h3>Background</h3><ul><li>I create a fresh Date instance, Date(), but wait <a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/#date-naming">Why Date is not date only, why time is also present on the Date !!!</a></li><li><a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/#independency-of-date">Independency of Date</a></li><li><a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/#date-interval">Date Interval</a></li><li><a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/#time-interval">Time Interval</a></li><li><a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/#localization-Date">Localization of Date</a></li><li><a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/#calendar">Calendar</a></li></ul><h3>Date</h3><p>We can always find the necessary docs on the <a href="https://developer.apple.com/documentation/foundation/date">Apple doc over Date</a>. Feel free to revisit. But for now let’s drive deep 🏊 on our Swift Dates introductory talk, you gonna love it or hate it? Let’s see.</p><p>By definition Date is the type that represents Time on Foundation framework. Hmmm a bit confusing, date represents time.</p><p>So on a regular conversation if we say, which date it is? One will answer something like 25 October, 2018. And if we ask, what time it is? The answer will be 10 am or similar. What about Day? Answer, Thursday.</p><p>But when we talk about Date on <strong>Swift</strong>; be prepare to include all those components, that we just talked about.</p><p>Perhaps Time will be more appropriate name, as Time is a more core concepts even for date also.</p><p>Wait, thats not actually the end of a confused discussion. Date has more insights to make us even more puzzled about its <strong>Name</strong>.</p><p>Date <strong>value</strong> basically represents a <strong>time interval</strong> from an absolute reference date. WTH!!! And what does it means. Lets talk...</p><p>So the typical <strong>reference date</strong> is 00:00:00 UTC on 1 January 2001, it can also be 00:00:00 UTC on 1 January 1970 or even the ref date we want.</p><p>When we initialize an Date instance, the value of that instance actually tells us the difference/interval from that ref date. So hence Date is the <strong>timer interval</strong> from an absolute ref date. <br><em>Just a small note:</em> reference date <em>is not a Swift</em> Date, <em>its our regular date</em>.</p><p>So are we thinking that, TimeInterval cloud be a more appropriate Name? Nope can&#39;t be. TimeInterval is a typealias of Double.</p><p>You know what, it doesn’t matter anymore. At some point of our career we will eventually figure this out.</p><p>We just need to understand the base idea, despite the <strong>Name</strong> as Date, Date is actually a difference based value from a reference.</p><p>So lets move on…</p><p>The interesting part about Date is, it is not dependent on time-zone or any Calendrical system. As Date instance is a time-interval from a reference-point, if we transform the reference-point to another system then the Date instance will automatically converted to the new system.</p><pre>let defaultRefDate = Date(timeIntervalSinceReferenceDate: 120)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*gXs9go4s8nUh70hl" /></figure><p>Here the defaultRefDate is 120 Unit/seconds, represented as Double, right to the ref-point 0.</p><p><strong>Note:</strong> Seconds has only the fixed duration, thats why it is used as the Unit for Date. Month can be 28/29/30/31, years can have 52 weeks + 1/2 days, and don&#39;t forget days have to handle the daylight-saving-time.</p><p>Moving back to our Date independency talking: if someone has a local of Arabic, Ar, then he will see something like: ٠١‏/٠١‏/٢٠٠١، ٦:٠٢ ص<br>but on someone who has an English local will see it as Jan 1, 2001 at 6:02 AM on their respective Xcode&#39;s playground view.</p><p>What happens here is that, Playground prints the defaultRefDate base on the user&#39;s locale. It has no connection with Date instance. Similarly we can convert the date to another calendar or format. We will see those in the upcoming talk.</p><h3>Date Interval</h3><p>Date Interval is the time-frame/timeline between two Date instance. It is a close boundary interval.</p><h3>Time Interval</h3><p>Time Interval is a representative type of seconds, unit of time. It is a typealias of Double.</p><h3>Date Localizing</h3><p>On different community/zone date are represented on different way. Some has day first, some has year first when printing a date. Sometimes Full month name is required, sometimes the regular three letters format of month-name is accepted. <br>Another major concern is the Month name. On Spain it is marzo for March. Do we want to go with Japanese or Chinese. Think its enough. 😛</p><p>So how we gonna support different locale for our dates. The good think is its already provided by the system. We just need to set the local and thats it.</p><p>We will talk in more details on the next blog post, Format your Date[s].</p><h3>Calendar</h3><p>So Date is an absolute points in time. Calendar makes it possible for a Date instance to be operated on different Calendrical Unit, day weekday year etc, with Calendrical systems; example Gregorian or Islamic calendar.</p><p>In other words Calendar provides the calculation and comparison of Dates on different Calendrical system.</p><p>Calendar handles the things like leap-year, daylight saving and any other things that are related with a Calendar.</p><h3>Conclusion:</h3><p>This blog post may seems to be end. But behold its not. There is one more major part we need to learn and its the <a href="https://mobidevtalk.com/format-your-dates/">DateFormatter</a>, which is our next blog post. So the Swift Dates, Love or Hate, still continues 😉.</p><p>After the DateFormatter talk we will again start some Q/A to make sure we understand the whole flow for Dates and its related concepts.</p><p>Till then Happy Talking. 🤓</p><p><em>Originally published at </em><a href="https://mobidevtalk.com/swift-dates-love-or-hate-it-you-just-cant-ignore-it/"><em>https://mobidevtalk.com</em></a><em> on October 28, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a48f84fe329a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobidevtalk/swift-dates-love-or-hate-it-you-just-cant-ignore-it-mobidevtalk-a48f84fe329a">Swift Dates Love or Hate it, you just can’t ignore it | @mobidevtalk</a> was originally published in <a href="https://medium.com/mobidevtalk">mobidevtalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>