<?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 Tommy Bajis on Medium]]></title>
        <description><![CDATA[Stories by Tommy Bajis on Medium]]></description>
        <link>https://medium.com/@tommybajis?source=rss-3b9821a0a779------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_B8Y7c0YBnwbA_NQ.</url>
            <title>Stories by Tommy Bajis on Medium</title>
            <link>https://medium.com/@tommybajis?source=rss-3b9821a0a779------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:48:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tommybajis/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[Just My Type! — Custom Types and Error Handling in Swift]]></title>
            <link>https://medium.com/@tommybajis/just-my-type-custom-types-and-error-handling-in-swift-7f16ea0b3aa0?source=rss-3b9821a0a779------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f16ea0b3aa0</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Tommy Bajis]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 02:16:12 GMT</pubDate>
            <atom:updated>2017-10-10T02:22:42.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*xUW4T5-85reXZyHm_xDNvQ.png" /></figure><h3>The First Error</h3><p>Before you sit down to code, it’s important to address the first error you’ll need to handle, not try-ing.</p><p>Reading documentation or taking the time to learn about error handling isn’t exactly most people’s idea of a fun time. It definitely wasn’t for me, at first. However, after exploring some tutorials and contemporary literature on the subject, I’ve found a certain appreciation in constructing custom types to deal with errors.</p><h3>Functional Swift — A Fantastic Resource</h3><p>Whether you’re a tenured Swift Developer, or someone just getting started, chances are that you’ve heard about <em>Functional Programming</em>.</p><p><a href="https://www.objc.io/books/functional-swift/">Functional Swift</a> is a fantastic resource and introduction into <em>Functional Programming </em>in Swift. While this resource highlights many great topics, I found the sections on <strong>Enumerations </strong>and <strong>Swift Errors</strong> to be particularly useful in my projects. This post will take you through some examples inspired from those sections.</p><p>The examples below are available in a <a href="https://github.com/tbajis/Demos/tree/master/JustMyType">playground</a> in my <a href="https://github.com/tbajis/Demos">Demos Repository</a>. Feel free to clone or download the repo and follow along!</p><h3>The Problem</h3><p>I’m sure that we’ve all written methods to check for certain values in <em>arrays </em>or <em>dictionaries</em>. These container types are a part of the <em>Swift Standard Library </em>and are integral to iOS Development. In the examples that follow, we’ll refine a method that retrieves the number of team members using only an individual’s memberName. However, getting the number of team members requires looking up the team first. A reasonable approach to constructing this method might look like this:</p><p><em>Using an Optional Return Type</em></p><pre>func numberOfTeamMembers(memberName: String) -&gt; Int? {</pre><pre>   guard let team = teamNames[memberName] else { return nil }<br>   guard let number = teamMembers[team] else { return nil }</pre><pre>   return number<br>}</pre><p>We could then call this method in our code like so:</p><p>let someLookup = numberOfTeamMembers(memberName: &quot;Tommy&quot;)</p><p>Not bad, right? Our numberOfTeamMembers(memberName:) method will return an optional Int? if the lookup is successful. Otherwise, in the event that one of the checks fail, someLookup will contain nil. While this may seem like a reasonable approach to solving our problem, we know nothing about why a lookup could fail. In other words, should the method above return nil, we don’t have any information as to which of the checks did not pass. For more complex methods, this could pose a problem when tracking down the source of a lookup error.</p><h3>A Solution: Enter Enumerations</h3><p>One of the shortcomings of the numberOfTeamMembers(memberName:) method lies in its return type Int?. What if we could create our own return type? Specifically, a type that could return an Int if the lookup is successful and return a detailed error if it fails. To do so, we could try something like this:</p><pre>enum LookupError: Error {<br>   case teamMemberNotFound<br>   case numberOfMembersNotFound<br>}</pre><pre>enum LookupResult {<br>   case success(Int)<br>   case failure(LookupError)<br>}</pre><p>Here we’ve created a custom return type, LookupResult, that contains two enumeration cases, success(Int) and failure(LookupError). A success case will be associated with an Int and a failure will be associated with a LookupError. Note that LookupError contains two enumeration cases, teamMemberNotFound and numberOfMembersNotFound. These cases just happen to represent the two checks that could fail in our previous method! Now we could re-write our method like so:</p><pre>func numberOfTeamMembers2(memberName: String) -&gt; LookupResult {<br>   guard let team = teamNames[memberName] else {<br>      return .failure(.teamMemberNotFound)<br>   }<br>   guard let number = teamMembers[team] else {<br>      return .failure(.numberOfMembersNotFound)<br>   }</pre><pre>   return .success(number)<br>}</pre><p>Similarly, we could call this method like this:</p><p>let newLookup = numberOfTeamMembers2(memberName: &quot;Dan&quot;)</p><p>Now newLookup will contain an Int in the case of a successful lookup and a LookupError in the case of failure. While we had to apply a little more overhead to get this result, it demonstrates how beneficial custom types can be when needing to handle errors in our projects. Although, if we wanted to, we could take this example one step further.</p><h3>One Step Further: Enter Generics</h3><p>While the previous example did help solve our problem, it could be improved upon. Ideally, we’d like our LookupResult type to be more generalized so that it can be used for different tasks. Basically, we’d like to not have to create a new result type for each method or problem that we solve in our projects.</p><p>To apply <em>Generics</em> to our previous example, we could create a new result type and a new generalized look up method like so:</p><pre>enum NewResult&lt;T, SomeError: Error&gt; {<br>   case success(T)<br>   case failure(SomeError)<br>}</pre><pre>func newLookup(memberName: String) -&gt; NewResult&lt;Int, LookupError&gt; {<br>   guard let team = teamNames[memberName] else {<br>      return .failure(.teamMemberNotFound)<br>   }<br>   guard let number = teamMembers[team] else {<br>      return .failure(.numberOfMembersNotFound)<br>   }<br>}</pre><p>The NewResult&lt;T, SomeError: Error&gt; type can be used to return any generic type T on success and any SomeError on failure (so long as SomeError conforms to the Error protocol). The precision of this generic return type allows us to take advantage of Swift’s type checking and can prevent bugs before your project has been tested. We could even switch on the result of the method we wrote above for clarity.</p><pre>let teamMembersResult = newLookup(memberName: &quot;Samantha&quot;)</pre><pre>switch teamMembersResult {<br>   case .success(let number):<br>      // TODO: handle success flow here<br>   case .failure(let error):<br>      // TODO: handle error flow here</pre><pre>}</pre><h3>In Conclusion</h3><p>The purpose of using the result type above is not to completely replace the implementation of optionals in our projects. After all, we did have to define custom enumerations to solve what was a relatively simple problem. In addition, interfaces that consistently favor custom types over existing types will be less familiar to the occasional contributor.</p><p>However, using the NewResult&lt;T, SomeError: Error&gt; type is a great way to handle errors in Swift. Using enumeration cases helped us define types that were specific to the problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f16ea0b3aa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>