<?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 Toby O&#39;Connell on Medium]]></title>
        <description><![CDATA[Stories by Toby O&#39;Connell on Medium]]></description>
        <link>https://medium.com/@oconnelltoby?source=rss-96f3bc4104e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HEZHi_StQUNgGG3f</url>
            <title>Stories by Toby O&amp;#39;Connell on Medium</title>
            <link>https://medium.com/@oconnelltoby?source=rss-96f3bc4104e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 13 Jul 2026 09:30:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oconnelltoby/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[Swift enums and the danger of the default case]]></title>
            <link>https://oconnelltoby.medium.com/swift-enums-and-the-danger-of-the-default-case-625a0830f57a?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/625a0830f57a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 20:41:34 GMT</pubDate>
            <atom:updated>2024-02-15T20:41:34.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*r9oGH-Kg1lj9ugy00Hlsbw.png" /><figcaption>It’s a trap!</figcaption></figure><h3>Context</h3><p>A lot of the time in Swift we will use enums to define bits of state within an app. The beauty of enums is that they represent a complete set of possible options. As such, when switching on an enum we can guarantee that every possible option is accounted for.</p><p>One issue I see occasionally is abusing the default case. Consider the following example:</p><pre>enum Style {<br>    case small<br>    case big<br>}<br><br>func size(for style: Style) -&gt; CGFloat {<br>    switch style {<br>    case .small:<br>        8<br>    default:<br>        16<br>    }<br>}</pre><p>On the surface this seems perfectly reasonable, but imagine a new developer is tasked with adding a third style - medium. Unless that dev already knows about the size(for:) function, the app will start behaving incorrectly… <em>silently…</em></p><pre>enum Style {<br>    case small<br>    case medium<br>    case big<br>}<br><br>func size(for style: Style) -&gt; CGFloat {<br>    switch style {<br>    case .small:<br>        8<br>    default: // Uh oh!<br>        16<br>    }<br>}</pre><p>The solution to this particular example is simple. If we explicitly list all the enum cases, when medium is added, the compiler will prompt let us know that the switch must be exhaustive and that we’ve not handled medium.</p><pre>enum Style {<br>    case small<br>    case medium<br>    case big<br>}<br><br>func size(for style: Style) -&gt; CGFloat {<br>    switch style {<br>    case .small:<br>        8<br>    case .medium: <br>        12<br>    case .big:<br>        16<br>    }<br>}</pre><h3>Conclusion</h3><p>Obviously the example presented is contrived but the concept is worth applying whenever you are about to use a default case.</p><p>The power of enums is in their completeness, so don’t throw that away with a default case unless you’re sure that’s what you want!</p><p>And as a rule of thumb:</p><blockquote>Never lay traps for future devs</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=625a0830f57a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why structs are better than protocols for dependency inversion]]></title>
            <link>https://medium.com/codex/why-structs-are-better-than-protocols-for-dependency-inversion-55f1ec3ef777?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/55f1ec3ef777</guid>
            <category><![CDATA[structure]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 17:20:54 GMT</pubDate>
            <atom:updated>2024-02-29T17:59:13.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*ofTWt4K4-J3fMpOnnLV9LQ.jpeg" /></figure><h3>When structs are better than protocols for dependency inversion</h3><p>When we think of dependency inversion in Swift, protocols are usually the first thing that come to mind. The well known pattern is to create a protocol that defines some required behaviour and create a concrete implementation that performs that responsibility.</p><p>This becomes invaluable when testing our code as we can substitute dependencies for mocked versions which can be primed with desired responses and queried for expected outcomes.</p><p>Whilst this pattern is perfectly adequate in most instances, structs can often provide advantages that protocols can not.</p><h3>Where protocols fall down…</h3><h4><strong>Name-spacing</strong></h4><p>Once major disadvantage of protocols is that they cannot nest other types. Imagine the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0217fde0291c44aa06f3a915083d9c65/href">https://medium.com/media/0217fde0291c44aa06f3a915083d9c65/href</a></iframe><p>If we tried to define a protocol for our House, we would also need to define a protocol for the Inhabitant too, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bf04c15d1d04c828e2165aa58769837/href">https://medium.com/media/8bf04c15d1d04c828e2165aa58769837/href</a></iframe><p>Annoying, the Inhabiting protocol cannot be nested inside Housing, so it pollutes the global namespace. Over time, this can cause conflicts and cashes, especially in large codebases.</p><h4><strong>Heterogenous Arrays</strong></h4><p>Suppose our consuming type required an array of houses. With the following snippet we run into the infamous Protocol ‘Housing’ can only be used as a generic constraint because it has Self or associated type requirements error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d129f4597d084946699b34ed2472b6dd/href">https://medium.com/media/d129f4597d084946699b34ed2472b6dd/href</a></iframe><p>Here we have 2 options. The first is to make Street generic, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c454bc51d11251a9c3cb755357843b20/href">https://medium.com/media/c454bc51d11251a9c3cb755357843b20/href</a></iframe><p>The problem here, however, is that now we are tied to one particular type of Housing. On our Street we might have multiple types of house like Bungalows and Mansions so this might not always be what we want.</p><p>The other solution is to create a type-erasing wrapper in a similar way to how AnyHashable or AnyPublisher work. Here we could create the type-erased AnyHousing, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/972c0d9081fb55f21934cee65597bb7b/href">https://medium.com/media/972c0d9081fb55f21934cee65597bb7b/href</a></iframe><p>But oh no! Here we can see that we’ve tied ourselves to one specific type of Inhabitant per house! To fully implement the type erase we need an AnyInhabiting type too. The final result is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f93d1cfb2b6ff041bfc8cef306fc0dd/href">https://medium.com/media/2f93d1cfb2b6ff041bfc8cef306fc0dd/href</a></iframe><p>That’s pretty verbose and if we look closely, the implementations of AnyInhabiting and AnyHousing are suspiciously similar to the Inhabitant and House we started off with!</p><h3>The trick to using structs…</h3><p>The answer to how we can use structs to perform the same function as protocols is by keeping them simple! We can write the struct in such a way that it holds only the data and functionality required by the consuming type. Instead of conforming to a protocol we can write an adaptor to map any object to our struct.</p><p>Suppose following ViewModel. It allows us to define the text and buttonTapped functionality upon initialisation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0af4b8ffd19f959d961dd3ee84e66fe7/href">https://medium.com/media/0af4b8ffd19f959d961dd3ee84e66fe7/href</a></iframe><p>We can now add a convenience initialiser in an extension to map from the services we need to call upon.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774c4b8367e62fd88435cebab875e9cc/href">https://medium.com/media/774c4b8367e62fd88435cebab875e9cc/href</a></iframe><p>When it comes to testing our UI layer, there is no need to create an object and conform to a protocol. We can simply provide test functionality and text upon initialisation.</p><h3>Conclusion</h3><p>We’ve now seen an alternative to protocols that performs the same function, maintains the same level of testability and simplifies verbose boilerplate code. Seems too good to be true right?</p><p>The one caveat I have seen is that some discipline needs to be applied to the initial struct in keeping it as a data-only object (Kotlin style data-classes would be ideal here).</p><p>I find this pattern cleaner and less verbose in most cases when compared to protocols, so it continues to be something I use in my daily work</p><p>For completeness, <a href="https://gist.github.com/oconnelltoby/af160f5efe7b00c5d33887be280d2855">here is a gist</a> which continues the House example in the same way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55f1ec3ef777" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/why-structs-are-better-than-protocols-for-dependency-inversion-55f1ec3ef777">Why structs are better than protocols for dependency inversion</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The importance of logical data modelling]]></title>
            <link>https://medium.com/codex/the-importance-of-logical-data-modelling-c9686ccf4f1?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9686ccf4f1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[crash]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 21:27:04 GMT</pubDate>
            <atom:updated>2022-04-19T01:15:57.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*WU2RwxQKUsBqIjoDHEKlpA.jpeg" /><figcaption>struct 💥 / enum ❤️</figcaption></figure><p>As an iOS developer, I am forever shocked at how often I see fatalError(“This should never happen”) in production code. This usually arises in situations where an edge case is programatically possible, but logically impossible.</p><h3>The scenario</h3><p>Imagine a situation where I’d like an app to catalog the CDs and books on my bedroom shelf. I create an Item struct which tells me the title, and has optional fields for duration and the number of pages depending on if it’s modelling a CD or book.</p><pre>struct Item {<br>    var title: String<br>    var duration: TimeInterval?<br>    var numberOfPages: Int?<br>}</pre><p>This struct leaves me with a problem though. I am able to create an Item with both a duration <em>and</em> a numberOfPages. I am also able to create an Item which has neither field!</p><p>When I try to present my Items as rows in a table, the issue becomes apparent:</p><pre>func makeRow(for item: Item) -&gt; Row {<br>    if let duration = item.duration {<br>        return Row(heading: title, subHeading: duration)<br>    } else if let numberOfPages = item.numberOfPages {<br>        return Row(heading: title, subHeading: numberOfPages)<br>    } else {<br>        fatalError(“This should never happen”)<br>    }<br>}</pre><p>Despite the error message, the fatalError <em>could</em> happen. For my app to crash, I would only have to write the following:</p><pre>let item = Item(title: “Moby-Dick”)<br>let row = makeRow(for item) // 💥 Crash here!</pre><p>It’s <em>concerningly</em> easy to write non-sensical code here, and it’s not immediately obvious from the call site alone that a crash would occur.</p><h3>What can be done about it?</h3><p>Any time I am in the situation where I have two mutually exclusive fields, and I need only one, my rule of thumb is to reach for an enum!</p><p>By utilising enums, we can structure our code in a way which ensures the compiler will only allow logical states to exist. Once we have eliminated the impossible states, the nonsense fatalErrors disappear!</p><h3>Take 2: Save me enums!</h3><p>First, I refactor my code and represent the items with the following enum:</p><pre>enum Item {<br>    case song(title: String, duration: TimeInterval)<br>    case book(title: String, numberOfPages: Int)<br>}</pre><p>The row building code now needs refactoring too:</p><pre>func makeRow(for item: Item) -&gt; Row {<br>    switch item {<br>    case let .song(title, duration):<br>        return Row(heading: title, subHeading: duration)<br>    case let .book(title, numberOfPages):<br>        return Row(heading: title, subHeading: numberOfPages)<br>    }<br>}</pre><p>Note how the fatalError has disappeared! There can never be a crash here now, as there can be no invalid Item.</p><h3>Conclusion</h3><p>The example presented is clearly contrived, but the architectural pattern is invaluable. I see this problem most commonly in code that handles JSON decoding. Next time you look at structures decoded from JSON, try and spot the mutually exclusive fields. If you end up with an invalid object, chances are your decoding operation should have failed already!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9686ccf4f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/the-importance-of-logical-data-modelling-c9686ccf4f1">The importance of logical data modelling</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with Natural Language Processing]]></title>
            <link>https://medium.com/codex/fun-with-natural-language-processing-f88ef0be7b21?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f88ef0be7b21</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[spelling]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 16:35:14 GMT</pubDate>
            <atom:updated>2022-04-10T16:49:16.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_vgk-y3raSuQZ7vrhns_A.png" /><figcaption>Check You Spellling!</figcaption></figure><p>I’ve recently discovered Apple’s Natural Language framework and decided to have a play, test out some ideas and share my findings. This will be a short article about a few things the framework can do and potentially offer some inspiration for your own apps</p><p>I started with UITextChecker. As the name implies the text checker does spell checking. You give it a string to check and it spits out the first mis-spelt word. From here you can get the text checker to give some suggestions for what the desired word might be. This is essentially Apple’s version of red squigglies</p><p>My immediate though was around search fields and mirroring Google’s “Did you mean x?” functionality. I banged a quick bit of code and voilà! Search field correction suggestions!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c057f3b50eaa88005dfa59a5d9408a33/href">https://medium.com/media/c057f3b50eaa88005dfa59a5d9408a33/href</a></iframe><p>Following this, I thought it might be nice to offer suggestions for semantically similar options. As you might have guessed, the Natural Language framework does this too!</p><p>By adding the following bit of code, we can get a bunch of similar words. The framework also offers a distance parameter for each of these that indicates how close they are to the original word.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/437b4f9f9356f1d62f82bebbd34b9dc5/href">https://medium.com/media/437b4f9f9356f1d62f82bebbd34b9dc5/href</a></iframe><h3>Final thoughts</h3><p>I can already see how I might use this in apps to provide some nice UX features with minimal complexity. There’s plenty of other cool bits the Natural Language framework can do too, so it’s definitely worth having a play!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f88ef0be7b21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/fun-with-natural-language-processing-f88ef0be7b21">Fun with Natural Language Processing</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift + C: Callback Interoperability]]></title>
            <link>https://medium.com/codex/swift-c-callback-interoperability-6d57da6c8ee6?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d57da6c8ee6</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[interoperability]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Fri, 22 Oct 2021 10:49:13 GMT</pubDate>
            <atom:updated>2022-01-28T10:04:08.873Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*SlihR_sTH3TTj0SZgbsnhA.png" /></figure><h3>Background</h3><p>A very common pattern across programming languages is the use of callback functions. A callback function is a reference to executable code passed as an argument to other code, allowing it to be executed at a later time.</p><p>In swift we encounter this patten often. One particularly common example is URLSession.dataTask(with:completionHandler:). After a request has been made, the network may take some time to respond. Rather than wait idly, we can give a completion handler to be executed when the response is received allowing the application to proceed in the meantime.</p><p>One place we see this pattern in C is in the SQLite3 framework packaged with Swift. SQLite3 facilitates access and manipulation of Structured Query Language databases and is the underlying technology powering CoreData.</p><p>As databases can take time to search or alter, SQLite3 provides the function sqlite3_exec with takes a C style callback. When this function is bridged across to Swift the @convention(c) annotation is applied. This annotation denotes that the callback is going to be used in a C context and must follow certain criteria. One of these criteria is that the function cannot capture any data. This poses a problem as we are likely to want to pass the callback arguments onto some other object that exists outside of the callback - we may want pass database information to a view layer example.</p><h3>Solution</h3><p>One way many C APIs work around this limitation is by passing an additional context parameter. This allows a reference to some object to be passed through to the callback in addition to the arguments that are returned later. We can then pass the other arguments to the object so they can be transfered outside of the callback scope.</p><p>Assume the following setup:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37f9361fbbe9c61dfb1466bbd409e5bc/href">https://medium.com/media/37f9361fbbe9c61dfb1466bbd409e5bc/href</a></iframe><p>Here we can see that the Callback typealias is marked with the aforementioned @convention(c) annotation. If we modify the code to capture an object within the scope of callback we see the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mufv23dAgKjD2GpY_l2dTg.png" /><figcaption>A C function pointer cannot be formed from a closure that captures context</figcaption></figure><p>The way we can work around this is by passing our object as the context argument like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e406ec1ccbdb1ccd0cdca9d6599aa3/href">https://medium.com/media/45e406ec1ccbdb1ccd0cdca9d6599aa3/href</a></iframe><p>Here we create an Unmanaged object which we are expected to manage the lifetime of manually. We convert this to an UnsafeMutableRawPointer so it can be passed into sqlite3_exec as context data. The context data is then passed into our callback where is can be converted back into our Object type ready for use.</p><p>passRetained creates a reference keeping the object alive indefinitely until takeRetainedValue is called. At that point, the retain is consumed and the object can be deallocated. If the object was guaranteed to still be alive at the time the callback is executed, passUnretained and takeUnretainedValue could be used, but be aware that if the object goes out of scope, this would result in a crash very similar to how unowned variables work.</p><h3>Bonus Material</h3><p>Ideally, we’d like to extend this pattern so we are not reliant on any one object to handle the response of the C API. One way of achieving this is to pass a Swift closure as the context argument. The following repo has an example of that pattern for those who are interested:</p><p><a href="https://github.com/oconnelltoby/Adder/blob/master/Sources/Adder/Adder.swift">Adder/Adder.swift at master · oconnelltoby/Adder</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d57da6c8ee6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/swift-c-callback-interoperability-6d57da6c8ee6">Swift + C: Callback Interoperability</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuple splatting in Swift]]></title>
            <link>https://oconnelltoby.medium.com/tuple-splatting-in-swift-7ebe8bed3dad?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ebe8bed3dad</guid>
            <category><![CDATA[tuples]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[splat]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 08:13:24 GMT</pubDate>
            <atom:updated>2021-08-28T08:13:24.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*m9ncM3IAxOk64prTLaqLig.png" /></figure><h3>What Is Splatting?</h3><p>Argument splatting is the concept of extracting the parameters of an object to pass to a function automatically. In Swift this can be done using tuples.</p><p>Suppose we had some data and a function that looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e5d97b86a781f88f597de8e76628bb/href">https://medium.com/media/26e5d97b86a781f88f597de8e76628bb/href</a></iframe><p>We’d like to pass all our users through the makeGreeting function to generate personalised greetings. One common way to achieve this would be to use the map higher order function like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69e05049f557ebb66bc81ae6246f3dc7/href">https://medium.com/media/69e05049f557ebb66bc81ae6246f3dc7/href</a></iframe><p>We can make this more concise however by utilising tuple splatting! This will allow our 2 argument function to take a tuple with 2 elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d9f7a2bf3cda5eaded9486b4f896e3f/href">https://medium.com/media/3d9f7a2bf3cda5eaded9486b4f896e3f/href</a></iframe><p>Tuple splatting allows us to pass the arguments through without having to extract them from the original data. Note that this can be done with other higher order functions such as filter, flatMap, forEach etc.</p><h3>Direct splatting</h3><p>It should be noted that direct splatting cannot work. If we try to call out makeGreeting function with a single tuple we get the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRtDShwlsWxUDd6JwLQSXQ.png" /><figcaption>Global function ‘makeGreeting’ expects 2 separate arguments</figcaption></figure><p>As we know, going through a little indirection like with the map function can solve this problem for us. The following function can be used to achieve that small amount of indirection required:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/113891fa94a7d78a5516902c5add6f9f/href">https://medium.com/media/113891fa94a7d78a5516902c5add6f9f/href</a></iframe><p>We can use this new helper like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00ac8750861ed9ee86527a5cb5681b80/href">https://medium.com/media/00ac8750861ed9ee86527a5cb5681b80/href</a></iframe><h3>Conclusion</h3><p>We’ve seen how tuple splatting can be used with higher order function to make code more concise.</p><p>Use of the helper certainly make the call site more concise, but it could be argued that it hurts readability. Personally I quite like it, but let me know what you think in the comments :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ebe8bed3dad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enums Cases as Protocol Witnesses and the Open-Closed Principle]]></title>
            <link>https://medium.com/codex/enums-cases-as-protocol-witnesses-and-the-open-closed-principle-f622c284f881?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f622c284f881</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 10:23:32 GMT</pubDate>
            <atom:updated>2021-07-25T11:13:12.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_Fsy_krMDnRuKe9k2sFO6Q.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@andreiamza2000">Amza Andrei</a></figcaption></figure><h3>Background</h3><p>Recently I have been implementing a lot of analytics events in a client’s app. Tagging this application (which has a great deal of UI) was always going to a laborious task, so I was looking to architect an ergonomic API to interact with.</p><p>Whilst deciding on the interface I remembered the Swift 5.3 feature that allows <a href="https://github.com/apple/swift-evolution/blob/main/proposals/0280-enum-cases-as-protocol-witnesses.md">enum cases to be used as protocol witnesses</a>. This became a great teaching opportunity for the junior I was pairing with. In short, a protocol that requires a static function that returns Self can be satisfied by an enum case with an associated value. Additionally, any static variable of type Self in the protocol can be satisfied by a enum case without an associated value.</p><p>Suppose we had the following protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94873b6b04cbd75c7cdc13bde2eadfbe/href">https://medium.com/media/94873b6b04cbd75c7cdc13bde2eadfbe/href</a></iframe><p>We could satisfy it with the following struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff252b92d28bf9519676e29a3595b450/href">https://medium.com/media/ff252b92d28bf9519676e29a3595b450/href</a></iframe><p>Additionally, we could also satisfy the protocol with this enum:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acfb2aca8ddb8d32e6d8a6bdf05bf228/href">https://medium.com/media/acfb2aca8ddb8d32e6d8a6bdf05bf228/href</a></iframe><p>To the API consumer both of these look the same as they are called identically:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cfb4b5ec54122fb96cb081f3f41b1c9/href">https://medium.com/media/6cfb4b5ec54122fb96cb081f3f41b1c9/href</a></iframe><h3>The Open-Closed Principle</h3><p>The <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">Open-Closed principle</a> is one of the 5 <a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a> design principles. It states that “software entities should be open for extension, but closed for modification.” What this means is, our API should be extendible without having to change the original source code.</p><h3><strong>Enum vs Struct</strong></h3><p>The Open-Closed principle is one place where enums fall down. They cannot be extended to include additional cases, so every time a new event type is added to our protocol, we need to modify the original enums source. This is not the case with a struct that can be extended across multiple files.</p><p>One other consideration is the size of the protocol. Currently there are two events, but what happens when the number of events to track explodes? If we had some 60 screens each with 2-5 events we’d end up with around 210 enum cases. These would all have to sit in the same file and in the case of our name variable, we’d have an enormous switch statement too.</p><p>In a situation where a backend analytics system can only handle certain events, it may make complete sense to prevent any unknown &amp; unhandled events slipping through by using an enum, but overall I think the struct pattern works best in this scenario.</p><h3>Conclusion</h3><p>Using enum cases as protocol witnesses is a cool addition to the Swift language, but we still need to consider if enums are the best tool for the job at hand. As always, when you’ve got a shiny new hammer, it’s tempting to treat everything a nail, but it’s always worth stepping back and assessing the needs of the API &amp; the ergonomics of its ongoing use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f622c284f881" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/enums-cases-as-protocol-witnesses-and-the-open-closed-principle-f622c284f881">Enums Cases as Protocol Witnesses and the Open-Closed Principle</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoding awkward types with minimal boilerplate using `withUnsafeBytes`]]></title>
            <link>https://medium.com/codex/encoding-awkward-types-with-minimal-boilerplate-using-withunsafebytes-4032dd861d9f?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4032dd861d9f</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 21:51:50 GMT</pubDate>
            <atom:updated>2021-08-28T08:59:32.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuhsaEPY4zSfd9Uvmr2Lrg.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@flowforfrank">Ferenc Almasi</a></figcaption></figure><h3>History</h3><p>For many years now, the go-to way of encoding and decoding Swift types to JSON has been the Codable protocol.</p><p>This gave a more type safe way of handling json than its predecessor JSONSerialization, which spat out [String: Any] dictionaries. Conversely Codable handles conversion upfront, dealing with all the type conversion, and failing if the object cannot be converted successfully.</p><p>An additional advantage of Codable is that conformance can be synthesised for many objects if they only contain other Codable or simple types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2567ca3bb1036986ee28ca8db0aa32e7/href">https://medium.com/media/2567ca3bb1036986ee28ca8db0aa32e7/href</a></iframe><h3>The problem</h3><p>One place common place where Codable conformance cannot be synthesised is when using enums with associated values. The complier will tell us that the type does not conform to Decodable or Encodable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwcejpRWcCspDIU_V1Mv7w.png" /><figcaption>Un-synthesisable Codable conformance</figcaption></figure><p>There are a number of ways of getting around this issue, the most common being to use custom implementations of the Decodable or Encodable protocols. One implementation might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09ec00ea9132d2d9bae477b799c23fdc/href">https://medium.com/media/09ec00ea9132d2d9bae477b799c23fdc/href</a></iframe><p>Despite the fact that this adds a tremendous amount of boilerplate code, it’s also not reusable. If we have another enum with a different format, we would have to re-write this all again.</p><p><a href="https://forums.swift.org/t/codable-synthesis-for-enums-with-associated-values/41493">Proposals</a> have been made to add Codable synthesis to enums with associated values but as of yet, nothing has been added to the Swift language.</p><h3>Solution: withUnsafeBytes to the rescue!</h3><p>One simple solution to solve the problem of reusable conformance for varying types is to use withUnsafeBytes. This allows us to access the underlying memory for a Swift object. We can then use that underlying memory directly or as part of a larger JSON object. Here is a simple (and reusable) protocol that does the encoding for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7954b2616dbbeba82aa7a959e71fafe8/href">https://medium.com/media/7954b2616dbbeba82aa7a959e71fafe8/href</a></iframe><p>It should be noted that this is not a robust way of serialising data, just a really simple one. Ideally, this data should not be written to disk or transferred between devices as the data format could change between Swift versions or between different devices. Having said that, newer versions of Swift with ABI stability may mitigate this concern somewhat.</p><p>I will be using this method to transfer data between my Unit Tests and my Application for testing under different launch conditions. I consider this relatively safe as the device type and Swift version will always match.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4032dd861d9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/encoding-awkward-types-with-minimal-boilerplate-using-withunsafebytes-4032dd861d9f">Encoding awkward types with minimal boilerplate using `withUnsafeBytes`</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using tuples for Comparable and Equatable conformance]]></title>
            <link>https://medium.com/codex/using-tuples-for-comparable-and-equatable-conformance-5587842a9784?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5587842a9784</guid>
            <category><![CDATA[comparable]]></category>
            <category><![CDATA[tuples]]></category>
            <category><![CDATA[equatable]]></category>
            <category><![CDATA[conformance]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 09:49:29 GMT</pubDate>
            <atom:updated>2021-08-28T08:59:25.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I discovered that tuples can be used to easily and simply compare and equate multiple variables.</p><p>Take for example the implementation of Date and Comparable taken from the Swift documentation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2dbdcee8125a4781d2f9c1e32bf070/href">https://medium.com/media/1e2dbdcee8125a4781d2f9c1e32bf070/href</a></iframe><p>This compares the year, month and day in that order to determine which is greater (later). A simpler (and perhaps more readable) way of writing this same code is this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23d27f1adadf8225b10bb4547c62a749/href">https://medium.com/media/23d27f1adadf8225b10bb4547c62a749/href</a></iframe><p>The tuple is compared in order of its variables so we achieve the same result.</p><p>As an added bonus, the same is true for Equatable conformance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7267db22eecbd2c7ff99503dc5883412/href">https://medium.com/media/7267db22eecbd2c7ff99503dc5883412/href</a></iframe><p>This last one is a bit of a contrived example as Equatable conformance would be synthesised for Date anyway, but suppose we wanted to omit the year, to compare birthdays, it would be very easy to simply remove year from the tuples</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5587842a9784" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/using-tuples-for-comparable-and-equatable-conformance-5587842a9784">Using tuples for Comparable and Equatable conformance</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UIGestureRecognizer with closures]]></title>
            <link>https://medium.com/codex/uigesturerecognizer-with-closures-cbea04a4df2f?source=rss-96f3bc4104e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbea04a4df2f</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[uibutton]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[selectors]]></category>
            <category><![CDATA[uigesturerecognizer]]></category>
            <dc:creator><![CDATA[Toby O'Connell]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 23:00:17 GMT</pubDate>
            <atom:updated>2021-08-28T08:59:19.257Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the biggest downsides to UIGestureRecognizer is the inability to attach simple closures in-line. To use them, a target object must be specified alongside a Selector pointing to a function to call.</p><p>One major disadvantage to this paradigm is that UIGestureRecognizer only passes the calling object to the called function. This means that if multiple objects call the same function, they need to be differentiable in some way.</p><p>Out of curiosity I looked for a solution online. Many suggest using the Objective C runtime to add an Associated Object to manage a closure, but this gets into the realm of hackiness. One cleaner solution I stumbled across was to simply subclass the gesture recogniser and add the action to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1be9407064f8b560aad2279a2b790ba3/href">https://medium.com/media/1be9407064f8b560aad2279a2b790ba3/href</a></iframe><p>This simple but elegant solution solves the problem neatly and cleanly. The same solution can also be used for other subclassable target + selector style APIs such as with UIButton.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbea04a4df2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/uigesturerecognizer-with-closures-cbea04a4df2f">UIGestureRecognizer with closures</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>