<?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 Bartosz Polaczyk on Medium]]></title>
        <description><![CDATA[Stories by Bartosz Polaczyk on Medium]]></description>
        <link>https://medium.com/@londeix?source=rss-455e6a104b5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kUjhJrUgR4fRXV8Py45ymQ.png</url>
            <title>Stories by Bartosz Polaczyk on Medium</title>
            <link>https://medium.com/@londeix?source=rss-455e6a104b5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 13 Jul 2026 12:21:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@londeix/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[Inspecting Xcode’s build system graph at ease]]></title>
            <link>https://medium.com/@londeix/inspecting-xcodes-build-system-graph-at-ease-e96573d5d340?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e96573d5d340</guid>
            <category><![CDATA[build-system]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 03:36:20 GMT</pubDate>
            <atom:updated>2023-09-25T06:36:46.608Z</atom:updated>
            <content:encoded><![CDATA[<h4>How does the Xcode build system work under the hood?</h4><p>If you ever tried to understand why the Xcode build system complains about a compilation cycle or optimize a build where a particular step is invalidated between executions, there aren’t any good visualization tools that might help with troubleshooting other than build logs or Build Timelines added in Xcode 14. While these two techniques might still give some insights, 1) they are only available as a post-build artifact so aren’t useful to troubleshoot build system dependency cycles and 2) these approaches have limitations.</p><p>From what I observe, many engineers underestimate the complexity of build systems. That is especially the case for Xcode users where predefined templates bootstrap the project magically and developers don’t have to set up steps manually.</p><p>In this blog post, we will scratch the surface of the Xcode build system and audit what steps are involved when you press ⌘+R in a visual representation of a build graph using <a href="https://github.com/polac24/XCBuildAnalyzer/">XCBuildAnalyzer</a>.</p><h3>Scenario I — build cycle</h3><p>For sure you have seen an error saying that you have a cyclic dependency in your project, which might be just a simple oversight with incorrectly set target dependencies, but in more complex scenarios (mixed ObjC&amp;Swift target, I am looking at you), the fix might not be simple. If that happens, Xcode provides a simplified cycle detail in the Report navigator view and prints the “raw dependency cycle trace” below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTmSrIc-yrZf2GCF4u6quQ.png" /><figcaption>The high-level summary of a simple dependency cycle in Xcode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrlGrEWYXW70Bt5ZxLS_aw.png" /><figcaption>Detailed, raw dependency cycle path</figcaption></figure><p>The latter data is quite difficult to analyze but gives us some clues about the internal implementation of the build system. It consists of all nodes and commands that constitute a cycle in the build system graph.</p><p><em>Commands</em> are actual steps that have a concreted action like calling an external application, while <em>nodes</em> are just virtual nodes, convenient for setting dependencies between commands. You can think of <em>commands</em> as real actions and nodes as breakpoints describing what kind of outputs/inputs a given command produces/depends on. A list of sample commands and nodes below might give you a clue of their differences:</p><h4>Command (with tool involved):</h4><ul><li>Copy (file-copy)</li><li>SwiftDriver Compilation (swift-driver-compilation)</li><li>SwiftMergeGeneratedHeaders (swift-header-tool)</li><li>WriteAuxiliaryFile (auxiliary-file)</li><li>PhaseScriptExecution (shell)</li><li>CreateBuildDirectory (create-build-directory)</li><li>ClangStatCache (shell)</li><li>VersionPlistTaskProducer (phony)</li><li>CodeSign (code-sign-task)</li></ul><h4>Nodes:</h4><ul><li>entry</li><li>begin-scanning</li><li>begin-compiling</li><li>copy-headers-completion</li></ul><p>In our example, a quick inspection of all <em>nodes</em> and <em>commands</em> provides an overview of things happening. Names refer to module map/header map creation, validation, assets compilation, and other terms that not always might be obvious. To have a better mapping of all relations between steps, having a graphical visualization of all these nodes might be helpful. Fortunately, for each build (including those that failed with a cycle error), Xcode generates a full dump of the build graph nodes in the DerivedData. Despite the representation being in a readable JSON format, navigating through a large object file might be tricky, which is why I created an experimental macOS app, <a href="https://github.com/polac24/XCBuildAnalyzer/">XCBuildAnalyzer</a>, that draws it on a 2D plane.</p><p>The build analyzer can draw a graph that might look familiar to you if you have ever troubleshooted memory cycles in Xcode or Instruments. The goal of this app is to draw the graph in a digestive format, easier to create a mental model of parts in a cycle. <a href="https://github.com/polac24/XCBuildAnalyzer/tags">Download</a> the app and drag and drop the .xcodeproj or Package.swift after building it in Xcode.</p><p>As you may guess, the graph itself is very big so drawing it on a screen wouldn’t be helpful — thus, the app presents a subgraph, similar to the one generated for our example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdLdS1wK9wGNk10_b18R-w.png" /><figcaption>A build system cycle drawn in XCBuildAnalyzer</figcaption></figure><p>If you follow the yellow cycle path, you find that Library1 depends on Library2 in links:</p><ul><li>[Library1] end -&gt; [Lirary2] entry</li><li>[Library2] modules-ready -&gt; [Library1] begin-compilation</li></ul><p>That cycle is something we have to resolve — there aren’t any ready-to-apply fixes — problems are project-specific and the analysis should be carried over case-by-case. <br>For details, the XCBuildAnalyzer app allows expanding nodes in the graph to disclose steps relevant to troubleshooting.</p><blockquote>Tip: the build graph view can very easily get out of control as you expand nodes. If that happens, just start the process from the beginning, just like you would do in the Xcode memory inspector.</blockquote><h3>Scenario II — missing dependencies</h3><p>Do you recall a problem with random and transient Swift errors happening after cleaning a project or building on a different machine with the message No such model {HereModule}? That might be caused by incorrectly defined target dependencies and based on a nondeterministic order of compilation, the required {HereModule} might, or might not be ready yes.</p><p>If your project contains only a few targets, probably you can quickly find a missing link, but for bigger projects with dozens or hundreds of targets, that might be tricky.</p><p>The first sign of a problem can surface right after opening the graph and realizing that nodes from the problematic target {HereModule} are missing. That implies that you haven’t set any dependency to that module and it works on your machine because you built that target earlier or using a different scheme. But if both targets are on a list, let’s find the first common node that depends on two targets. First, we have to find which compilation target reported an error. In Xcode’s report navigator pick Recent and Errors only selectors to filter all other steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-cfC7p1H0paTNHaBf_XGA.png" /><figcaption>Finding the compilation target: The Down3 target failed with a missing Top2 module (the target name is likely also Top2)</figcaption></figure><p>To inspect a problem, we want to find a relation between build graph nodes “finishing the Top2” and “beginning of the Down3“. Let’s open XCBuildAnalyzer and with the ⌘key, select [Top2] modules-ready and [Down3] begin-compiling. Let’s analyze the result below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwXnDSa4xPsePM2r-vpc4g.png" /></figure><p>Let’s start by reading the graph from right to left. The build system always starts the analysis from theend node (0.) and traverses through the graph to find the steps required for execution. <br>Firstly, we can realize that there is no direct or indirect relation between Down3 (1.) and Top2 targets (2.). So why isTop2 even included in the build and why the build system is not complaining all the time? As seen, Top3 (3.) is the target that has an explicit dependency on a Top2, and based on the compilation order, Top2 and Top3 might be compiled prior to Down3.</p><blockquote>Note that even the graph renders Down3 begin-compilling to the right of [Top2] modules-ready , that doesn’t mean it will be executed later. Remember that the graph represents relations between nodes; it does not represent a timeline.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*jGXHv3si_uhcz_l4jEsvtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*yJN5cefLYaMMiuWCqgoDKQ.png" /><figcaption>Expected (left) and actual (right) relations between targets</figcaption></figure><p>Once we add a missing dependency in Xcode and compile the project again, the subgraph reveals the expected dependencies between Down3 and Top2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9Zq62ZZY-t_2Lst0dWtSA.png" /></figure><h3>Scenario III — curiosity</h3><p>The last reason why you may want to review the build graph is <em>pure curiosity</em>. For instance, Xcode 15 introduced a nice feature to generate Swift/ObjC type with all of your Assets symbols (for more details, read this <a href="https://www.swiftjectivec.com/generated-asset-symbols-objective-c/?utm_campaign=iOS%2BDev%2BWeekly&amp;utm_medium=web&amp;utm_source=iOS%2BDev%2BWeekly%2BIssue%2B627">blogpost</a>). You might ask yourself: (1) how is that implemented? and (2) can I safely modify <em>.xcassets</em> content from prebuild shell build scripts so the generated asset symbols file will always reflect the change?</p><p>Finding a starting point for the assets symbols generation shouldn’t be difficult because node names are often self-explanatory (like CompileAssetCatalog, GenerateAssetSymbols , TestTargetTaskProducer, etc.). In our case, that will be GenerateAssetSymbols and on the right pane of the XCBuildAnalyzer, you can find that it is an external shell command (actool) invocation. <em>Bonus: you can inspect the list of args and ENVs passed to that external command.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWmRJiBBm0VmTMsuHaWOvg.png" /></figure><p>As expected, this step will output two files (ObjC and Swift) and take Assets.xcassets directory as input.</p><h4>Question 2: Can I safely modify .xcassets content from pre-build shell build scripts so the generated asset symbols file will always reflect the change?</h4><p>For the second question, before jumping into heavy 2D graph visualization, let’s add a shell script and analyze raw Xcode’s build output logs to see which one was executed first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*491jbt9t2xKqf9mz0jHNmw.png" /></figure><p>In the logs, seems that our script was indeed scheduled first, but is that a coincidence? Maybe we were just lucky? Let’s open the project in XCBuildAnalyzer and compare the relationship between [GenerateAssetSymbols] xxx.swift and &lt;execute-shell-script&gt; . From the left pane select two nodes (you can use ⌘ or ⇧ keys) and you will get something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAPZrIL2-uk76fSksUB5zw.png" /></figure><p>Success! So <strong>there is</strong> a strong relation between those two steps and we can be confident that GeneratedAssetSymbol.swift will be generated <strong>after</strong> the script is done. Saying that we can safely modify the .xcassets directory, and the actoolwill respect it.</p><blockquote>Warning! Having the right asset symbol in Swift/ObjC is just a partial success. To ensure that the modified assets will be included in the application bundle, we need to ensure that the assets compilation step (CompileAssetCatalog) is also dependent on the run script. With just a few clicks you can validate that this is also a case — Assets.car (the compiled assets representation) will also include updated assets.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWpFifYP3lsyFPZGql-AOg.png" /><figcaption>The subgraph of the Assets.car generation</figcaption></figure><h3>Epilogue</h3><p><a href="https://github.com/polac24/XCBuildAnalyzer/">XCBuildAnalyzer</a> is one of those tools that sit in your toolbelt and you hope to never need it. However, it might be helpful if you hit a tricky build system problem that you cannot resolve in a conventional way: by reading logs or double-checking Xcode target dependencies.</p><p>So let’s hope for the best, but prepare for the worst — try out XCBuildAnalyzer and say hello to the Xcode build system internals!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e96573d5d340" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stubbing in pair with Swift compiler: A spy registration]]></title>
            <link>https://medium.com/@londeix/stubbing-in-pair-with-swift-compiler-a-spy-registration-bbfdc1cf87a1?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbfdc1cf87a1</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 08 Apr 2019 16:15:25 GMT</pubDate>
            <atom:updated>2019-06-18T16:21:30.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stubbing in pair with Swift compiler: a spy registration</h3><h4>How to effectively verify unit test side effect without code generation in Swift</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hJRToGwERMRiq1tdEF7ag.gif" /><figcaption>Thanks to <a href="https://dribbble.com/juneuprising">Bill Chung</a> for the wonderful eye animation</figcaption></figure><p>Often we need to unit test code with side-effects that interact with other parts of your system using abstraction — protocols in Swift. There are many techniques to build that abstraction and verify if our code works as expected: stubbing, spying, dummying etc.</p><p><a href="https://medium.com/@londeix/stubbing-in-pair-with-swift-compiler-c951770a295b">Previously</a>, I made a deep dive into auto-generating a stub placeholder that allows seamless customization of a mock’s function behavior right in a test case. Let’s extend that approach with a spy registration that observes and records side-effects generated during a test case.</p><h3>What you need to know first</h3><p>Let me present in a nutshell how you can speed up a process of building function’s stub with some Swift compiler help (for details refer <a href="https://medium.com/@londeix/stubbing-in-pair-with-swift-compiler-c951770a295b">to my previous post</a>).</p><p>Assume that you wish to create a mock for a protocol containing some function (for the sake of this article named addUser(name:)). And instead of creating it from scratch with a custom flag(s) and/or embedded assertions, for each function generate only a single variable as a placeholder to be called internally during that function’s call. In a traditional way, you would need to manually provide a type of that placeholder&#39;s function but with lazy modifier and some simple helper function stub, it can be inferred by a Swift type system. The final solution would look as simple as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb924d71f6729184ab44929e38569d9b/href">https://medium.com/media/bb924d71f6729184ab44929e38569d9b/href</a></iframe><p>In a test case, you need to explicitly register behavior of addUser with a concrete implementation, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c62e515472588c953c1dfd09870a8d5/href">https://medium.com/media/5c62e515472588c953c1dfd09870a8d5/href</a></iframe><h3>Problem statement</h3><p>The benefit is that we don’t have to manually specify the type of addUserAction variable. However, <strong>generating its body (</strong><strong>addUserAction) has to be done on a test case-level </strong>which often leads to messy variable declaration and assignments as above. The aim of this article is to completely eliminate that manual step of action declaration which in a first place can positively affect test case readability and as a by-product positively affect development speed and joy.</p><h3>Step 1: stub split</h3><p>Firstly, let’s modify our stub function and separate its input and output types into two generic types:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ddfa30832a387f714becd2a0927402b/href">https://medium.com/media/8ddfa30832a387f714becd2a0927402b/href</a></iframe><p>it works also for functions that take several parameters —then the type will be a tuple with corresponding types, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f8098bc9cbbcfcadf2062050b86fa1c/href">https://medium.com/media/5f8098bc9cbbcfcadf2062050b86fa1c/href</a></iframe><h4>Nice mock stubbing</h4><p>Once we split the type of our entire stub’s type into Input (I)and Output (O) generics, as a low hanging fruit we can make a stub builder that generates nice stub — one that returns some predefined value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9810952d7bd90421dce7878558755de6/href">https://medium.com/media/9810952d7bd90421dce7878558755de6/href</a></iframe><p>Once action placeholder is build using niceStub, in a testcase we don’t have to manually “register” the function’s body before calling the protocol’s function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5341987e1db7ab8cd91bff2b9691277/href">https://medium.com/media/c5341987e1db7ab8cd91bff2b9691277/href</a></iframe><p>Another simple improvement here is defining predefined return values for some popular types (like 0 for Int, false for Bool, nil for Optional&lt;T&gt; etc.). With a simple DefaultProvidable protocol that specifies a default value of a given type and more specific niceStub, stubbing is as simple as never before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e08a5ec3121127e2432c4aa8c5f5d54/href">https://medium.com/media/5e08a5ec3121127e2432c4aa8c5f5d54/href</a></iframe><blockquote><strong>What if the function doesn’t return anything</strong>? In a Swift language all functions actually return something, Void if not specified. Void is implemented as a zero-length tuple and as a non fully fledged type it cannot conform to any type like DefaultProvidable. No worries, Swift type system can correctly select the right implementation if we introduce another niceStub specifically for functions that return Void:</blockquote><blockquote><strong>func</strong> niceStub&lt;I&gt;(of: (I) -&gt; Void ) -&gt; (I) -&gt; Void {<br> return { _ in }<br>}</blockquote><h3>Call arguments spy</h3><p>Although we have a simple way to define stub, we completely ignore passed arguments there. However, it not uncommon to inspect arguments that have been passed to the mock object and to achieve that we need to apply another trick. Thanks that body of a mock’s function (like addUserAction) is defined as a variable we can easily edit its behavior in a testcase runtime.</p><p>To apply a spy, just inject an intermediate spy layer that stores all the arguments call in a recorder and performs already specified body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-zuEC801dam7_GDe1Luog.png" /><figcaption>Injecting spy layer using spyCalls(…)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbc816c10db4534738a4e200921bba86/href">https://medium.com/media/dbc816c10db4534738a4e200921bba86/href</a></iframe><blockquote>If you are not familiar with Swiftinout modifier, it gives a change to modify the value of passed argument once it is finished. It resembles a bit passing pointer argument in Objective-C but with a restriction that it cannot escape that “pointer”.</blockquote><p>spyCalls takes an inout argument of a function to spy, injects a function that records its arguments to ArgRecords&lt;I&gt; and then calls original stub implementation.</p><p>Implementation of a missing ArgRecords is really straight-forward as this is just a custom collection to keep track of all records. It needs to be represented as a reference type collection and backing up by the simplest Array is often enough (as long as you don’t expect any multithread read/write operations).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dff369bd8f291276668c2641eee8ddf1/href">https://medium.com/media/dff369bd8f291276668c2641eee8ddf1/href</a></iframe><p>ArgRecords resembles a Collection but here it specifies custom subscript return type. Instead of T, I suggest returning optional T? just to not crash tests if the expected spy index is out of range. In practice, subscript result lands in XCTAssertEqual which automatically aligns optionality types and gracefully could handle out-of-range access:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f954b6d4cf4f5d609788a2b5725f7d09/href">https://medium.com/media/f954b6d4cf4f5d609788a2b5725f7d09/href</a></iframe><blockquote>Technically, subscript could return non-optional T and conform to Collection but any out-of-range access crashes the test suit —it is up to you what type to select.</blockquote><h3>Further improvements</h3><p>If you find it useful and promising, this is just a beginning! The presented approach sets up a foundation for much more complexed and omnipotent testing toolset that supports synchronous or asynchronous expectations, return values control with some syntactic sugar API. Open-source <a href="https://github.com/polac24/StubKit/">StubKit</a> library is based on that approach and provides a set of extensions (some of them are described below).</p><h4>Improvement 1 — support for throwing functions</h4><p>Until now we assumed that our stubbing function does not throw. If it does, we need to prepare twin declarations of stub and spyCalls that are capable of stubbing and spying functions with throws modifier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d2895f869971645f0ab1b884fe33259/href">https://medium.com/media/6d2895f869971645f0ab1b884fe33259/href</a></iframe><h4>Improvement 2 — generics functions</h4><p>Creating a stub/mock of a function that is <strong>generic</strong> is a bit tricky. As long as you expect only one specification, your entire mock can be generic with a force-casting (aka unwrapping):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ced39747709bfb7d7cf2bfd5443a7bc4/href">https://medium.com/media/ced39747709bfb7d7cf2bfd5443a7bc4/href</a></iframe><p>However, if a single generic type for a stub is unacceptable, you should prepare a set of expecting specializations and choose one that matches. Please refer to <a href="https://github.com/polac24/StubKit/blob/master/docs/documentation.md#generic-functions">StubKit’s documentation</a> for detailed example.</p><h4>Improvement 3— Convenient ArgRecords comparison</h4><p>So far in the assert section we had to manually compare each subsequent call manually:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b27f90a19d50fb7cb470606c42f201/href">https://medium.com/media/f4b27f90a19d50fb7cb470606c42f201/href</a></iframe><p>With straightforward conformance to Swift’s ExpressibleByArrayLiteral protocol, ArgRecords can be initialized directly from an array literal (like [1,2])</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa96dfd5b118f53a3fefe267ae60e6e4/href">https://medium.com/media/aa96dfd5b118f53a3fefe267ae60e6e4/href</a></iframe><p>Furthermore, if we spy a function that takes a single Equatable argument, entireArgRecords can easily conform to Equatable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/375fd284d154f44021c30666b50ad95f/href">https://medium.com/media/375fd284d154f44021c30666b50ad95f/href</a></iframe><p>By wrapping these two improvements, the Swift compiler automatically aligns appropriate types and makes such idiomatic assertion possible:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5224174a3a19f40f3f3e06af4c00c078/href">https://medium.com/media/5224174a3a19f40f3f3e06af4c00c078/href</a></iframe><h3>Summary</h3><p>Writing and working with a manually created stub or mock seems to be a bit boring and wearisome step. Contrary to other languages (Ruby or JavaScript) lack of type dynamism API in Swift prevents more flexible and automatic testing tool. Technically Swift ABI lays some groundwork for <a href="https://twitter.com/dgregor79/status/1110616985774088192">magical testing library</a>, but as Doug Gregor wrote, “it would be a bunch of work (…) yet doable”.</p><p>I believe that the presented in this article approach eliminates some degree of dummy code that has to be written, although some minimal work to prepare a mock/stub is still required. The greatest benefit is concise and self-explanatory test case without a flood of intermediate variables placed around stubs and test case scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iaBRdH0J2bDNTRWS804ujg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbfdc1cf87a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift weak reference assertion]]></title>
            <link>https://medium.com/@londeix/swift-weak-reference-assertion-cf04fef6c334?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf04fef6c334</guid>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 06:01:00 GMT</pubDate>
            <atom:updated>2019-02-26T11:10:43.252Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Unit tests and memory leaks</em></h4><p>How do you assert that your code doesn’t introduce any unexpected cycles that lead to memory leaks? Do you actually verify weak/strong references in unit tests? If you find these questions interesting, let me demonstrate how you can write a concise and self-explanatory Swift test case that verifies correct reference type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITDWf9oX9MdDv2BgdCOWfQ.jpeg" /></figure><h3><strong>Weak verification</strong></h3><p>Whether your code keeps a strong or weak reference to some other object is crucial for non-garbage-collected languages like Swift. Even a tiny mistake may lead to a leak, invalid behavior or even crash. Although I don’t see many developers writing them, I believe that verification on a unit test level for misaligned reference type should a part of the implementation cycle— no matter if you practice TDD approach or not. Maybe our developer community categorizes them as second-class citizens because we are not sure how to write them and their readability is often far from perfect? <br>Let’s consider the simplest possible test that checks if an instance of a listener added to MasterClass’s is kept weakly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5031bce350429692834019cd5fdeb23/href">https://medium.com/media/d5031bce350429692834019cd5fdeb23/href</a></iframe><p>We can identify several code-smells there, including:</p><ol><li>unnecessary weakListener — duplication of listener just to inspect if a weak reference becomes nil</li><li>Optional type of a listener (with force unwrap )— to let it be nilled</li><li>manual assignment (weakListener=listener) of a strong reference to a weak one</li></ol><p>Even if you fix the second issue by introducing a scope that automatically releases listener at the end of its lifetime, this could end up with even more esoteric code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70eb2d467050af345841d8a98118d58a/href">https://medium.com/media/70eb2d467050af345841d8a98118d58a/href</a></iframe><blockquote>Tip: Swift’s do block we often identify with do-catch structure that catches Errors, while standalone <strong>do keyword is still a valid scope generator.</strong> As you may expect, within a body of suchdo block you cannot call try since potential thrown Error wouldn’t be handled.</blockquote><p>Alternatively, you may find XCTestCase’s addTeardownBlock function useful here. Similarly to defer keyword it defers the execution a block until all other commands in a test case finish — practically just before tearDown function. Nifty approach yet with a bit limited flexibility due to potential execution reorder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc733c9b3a3707dff32e122d26dd49e0/href">https://medium.com/media/cc733c9b3a3707dff32e122d26dd49e0/href</a></iframe><h3>Weakly-scoped — `with` inspiration</h3><p>Many modern languages (like Kotlin) provide setup functions intended to build up an instance in a self-contained scope (often named as with,apply), like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ab2308a9d638a7c77d79f14dcdc65a7/href">https://medium.com/media/6ab2308a9d638a7c77d79f14dcdc65a7/href</a></iframe><p>In a <a href="https://forums.swift.org/t/circling-back-to-with/2766">discussion</a> started by Erica Sadun, the Swift community considered adding it to a language. Ignoring the self-rebinding syntax, the implementation would be really straight-forward — take a starting instance T, mutate it in a block that takes that reference’s copy as an inout parameter and return mutated value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05c759f03a029b0d50c580221ad74fc4/href">https://medium.com/media/05c759f03a029b0d50c580221ad74fc4/href</a></iframe><p>Maybe you already noticed that our initial problem resembles the solution that discussed with tries to solve. To verify weak reference we had to:</p><ol><li>take initial/starting value of some generic T reference type</li><li>pass it to the block body that presumably leverages it (e.g. adds a listener, send as a function argument etc.)</li><li><strong>observe our initial instance weak reference if it is </strong><strong>nil</strong></li></ol><p>Combining the approaches in the first paragraph and with implementation, one may try to write it as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2323dfbddaae8b8640e8e372e41b58bf/href">https://medium.com/media/2323dfbddaae8b8640e8e372e41b58bf/href</a></iframe><p>At glance, it looks OK but the above snippet doesn’t work as one might expect. Even the dummies weaklyScopedNaive(MasterListener(), action: {<strong>_</strong> <strong>in</strong> }) always returns non-nil value because first(v) argument keeps a strong reference until the end of weaklyScopedNaive function, making in practice weakValue a strong reference.</p><h3>Weakly-scoped solution</h3><p>To overcome that problem we should transfer instance generation to the scope controlled by us and observe a weak reference after the scope destroy. No matter how complex that sounds, Swift provides such feature out the box — @autoclosure. Originally, it was designed to instantiate heavy instances on demand, to not compromise performance but it perfectly suits our need. Let’s introduce small changes to our function’s definition (add @autoclosure and rethrows):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4f47154c91c412480dd3f2ef07051aa/href">https://medium.com/media/b4f47154c91c412480dd3f2ef07051aa/href</a></iframe><blockquote>autoreleasepool (don’t mix up with autoclosure) could be useful if you play with Objective-C objects that might receive autorelease message (instead of release one that always happens for Swift class), that deffers deallocation until end of autoreleasepool. If you don’t expect Objective-C instancess, do scope is enough.</blockquote><p>Let’s come back to our initial test case and try to rewrite it using weaklyScoped helper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f16cdb4b4bf992396aafa192ace2d8e5/href">https://medium.com/media/f16cdb4b4bf992396aafa192ace2d8e5/href</a></iframe><p>It presents the essence of our test case scenario with a clear separation into Arrange, Act, Assert sections and elimination of noisy assignments. All the commands perform in a synchronous manner so complex scenarios with several steps also can apply this technique.</p><h3>Summary</h3><p>Test cases that verify reference types (strong vs weak) can eliminate plenty of invisible, nasty bugs affecting memory footprint or invalid behavior. If you ever found them clumsy and counter-intuitive to read, with the presented approach we can eliminate most of their drawbacks. <br>Although the weaklyScoped implementation uses some advanced Swift features (autoclosure, rethrow ) the final test case is simple and self-explanatory, even for beginners.</p><h4>Add-on:</h4><p>The usability of weaklyScoped function exceeds that trivial scenario with a listener or delegate. You can leverage it for leak detection or even completion-cancellation. For the inspiration on how to track them, see snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43471c0099753fa02d111cc19848fc42/href">https://medium.com/media/43471c0099753fa02d111cc19848fc42/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf04fef6c334" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xcode file variants without targets]]></title>
            <link>https://medium.com/@londeix/xcode-file-variants-without-targets-9724cbabe821?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9724cbabe821</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 03 Dec 2018 19:00:16 GMT</pubDate>
            <atom:updated>2018-12-03T19:00:16.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build Rules to select a file variant</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwl2b_CAibE_ps2kZOfcVQ.jpeg" /></figure><p>If you want to configure your iOS/Mac (Swift or Objective-C) build with some alternative variant, there are plenty of different approaches to follow. In general, you can divide them into two clusters: switch it in runtime (e.g. parsing Info.plist) or compile-time (leveraging Swift Compilation Conditions/Preprocessor Macro or define new target). Obviously, we always prefer the compile-time check but the overhead often may overweight its benefits.</p><p>This post will present an alternative way to control a file variant selection based on Xcode Build Rules (in contrast to traditional Xcode targets).</p><h4>Problem statement</h4><p>There are plenty of solutions to build a different flavor of the app that may differ in:</p><ul><li>endpoint address (e.g. staging vs production)</li><li>logic (e.g. enable/disable geofencing check)</li></ul><p>For more details, let me recommend this <a href="http://iosbrain.com/blog/2018/11/10/dividing-and-conquering-your-xcode-projects-with-targets/">post</a>, which presents most of them in details.<br>Long story short, for Swift development you can choose between:</p><ul><li><strong>Compilation Conditions</strong> to use #if DEBUG ... #endif structure to include or disable given block of code</li><li><strong>separate targets</strong>, where each target contains a separate, dedicated file with a specific code for given configuration</li><li><strong>runtime checks</strong> from .plist input file or environment variable</li></ul><p>Each has a drawback, to mention:</p><ul><li>iffing on compilation conditions may lead to a messy code with a plethora of #if that affects the readability</li><li>separate targets introduce the unnecessary need to include all the “shared” codebase and configuration to all of them</li><li>for runtime configuration, we lose compile-time check.</li></ul><p>Wouldn’t be great if we could have a solution with a <strong>single target</strong> that depending on a configuration <strong>uses a specific variant of a file</strong>?</p><h4>Solution: Use or skip a .swift file using custom Build Rule</h4><p>Traditionally, Xcode targets give you a chance to selectively choose which file to include for compilation. You may leverage it to replace one source file with another one that specifies other baseURL or completely different logic strategy. For the sake of this post, let’s assume that we want to use one of two different Configuration_X.swift files:</p><pre>// Configuration_S.swift<br>struct Configuration {<br>  let baseUrl = &quot;https://staging.example.com/&quot;<br>}</pre><pre>// Configuration_P.swift<br>struct Configuration {<br>  let baseUrl = &quot;https://example.com/&quot;<br>}</pre><p>Without targets, we can achieve that using custom “Build Rules”, less popular tab in Xcode’s project, where you can specify how to process project files depending on their filename.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNfVcsJBgUJ7rrukqJEC9Q.png" /><figcaption>Adding custom Build Rule</figcaption></figure><p>When adding a custom Build Rule, you have to specify file pattern, a shell script to apply and what is the output file of your script. Then, Xcode during a compilation process will evaluate your script for files that match given pattern instead of a default behavior (e.g. compiling .swift files). <em>Please keep in mind that custom Build Rules have a precedence over the embedded rules — that gives us a chance to override the default compilation behavior.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yInLkUmBRtw09QC0AEksTw.png" /><figcaption>Custom Build Rule configuration screen</figcaption></figure><p>For our solution, we will follow the algorithm:</p><ul><li>include<strong> all</strong> versions of Configuration_X.swift into a single target</li><li>Xcode project specifies <strong>a dummy Build Rule</strong> that swallows files you want to skip (exclude from a build)</li><li>all other files (out of xxxxx_x.swift format) are processed as usual</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOUNKZuPOIQvN_Dn2D2q4A.png" /><figcaption>Overview of the file variant selection (Release build)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VjwX4mRoXvPutppx5R4pA.png" /><figcaption>Overview of the file variant selection (Debug build)</figcaption></figure><p>To control which files to swallow in a dummy Build Rule we will create a separate Xcode Configuration with User-Defined Setting CONFIGURATION_VARIANT (the setting name is of course up to you):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f_rAIkoWRXWn9Ko99mFyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxdQ2kEeTpC0rskl4WAoKw.png" /></figure><p>Above configuration means that for “Debug” configuration we would like to choose staging file variants with “S” postfix (xxxxx_S.swift) and for “Release” production with &quot;P” postfix (xxxxx_P.swift).</p><blockquote>There is plenty alternative options to specify User-Defined Build Setting, e.g. `buildsetting=value` argument for xcodebuild terminal command.</blockquote><p>Coming back to our newly created Build Rule, let’s specify that we want to manually process a subset of the project’s .swift files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sf1bM5ZEbhE8zX0MPEGPvQ.png" /></figure><ol><li>Process Swift files that end with a single-character postfix <strong>other</strong> than CONFIGURATION_VARIANT (please note that Xcode uses simple pattern matching rather than more powerful regular expressions here)</li><li>The script creates in a <strong>derived directory</strong> an empty file with _skipped postfix</li><li>Specify that Xcode should process just created empty file instead of an original one — here we technically consider the body of a file as empty.</li></ol><blockquote>Please note that we operate on a <em>$DERIVED_FILE_DIR</em> directory so given script creates a file in a build directory and doesn’t modify an original file, potentially under source control.</blockquote><p>As a result: no more multiple-targets, no more #if... #endif blocks, no runtime checks— Build Setting (e.g. specific for a Configuration) controls if a given file should be included or not.</p><p><em>A sample app that demonstrates it is available on </em><a href="https://github.com/polac24/ConfigurationCustomizationDemo"><em>GitHub</em></a><em>.</em></p><p>Finally, please note that this technique isn’t limited to .swift files. With a small modification of a Build Rule presented above, you may apply it for Objective-C files, images, assets or other data like .json files too.</p><h4>Summary</h4><p>Build Rules is a tool often underestimated and barely used by iOS/Mac developers. This post demonstrates how it can be useful to selectively include/exclude .swift files from a compilation process. Now we have another alternative to consider before immersing to the world of multiple-target projects or conditional-based code.</p><p><em>One limitation is that we can use only single-character postfix marker (like _A.swift, _B.swift, _1.swift etc.) as Xcode does not support glob or regex file matching in Build Rules tab. Feel free to duplicate </em><a href="https://openradar.appspot.com/radar?id=6063002872709120"><em>OpenRadar</em></a><em> suggestion that gives Build Rules more control on that.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9724cbabe821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stubbing in pair with Swift compiler]]></title>
            <link>https://medium.com/@londeix/stubbing-in-pair-with-swift-compiler-c951770a295b?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c951770a295b</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 12 Nov 2018 09:38:41 GMT</pubDate>
            <atom:updated>2019-05-13T14:34:50.845Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to quickly write unit test stub in Swift without code generation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7Wxn99zMGVBLxXBVf8POA.jpeg" /></figure><p>Often we need to unit test a code with side-effects that interact with other parts of your system by abstraction— protocols in Swift. There are many ways to verify if it works as expected: stubbing, spying, dummying etc. In general, engineers dubbed these forms as <strong>mocks</strong>, even “test double” is a legit name for that.</p><blockquote>FYI, “test double” name comes from “stunt double” in the film industry.</blockquote><p>Writing test doubles (like stubs or mocks) is a boring process in Swift and developers often try to generate it automatically by using tools like Sourcery/SwiftyMocky. However, if you wish to have more granular control or don’t want to introduce a new step to the build process, there is one trick to quickly (at least quicker) implement a test double.</p><h3>Side note: stubbing/mocking difference</h3><p><em>If you know how stubbing and mocking works, you can easily skip the following two chapters and jump to the next chapter or directly to the solution.</em></p><p>First, let’s distinguish what is the difference between stubs and mocks as they are quite similar. The fundamental difference sits in a verification process:</p><ul><li>for stubs, a test case has to <strong>manually </strong>call some methods to <strong>verify</strong> that expected side-effect happened</li><li>mocks <strong>make verification automatically</strong> using predefined configuration</li></ul><p>Let’s compare it in a pseudo-swift code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb39dc005978589fd5e298bd21d46ca/href">https://medium.com/media/bcb39dc005978589fd5e298bd21d46ca/href</a></iframe><p>CounterMock is preconfigured during initialization contrary to CounterStub where at the verification step we need to explicitly compare some addCalledTimes property to 3. The way these two test doubles are implemented is an implementation detail. The general rule of thumb is that <strong>verification</strong> distinguishes if we are using a stub or a mock (or mixed hybrid).</p><h3>Stubbing a function</h3><p>Let’s leave theoretical discussion off and go back to the ground. How actually a stub can be implemented in Swift? We want to create an object that conforms to a protocol with a chance to 1) verify if given functions have been called with the expected arguments and 2) control functions return values. <br>There are many approaches to do that, and the simplest is to introduce as many properties as behaviors we want to track into a stub. E.g. if you want to very that function has been called given times, add a counter, increment it in a function and after the test verify its value — as presented in the snippet above.<br>However, an alternative is to add an <strong>additional variable that provides a function placeholder</strong> (with almost the same signature type as the function) and call it when conforming to the protocol. <em>I wrote almost because we will make it optional just for convenience if a test case completely wants to ignore a given function.</em></p><blockquote>In this blog post, we will talk about protocol <strong>functions</strong> since variables are relatively simple to stub — just by introducing an instance.</blockquote><p>For the sake of this post, let’s think about the simplest protocol that synchronously saves a username to a database and returns a boolean to inform if a procedure succeeded or not. Its mock would look like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e100847dcebc4bcd215e005867cce9db/href">https://medium.com/media/e100847dcebc4bcd215e005867cce9db/href</a></iframe><p>For a function addUser, we introduced a variable addUserAction — a function that is evaluated every time addUser is called. Then, in a test scenario you can 1) verify that your system under test (testing code) indeed called that function and 2) emulate how database reacts (whether return true or false):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34ffc83f1eb3693531a6684afb596680/href">https://medium.com/media/34ffc83f1eb3693531a6684afb596680/href</a></iframe><blockquote>Generally speaking, by introducing addUserAction variable that matches functions arguments and return types, we let a test case to define a body of the relevant function of a protocol.</blockquote><p>By the way, if you don’t like optionality of addUserAction property you may continue with an equivalent implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afcde66e4ff12cf8b5b5c0221da0a812/href">https://medium.com/media/afcde66e4ff12cf8b5b5c0221da0a812/href</a></iframe><h3>Solution: inferred type</h3><p>In the stub presented above, we had to explicitly provide a type of addUserAction variable. For short functions, it seems to be an easy task but for ones that involve several arguments, closures, (re)throws, @autoclosure it may end up with a fight between you and the compiler. To overcome such burdensomeness, we can leverage Swift’s type inference system. The solution involves a global function that returns nil value of the same type as an argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d580c8f3854d7be28d38ad5bba82add5/href">https://medium.com/media/d580c8f3854d7be28d38ad5bba82add5/href</a></iframe><p>At first, it looks like a nonsense function but we will use it only to pull out T type, not its value.</p><p>Functions are first-class citizens in Swift, so we can pass a function as an argument to asNil to get a nil instance where Wrapped type matches the function type. In the example below, we have a variable addUserAction initialized as a nil value of the same type as our protocol’s function. That is exactly what previously we had to write down manually:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e646bb7fc9fe10013be92424784efe/href">https://medium.com/media/91e646bb7fc9fe10013be92424784efe/href</a></iframe><p><em>It is required to mark this variable a </em><em>lazy because referencing </em><em>addUser implicitly depends on </em><em>self, which cannot be accessed before full initialization.</em></p><p>Our Database protocol is very simple so the benefit is not so spectacular, but for extremely complicated function, the gain is significant. Like here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d51047b3aedeafbd2753409a20e649ae/href">https://medium.com/media/d51047b3aedeafbd2753409a20e649ae/href</a></iframe><p>Another benefit of this technique is that in case of protocol’s type modification we don’t have to touch stub’s implementation at all — the compiler will automatically update types.</p><h3>Summary</h3><p>We developers love concentrating on a real problem rather than spending time on boring and dummy tasks like implementing test doubles. Fortunately, Swift’s static type analyzer provides a handful tool — we can leverage it to auto-infer property type used in unit test stub implementation. Then, in a matter of seconds, we can have a stub ready to work, flexible and fully customizable in a test case.</p><p><em>I’d like to thank Mateusz Maćkowiak for inspiring me to write this post.</em></p><p><em>Edit (16th of November):</em></p><p>Some people wrote me that described approach has a downside: unit test does not explicitly verify which side effects are made and furthermore it requires to provide a fallback return value when a test case did not specify concrete xxxAction implementation (the ?? false part).<br>I agree, both arguments are true so if you share these concerns, let me present an alternative approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0acf1de108b249212439d0b8245815ec/href">https://medium.com/media/0acf1de108b249212439d0b8245815ec/href</a></iframe><p>Instead of asNil function, we will replace it with stub(of:), which behaves like implicitly unwrapped T.</p><blockquote><em>Starting with Swift 4.1, </em><em>ImplicitlyUnwrappedOptional </em><a href="https://swift.org/blog/iuo/"><em>has been reimplemented</em></a><em> but if you still remember it, you can think of </em><em>stub(of:) returning </em><em>T!.</em></blockquote><p>Unit test crashes in runtime if you call addUser(name:) before initialising addUserAction in a test case. As a benefit, 1) you have full control which side effects are allowed to be called (any non expected call to a stub crashes/fails a test) and 2) you don’t need to specify fallback return values.</p><p>Now, you have a choice. If you prefer to:</p><ul><li>never crash in unit tests -&gt; use asNil approach</li><li>have full control of side effects -&gt; use stub(of:).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c951770a295b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Watch out for protocol extensions in your Swift API (unit tests trap).]]></title>
            <link>https://medium.com/@londeix/watch-out-for-protocol-extensions-in-your-swift-api-unit-tests-trap-e28ad4ef3268?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28ad4ef3268</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 16:26:42 GMT</pubDate>
            <atom:updated>2018-04-23T16:26:42.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vch-T0O4TuPsLissfQn_NA.jpeg" /></figure><p>We all love protocol extensions, one of the most powerful element of protocol oriented programming (POP) in Swift. Despite their unquestionable benefits, there are some rare cases where you should avoid them. In this article, let me demonstrate a potential trap that your API consumer may fall into when trying to unit test a code that depends on some protocol extension function.</p><p><strong><em>Quick reminder: method dispatching</em></strong></p><p>In Swift we have three kinds of method dispatching: <em>static</em>, <em>vtable</em> and <em>message</em> dispatching. If you are not familiar with this terms, let me recommend a great post from <a href="https://www.raizlabs.com/dev/2016/12/swift-method-dispatch/">Riazlab’s</a>. In short, dispatching methods use different techniques to choose a concrete implementation of you function to execute if the same signature is defined in several places (e.g. parent class or protocol extension). <em>For instance, 1) having a class that inherits from </em><em>NSObject will always use message dispatching and 2) value types (structs, enums) will always use static dispatch.</em></p><p>OK, let’s go back to our dangerous scenario, where as an API creators (and we all are API designers, do you remember <a href="https://vimeo.com/234961067">presentation</a> by John Sundell?) we follow best practices and provide protocol abstraction for our public API. For the sake of this article, let’s assume we wish to expose a logger class that may log verbose and error messages, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e763cfe3e9d6ec1ca23b958a9afbf541/href">https://medium.com/media/e763cfe3e9d6ec1ca23b958a9afbf541/href</a></iframe><p>At glance it looks OK, but what if we wish to add a convenient API functions to log particular level? Protocol extension looks as a perfect match:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0928f8fb74ae8c7283a3064c765929bd/href">https://medium.com/media/0928f8fb74ae8c7283a3064c765929bd/href</a></iframe><p>So far so good. If we have some hypothetical API consumer where generic Logger abstraction is used in System class, it can directly call a method to log verbosely, like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f84bb9bd7c53026cb8f3f815644fa84d/href">https://medium.com/media/f84bb9bd7c53026cb8f3f815644fa84d/href</a></iframe><p>This works as expected, but let’s go over unit tests of a System class?</p><h3>Testing API protocol extensions</h3><p>Let us verify that our System actually logs a verbose message to a logger, every time we start it. Piece of cake. First we have to create a mock that conforms to a Logger protocol and keep track of all calls to verbose function. At the end, verify that verbose function has been called as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8663ee64da053871af902ae93d6777d1/href">https://medium.com/media/8663ee64da053871af902ae93d6777d1/href</a></iframe><p>It may be surprising for you, especially knowing that System actually logs a verbose message in a production code, but this test fails with a message:</p><blockquote><strong>XCTAssertEqual failed: (“[]”) is not equal to (“[“System started”]”)</strong></blockquote><h3>Failing scenario</h3><p>To understand what went wrong, we have to analyse dispatching method used to execute logger.verbose(message:) inside System.start(). System instance has a reference to a protocol Logger which provides function verbose in a <strong>protocol extension</strong>. By design Swift will <strong>always</strong> use static dispatch to call protocol extension’s implementation, no matter if actual implementation of a logger (LogMock in our case) implements verbose(_:String) or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yR0jiWbQTU6SrJsN_caXZA.png" /><figcaption>logger.verbose always calls a function from an extension due to static dispatch</figcaption></figure><p>One way to workaround it to verifying if LogMock.log(_:message) has been called correctly. It may seem like a rational idea at first, but but there’s an inherent problem with this approach —in System class tests, we have just began testing <strong>real</strong> verbose(message:) implementation from the API, written by a third-party developer. Potential implementation change or bug in Logger.verbose(_:String) could influence our test result. Unit test, as even name suggests, should validate the single unit of a code (here System class), in a highly isolated context.</p><h3>How to define API protocol correctly?</h3><p>Solution to this problem is really simple. As API designer all you have to do is to include all the functions/variables that you want to expose in a protocol extension into a main protocol definition, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a2ae1a210365fc5f4aa4668b45f37a/href">https://medium.com/media/d8a2ae1a210365fc5f4aa4668b45f37a/href</a></iframe><p>This changes a dispatching method of a verbose(message:) and error(message:) functions into <em>vtable</em> , which resolves an implementation in a runtime. As a result, our test scenario executes verbose(message:) from a LogMock implementation, as you would expect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbuEd-wM7ILEhxXRJSWrng.png" /><figcaption>Calling chain when verbose function is defined also in a protocol definition</figcaption></figure><h4>Customer flow</h4><p>Above fix is dedicated to API creators, but even if you don’t have access to modify protocol declaration, there is a remedy for your troubles. You’ll need to depend on your custom protocol that inherits from an original one and includes all declarations that API designer exposes only from protocol extension. In the meantime, while waiting for API designer’s fix, you are not blocked anymore.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/007669bca45d33cd2f18e055e20effc5/href">https://medium.com/media/007669bca45d33cd2f18e055e20effc5/href</a></iframe><h3>Summary</h3><p>We talked about protocol extensions and saw that testing a code that depends on a protocol extensions could be tricky. Fortunately, there is a really simple remedy for that — just include functions/variables definitions from a public protocol extension in your protocol definition. So when you hear yourself saying, “Let’s just implement it in a protocol extensions”, you’ll know it’s time to backpedal and ensure that static dispatch would not thwart customer’s unit tests.</p><p>For all their advantages, dynamic nature of <em>vtable</em> dispatching has some performance overhead comparing <em>static</em> one, which does not have to perform a table lookup. However, difference isn’t noticeable in most cases so it sounds as a reasonable tradeoff to make your API testable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28ad4ef3268" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top-down iOS error architecture]]></title>
            <link>https://medium.com/@londeix/top-down-error-architecture-d8715a28d1ad?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8715a28d1ad</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 22 Jan 2018 17:01:09 GMT</pubDate>
            <atom:updated>2019-04-27T18:17:34.020Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to handle errors in iOS apps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9u2nl55qXZvii16ptVVNNA.jpeg" /></figure><p>There isn’t a lot of articles about error handling in the iOS ecosystem, even this seems to be a non easy and substantial component of each app. Today, I wish to tackle this problem and present my solution towards less disruptive error handling in the iOS app.</p><h3>Initial state</h3><p>To ensure that we are on the same page, by <em>an error</em> I will mean an instance that conforms to Swift’s Error type and <em>error handling</em> is a reaction to it. These errors may arrive in a <strong>synchronous</strong> manner (disk operations, invalid argument) or <strong>asynchronously</strong> (no Internet connection, session token invalidated etc.). First group is obviously easier to deal, thanks to Swift’s standard do-catch structure. Very often, straightforward <strong>bottom-up</strong> procedure is sufficient, where an error breaks execution and it is automatically passed to a caller. If you have an asynchronous API with completion handler, developers are free to choose among plenty of techniques (to mention promises or RX streams) that also frequently follows the bottom-up model. In general bottom-up means that we propagate an error to our parent layer if we cannot handle it completely.</p><p>I found out that in many cases bottom-up direction is not a best approach and leads to a frustration when an error has to traverses plenty of layers up just to reach the one that is able to consume it. To give you an example, let’s assume that APIClient received 401 Unauthorised HTTP response, and your app should return to the initial login screen. Does it sound familiar for you to check if completion handler in a ViewModel is able to handle particular error, if not pass it to its Flow Coordinator, which then passes it to the parent(s) Flow Coordinator to finally reach to a generic place where you instruct the navigation controller to move back to the root. It ends up with a code that switches on an error extensively, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b271506d9ac115d816c424d439553e9/href">https://medium.com/media/2b271506d9ac115d816c424d439553e9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19wjfMSk_hQPA1FToiRDFw.png" /><figcaption>Bottom-up procedure</figcaption></figure><p>In case you chose delegate mechanism for a communication between distinguish elements, your delegate protocols may start to swell — every coordinator should include error events of its nested children. I observed that in many apps upper layers in a tree can handler only some specific errors (like session invalidated or unsupported API version) and below there is an aggregation point where all errors are presented to the UI (in a form of alert view or similar). So instead of starting from a bottom layer, I suggest reverting the propagation order, and start from the top layer and pass it down only when the parent layer wasn’t able to handle it.</p><blockquote>Note that in a root element we obtained a single aggregation point of all errors in the app what may be useful for analytics purpose.</blockquote><p>So, let’s will divide error handling process into two phases:</p><ul><li>Phase 1: propagate events up to its parent (unconditionally)</li><li>Phase 2: propagate event down, layer by layer to find one that can handle it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxdB86G49vJd5ps5G2XE7g.png" /><figcaption>Top-down error handling with Phase 1 (up direction) and Phase 2 (down)</figcaption></figure><blockquote>Such procedure is not a completely new idea, for instance JavaScript uses a very similar technique called <a href="https://medium.com/@pierreda/things-you-should-know-about-js-events-4ab474312736">bubbling event delegate</a> to dispatch touch events to DOM elements.</blockquote><h3>Protocol definition</h3><p>Implementation of a top-bottom error handling architecture is not a difficult task. Let me demonstrate you that you can easily implement it within 50 lines of code with a generic protocol oriented solution that is open for extensions.</p><blockquote>For the purpose of this article, I will use function names inspired by Swift’s keywords list (catch,throw, finally). While some of you may take it as a bit controversial, I believe such analogy helps understanding it.</blockquote><p>We will define the only one protocol, ErrorHandleable, that will be used as a node in an error-handling tree. Each instance keeps a reference to a parent layer used in the Phase 1 propagation and encapsulates a generic closure (HandleAction) used in the Phase 2, that decides whether it should be populated down or not (throws an error or not).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5841a3834d588ccaf105a4a1928332bd/href">https://medium.com/media/5841a3834d588ccaf105a4a1928332bd/href</a></iframe><p>API is very concise and consists of only two functions:</p><ul><li>throw is a function that begins handling an error (Phase 1) and receives an optional closure finally that is called after the handling process with an argument informing whether some layer did eventually handle it or not</li><li>catch receives an error (Phase 2) and decides if it should be populated down or not</li></ul><p>Take a look how could potential API call may look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d78131cd42f300d7cf907d740efb98/href">https://medium.com/media/52d78131cd42f300d7cf907d740efb98/href</a></iframe><blockquote>Note that when using this API, contrary to protocol definition, you don’t have to escape keyword-reserved names (like throw). Swift infers that we mean function instead of expression here.</blockquote><p>First, we built up a handling tree, where previousErrorHandler is some already existing handler received by some dependency inversion technique (e.g. dependency injection), and define two catch functions that potentially may handle an error. In a case that we observe an error in an asynchronous manner we throw it into our errorHandler instance to handle it. According to top-bottom procedure, it first climbs up into a root element, and then we visit all the nodes in the reversed order to finally find an element that completely consumed it (non-thrown action errorHandler#2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqIzLsEc_BtAc2CQ2BPXXg.png" /></figure><blockquote>In addition, nothing refrains from rewriting an error in an action block. Just throw completely new error (let’s say in errorHandler#1) and all beneath layers will observe modified one. However, remember that with great power comes great responsibility and use this capability with caution…</blockquote><p>This protocol API is very generic, so we can add some extensions for convenience usage:</p><ol><li>constraint caught errors into a generic type and transparently pass all others:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/182f348f41e0237919071cb868b57f69/href">https://medium.com/media/182f348f41e0237919071cb868b57f69/href</a></iframe><p>2. constraint caught errors into a single value (for a type conforming to Equatable protocol):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/129b1eafa57cc3afb8f446ae4b4ad278/href">https://medium.com/media/129b1eafa57cc3afb8f446ae4b4ad278/href</a></iframe><p>3. listen only for a particular type (or Equatable value) and <strong>never</strong> handle any error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06ae5e2e8e08bc8ceedda3551121cc9c/href">https://medium.com/media/06ae5e2e8e08bc8ceedda3551121cc9c/href</a></iframe><p>Sky is the limit for more protocol oriented extensions. For instance, you may add a function useful for synchronous API, that resembles do keyword — takes a throwing closure and begins a top-down handling in case of thrown error.</p><blockquote>Presented above protocol definition is rather a starting point that can be easily customised for you specific needs —for instance I can imagine a use-case where you wish to control also Phase 1 propagation…</blockquote><h3>One possible implementation</h3><p>Now, let’s try to create one possible implementation of ErrorHandleable — ErrorHandler. Root handler obviously contains no parent so its type has to be Optional and its default action is totally-transparent one that always propagates it down (functions are first-class citizens so nothing refrains us from introducing a default parameter in a signature):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ca58cc1e03d341a6a4d09009e4e7b8f/href">https://medium.com/media/8ca58cc1e03d341a6a4d09009e4e7b8f/href</a></iframe><p>Then, let’s provide an implementation of a required function throw, that accumulates an array with a path nodes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be52fb447e99ba7e83110220484630e8/href">https://medium.com/media/be52fb447e99ba7e83110220484630e8/href</a></iframe><p>When throw reaches the root node it performs Phase 2 by calling serve function which is also very simple: it calls an action and depending if it throws an error, passes it to a next element in a responsibility chain (next) or breaks it and calls finally closure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25ed92a60df9fb468e72cab2bd075431/href">https://medium.com/media/25ed92a60df9fb468e72cab2bd075431/href</a></iframe><p>The only one missing step is implementation for a catch function: it creates a child element with a defined action and current node defined as a parent:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23e6df21cf4cd1ed6312bd9ec81d2f44/href">https://medium.com/media/23e6df21cf4cd1ed6312bd9ec81d2f44/href</a></iframe><p>If you combine entire ErrorHandler implementation, it takes only 50 lines of code. Code implementation with all extensions is available <a href="https://gist.github.com/79da9649c68ee4cdc4ed5a7764c7eea3.git">here</a> for reference.</p><h3>Final results</h3><p>Having implementation of ErrorHandleable/ErrorHandler ready, we can take a look how would it look like in a real application, let’s say with MVVM+FC (Model-View-ViewModel + FlowCoordinator) architecture.</p><p>In a root ViewModel we instantiate ErrorHandler. Thanks to a fact that all errors within our app have to visit this node we have a perfect chance to automatically send it to our logging framework.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ffaae4d914d966b54756ac6a087d219/href">https://medium.com/media/0ffaae4d914d966b54756ac6a087d219/href</a></iframe><p>Once we have attached all the listeners, we pass rootError all the way down the view hierarchy, here RootCoordinator which does not handle nor listen for an errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d47ad03860bef23d1293d27918852665/href">https://medium.com/media/d47ad03860bef23d1293d27918852665/href</a></iframe><p>Let’s assume it&#39;s child coordinator LoggedInCoordinator <strong>can</strong> handle one specific error ApplicationError.sessionInvalidated and presents any other ApplicationError with an alert. To achieve it, in LoggedInCoordinator we have to keep a strong reference to a parent handler and every time our coordinator sets up a new child, it builds a new handler using computed variable errorHandler. I used computed variable since we cannot assign it once in the initialiser as it’s action references to self , not fully initialised at the initialisation yet. When defining closure-based action remember to always keep a <strong>weak</strong> reference to self, otherwise you may easily introduce retain cycle and memory leak.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acdd05e0c3a630d2fa67545054b41b6b/href">https://medium.com/media/acdd05e0c3a630d2fa67545054b41b6b/href</a></iframe><p>Once we obtained an error asynchronously while the app is running in ScreenViewModel, we start handling it by calling throw function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8523a109cb01f49e76e0fa76c825bab/href">https://medium.com/media/b8523a109cb01f49e76e0fa76c825bab/href</a></iframe><p>As a result we achieved a simple API where:</p><ol><li>entire error handling code is isolated in some parent element (here LoggedInCoordinator) and rest of a code does not care about it (unless it wishes to),</li><li>action handlers are type-safe,</li><li>code models native Swift syntax what improves its readability,</li><li>all hierarchy elements depend on a protocol ErrorHandleable, so isolating it for the sake of unit testing is not a problem.</li></ol><h3>Conclusions</h3><p>Standard approach for handling an error by propagating it up does not scale well and if your code contains a lot of layers (nested coordinators or controllers), communication between them may easily get our of control. With a presented above top-down approach, all the errors traverse in the reverse order — from a root to a child layer — so parent layer decides if it is able to handle given error and its children do not necessarily have to care about it.</p><p>Implementation of such top-down architecture is quick and straightforward so in my opinion there is no need to introduce any third-party library, even any μFramework. You benefit from a solution that perfectly meets your requirements and you get rid of one external dependency. Perfect win-win! If you want to see it in action, <a href="https://github.com/polac24/TopDownErrorSample">here is a very simple sample app</a>.</p><p>If you have any comments or any other error handling patterns to share, don’t hesitate to let me know on twitter <a href="https://twitter.com/norapsi">@norapsi</a>.</p><h3>PS1</h3><p>If you are wondering, what it has to do with a pinball game, here is an animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*afSnPAHMpJOcNAV2m1ccxQ.gif" /></figure><p>Thanks to Martyn Pękala and Jenus Dong for valuable suggestions.</p><p>Edit : Added <a href="https://github.com/polac24/TopDownErrorSample">github</a> sample project</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8715a28d1ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xcode unit tests with ⌘+S]]></title>
            <link>https://medium.com/@londeix/xcode-unit-tests-with-s-13f0deaed501?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/13f0deaed501</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Mon, 04 Dec 2017 18:07:52 GMT</pubDate>
            <atom:updated>2017-12-04T18:07:52.839Z</atom:updated>
            <content:encoded><![CDATA[<p>Practicing TDD using Xcode IDE can be a bit disruptive. Every time you introduce a small change in the implementation or test file, Xcode rebuilds entire project (fortunately using incremental build) and installs the app on a simulator. Depending which project configuration you have, it may take from a few to dozens of seconds. This article presents a way to bypass this long lasting procedure and automatically run unit test(s) whenever you save your implementation .swift file. We will leverage new feature of <a href="https://twitter.com/injection4xcode">John Holdsworth’s</a> “Injection for Xcode” app — support for auto-testing.</p><blockquote><strong>TLDR; <br></strong>InjectionTDD (together with InjectionForXcode) runs unit tests on a simulator environment without rebuilding nor reinstalling the app. Implementation and tests are injected into already-running host app, thus work almost in a real-time within a standard, well-known Xcode IDE. In addition, to speed-up testing process, InjectionTDD runs only a subset of test cases — these related to your just-updated implementation file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*VBXTgbOcK2F_SxYtGxzQ8Q.gif" /><figcaption>InjectionTDD in action.</figcaption></figure><h3>Goal</h3><p>It is crucial to get quick feedback whether your tests are passing (green) or failing (red) if you are making TDD, but not only then. Wouldn’t be nice to instantly know that your change/fix does not introduce any regression somewhere else? Or maybe you are covering your implementation with new test cases and it becomes frustrating to rebuild test target all over again? If you observe the same issues, InjectionTDD can save you a lot of time!</p><h3>Live updating</h3><p>Normally, to run unit test you have to wait for several steps like: building, linking, installing entire app and connecting Xcode with lldb server. Depending on your configuration it may take up to dozens of seconds. However, during development we quite often modify only one particular file and then observe the results. InjectionForXcode saves a ton of time by compiling <strong>updated file on-fly</strong> and replacing/swizzling its implementation in a live iOS process. Very similar approach can be applied for unit testing. This is how InjectionForXcode+InjectionTDD works in general:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZEJ17-7Lu3xx1hlU65wKw.png" /></figure><p>First, Xcode builds your test target, installs an app on a simulator and tries to perform first tests. However, dedicated framework called InjectionTDD, that you have to integrate into a test target, stalls test executions and keeps a runtime in a constant waiting loop.</p><p>Then, whenever you change something in Xcode, InjectionForXcode builds a slice of an application (only edited file + related unit tests) and injects it into already waiting “Hosting app”. At last, host app executes all tests and passes results back to the Xcode to presents them in its standard UI. Keep in mind that host app is not terminated afterwards and the entire process can be repeated all over again.</p><h3>Installation process</h3><p>Armed with theory background, let’s roll our sleeves up and play with it. You can start with any existing project with unit tests that is written in Swift or just try it out by pods command pod try InjectionTDD:</p><ul><li>Before any work, ensure that terminal command xcode-select -p points to the current Xcode version path. If not, assign correct version using -s option, like:<br>sudo xcode-select -s /Applications/YOUR_XCODE.app/Contents/Developer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*ZcQsAOXFeT8SXBbzOo5uTA.png" /></figure><ul><li>Install free “Injection for Xcode” app (remember to install version with <a href="http://johnholdsworth.com/InjectionTDD.app.zip">TDD support</a>) from <a href="http://johnholdsworth.com/injection.html">official site</a> and run it. <em>Note</em> <em>that application sits only in the tray.</em></li><li>Integrate InjectionTDD framework to your test target (CocoaPods, Carthage and manual installations <a href="https://github.com/polac24/InjectionTDD#2-integrate-injectiontdd-with-your-xcode-project">are supported</a>). If you use CocoaPods, it’s a single line change:</li></ul><pre>target &#39;YourAppTests&#39; do  <br>  pod &#39;InjectionTDD&#39;, &#39;~&gt; 0.5&#39;<br>end</pre><ul><li>Start your unit tests (⌘+U) <strong>on a simulator.</strong> After a while, Xcode console should print confirmation Connected to “Injection” plugin, ready to load x86_64 code:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*QJVzl5T3Ub-8g9WdhRDKng.png" /></figure><ul><li>We are ready to edit and save any of your implementation .swift file and click on “Inject Source” option in the Injection menu tray (or use shortcut ⌃=).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*_eYhUKHucrsOil-0q8rzpg.png" /></figure><p>InjectionForXcode starts magic and after a while you should see tests results in the console output and Test navigator (⌘+6) 🎉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ieVGW4FkXWmHWxXM4BtSaw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*uszZBdVyEYx1yHxM6VZo9w.png" /><figcaption>Live test navigator results</figcaption></figure><ul><li><em>Optionally</em>: you can enable “File Watcher” in the tray menu so that injection happens automatically, whenever you save a file. This is really handy.</li><li><em>Optionally</em>: by default test results are printed to the console, but if you want to also present notification summary (as below), install custom Xcode breakpoints to achieve the same result (see <a href="https://github.com/polac24/InjectionTDD#summary-notifications-installation">manual</a>):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*4J64DcNShOPEYpjUHIglpQ.png" /></figure><h3>How does it work under the hood?</h3><p>If you are interested in the implementation details, here are four stages that happen whenever you introduce a change to the implementation file:</p><ol><li>lookup of all test target files to find tests cases that directly call code from the implementation file: uses Swift’s metadata files .swiftdeps, (.swiftdeps describes which Swift symbols given file provides and depends on),</li><li>compile your swift project target using incremental build (commands are parsed from Xcode logs) and bundle it into a .framework,</li><li>send just compiled binary to the simulator process: iOS simulator app loads from a disk dynamic framework,</li><li>execute all XCTestCases on a simulator.</li></ol><h3>One tool fits all</h3><p>Contrary to Objective-C, which depends on message dispatching, Swift uses also static dispatch, what makes runtime method swizzling impossible. However, for InjectionTDD is not a case, where implementation and unit tests are bound together in a linking process so that unit tests always point to up-to-date implementation. In other words, XCTestCases are tightly coupled (by the time of compilation) with a unique type that is under test.</p><blockquote>Therefore, you can test all kinds of Swift types with all dispatching mechanisms: classes, final classes, structs, enums etc.</blockquote><h3>Best practices</h3><p>By default, InjectionTDD framework stalls execution of all tests and waits for injected tests. This is intended during development, but on a CI machine we want to normally execute all tests and never expect any injected tests. If you are afraid that integrating InjectionTDD framework only locally is an overkill, there is a remedy. You can control test execution (whether run them normally or wait for injection) by special flag in a scheme environment variable calledINJECTION_TDD_SKIP. If you set it to TRUE, all your unit tests will execute as normal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*pPxs5j6XvzkTFOrydza_Xw.png" /></figure><p>Therefore, it is recommended to keep at least two schemes committed to a repo:</p><ol><li>Used for building, where INJECTION_TDD_SKIP=TRUE</li><li>TDD development only (disabled INJECTION_TDD_SKIP env.)</li></ol><p>Your CI building script always use the first scheme, developers may switch to the latter one while coding.</p><blockquote><strong>Hint:</strong> to speed up entire injection process, development TDD scheme (2.) shouldn’t gather Code coverage. It can cut off couple of precious seconds.</blockquote><h3>Summary</h3><p>“Injection for Xcode” is a powerful and popular tool for live-updating your application in a runtime, especially when mastering UI details. Nowadays, it supports also unit testing in real-time that saves a lot of time and provides great integration with Xcode IDE.</p><p>Installation is really straightforward: download <a href="http://johnholdsworth.com/injection.html">Injection app</a>, integrate <a href="https://github.com/polac24/InjectionTDD#--integration-using-cocoapods">CocoaPod</a>s or <a href="https://github.com/polac24/InjectionTDD#--integration-using-carthage">Carthage</a> library to your test target and get ready for <strong>great TDD experience</strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13f0deaed501" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nobody expects Completion Inquisition!]]></title>
            <link>https://medium.com/@londeix/nobody-expects-completion-inquisition-170fd08f8783?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/170fd08f8783</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Sat, 30 Sep 2017 11:05:30 GMT</pubDate>
            <atom:updated>2017-10-06T04:29:30.671Z</atom:updated>
            <content:encoded><![CDATA[<p>How to test non-called completion handler scenario</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1XeDuYpKtUyd3JaZ1lPpQ.jpeg" /></figure><p>Testing completion-handler API happy path scenario is really simple with XCTestExpectation. Things get complicated if your test case has to verify whether given <strong>handler was not called</strong>. It is still straightforward if it’s called synchronously after some other event that you emulate. But how about a case where execution is deferred in time? In this article, I will demonstrate you a solution to achieve 100% sure that given completion handler will never be called — fast and reliable.</p><h3><strong>Problem statement</strong></h3><p>Let’s talk about unit tests of some asynchronous task that provides completion handler — let’s say downloading JSON from a server. It seems obvious that we have to verify if a completion is called in a happy-path scenario. XCTest has nice API for that: just create an expectation, fulfil it in a completion and wait for all fulfillments at the end of a test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd30397231d2f65ae9becb540a561ef0/href">https://medium.com/media/fd30397231d2f65ae9becb540a561ef0/href</a></iframe><p>I am pretty sure you saw such kind of tests plenty of times.</p><p>However, I don’t see that much test scenarios where we check that something did <strong>not</strong> happen. One example regards initiating download task that is invalidated/cancelled before it actually finishes (succeeds or fails with an error). At glance, there is nothing wrong with simple XCTFail() in a completion that shouldn’t be called. In case something was wrong (presumably due to a bug), we will have a change to fail current test and see red test in Xcode or CI. But is it really enough? What would happen if our Downloader defines@escaped callback and calls its later e.g. in DispatchQueue.async block?</p><h4>Deferred execution of unexpected handler (Completion Inquisition)</h4><p>Just to remind you, unit test always uses main thread to operate and after it reaches the end of a function, it is immediately classified as failed (red) or passed (green). Therefore, deferred execution of XCTFail() does actually log some failure but Xcode is not able to determine which previous test it actually corresponds to.<strong> If you are lucky, you will see errors inXcode console, but your entire test will be still green</strong>:</p><pre>Test Suite &#39;All tests&#39; passed at 2017-09-05 18:44:31.858.</pre><pre>Executed 3 tests, with 0 failures (0 unexpected) in 0.209 (0.215) seconds</pre><pre>2017-09-05 18:44:31.865211+0200 NotCalledUnits[66089:3985807] *** Assertion failure in void _XCTFailureHandler(XCTestCase * _Nonnull, BOOL, const char * _Nonnull, NSUInteger, NSString * _Nonnull, NSString * _Nullable, ...)(), /Library/Caches/com.apple.xbs/Sources/XCTest_Sim/XCTest-13188/Sources/XCTestFramework/Core/XCTestAssertionsImpl.m:41</pre><pre>2017-09-05 18:44:31.866778+0200 NotCalledUnits[66089:3985807] *** Terminating app due to uncaught exception &#39;NSInternalInconsistencyException&#39;, reason: &#39;Parameter &quot;test&quot; must not be nil.&#39;</pre><pre>*** First throw call stack:</pre><pre>(</pre><pre>0   CoreFoundation                      0x000000011184626b __exceptionPreprocess + 171</pre><pre>1   libobjc.A.dylib                     0x000000010dfa4f41 objc_exception_throw + 48</pre><pre>2   CoreFoundation                      0x000000011184b402 +[NSException raise:format:arguments:] + 98</pre><pre>3   Foundation                          0x000000010da81bd3 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 165<br>...<br>...<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnJPILmAi4IO6SIicahYVQ.png" /><figcaption>Isn’t it misleading? Succeeded test with a failed assertion in a console…</figcaption></figure><h4>Naive solution</h4><p>Another approach is to wait <em>a bit</em> and assume that as long completion did not pop up within, let’s say 0.1s, is will never be executed. It has two obvious cons:</p><ul><li>You have to guess how long to wait. Should it be 0.1s or 0.01s? If you set it incorrectly, it can easily end up with invalid or unstable tests.</li><li>It increases single test duration which by default should be as quick as possible by default.</li></ul><p>Both drawbacks may lead to a dangerous trap:</p><blockquote>When your tests take too long or are unstable, your teammates (or future you) start ignoring them and sooner or later just ditch them.</blockquote><h3>One possible solution</h3><p>Let me ask you a question: when do you have 100% sure that some external part of your system will never call a completion? Answer: <strong>In a case when no one keeps holds a completion block anymore!</strong></p><blockquote>To verify that nothing deferred execution of a block, we have to ensure that all other instances lost reference to a completion. OK, Sounds easy!</blockquote><p>But how to implement it? Of course we cannot define weak reference to a block: ‘weak’ may only be applied to class and class-bound protocol types. So, let’s define simple class ReferenceObserver that just notifies its deinit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e09b0cd6956c9b19bb1a00e78782ba6e/href">https://medium.com/media/e09b0cd6956c9b19bb1a00e78782ba6e/href</a></iframe><p>Then, let’s modify a bit our previous test: initalize observer , bind its deallocation handler to fulfilling XCTest expectation (line 4) and <strong>capture reference inside our unexpected completion handler (line 8)</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c27c32294be22134fa508f7594dfacd/href">https://medium.com/media/3c27c32294be22134fa508f7594dfacd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*YF0QRgLoKq6ZcdkfSzFvWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*6Ss2dJpFXN6Vi6R1VlHYWQ.png" /></figure><p>At the moment we have exactly two references to our ReferenceObserver instance: reference and capturedReference (in a completion). <em>Note: we had to add dummy assignment to an anonymous variable </em><em>_, otherwise Swift would not capture it at all.</em></p><p>As you can expect, let’s get rid of one of helper reference (just callreference = nil) and voilà:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*bCKHETh7-gbzG9HFCQONgw.png" /></figure><p>Only completion handler block keeps reference to ReferenceObserver and once completion handler is removed from a memory, deinitCompletion expectation automatically becomes fulfilled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*v9y1nQy_Qk6UpH7mIQt4gA.png" /><figcaption>Deallocation of completion handler automatically calls deinitCompletion.fulfill().</figcaption></figure><p>Here is our final test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b200dacb9d16f9de788d1b6cfe31c19/href">https://medium.com/media/3b200dacb9d16f9de788d1b6cfe31c19/href</a></iframe><p>We ended up with a solution that:</p><ul><li>does not unnecessary increase test duration because waitForExpectations quits immediately, after ReferenceObserver deinit.</li><li>ensures that completion will never be called.</li></ul><p><em>You may be wondering, what does </em><em>0.1s mean at the end of this test? It is just a </em><strong><em>maximum</em></strong><em> interval you let </em><em>Downloader instance to clear its handler reference.</em></p><h4>Alternative notation</h4><p>If you are like me, and you don’t like optionals in your codebase even in your unit tests, you can leverage additional scope to get rid of ReferenceObserver? optional type. <em>Did you know that you can create a </em><em>do section without any </em><em>catch, and it creates only an extra scope?</em> If we init our ReferenceObserver in a dedicated scope, its reference will be deleted at the end of it and thus we can remove an optionality. Once //Arrange section ends, the only one reference to an observer will be attached to a downloader. Below notation is equivalent to a previous code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/896473249ccec91b29fa6696639fdb51/href">https://medium.com/media/896473249ccec91b29fa6696639fdb51/href</a></iframe><p>The price that we have to pay here is readability. Some developer, non familiar with an empty do scope construction, may not understand what and why it actually occurs here. Therefore, despite my general reluctance to an optional, I would choose previous notation with ReferenceObserver?due to its readability and clearness.<br>What is your opinion on this? Do you agree with me? You can comment below or catch me on twitter, <a href="https://twitter.com/norapsi">@norapsi </a>.</p><p><strong>Sidenote</strong><br>At the end, let me here remind another golden rule about writing unit tests:</p><h3>Every time you write a test, verify that if you modify implementation to simulate a potential bug, your tests will actually fail!</h3><p><em>BTW. Such modified test is called a </em><strong><em>mutation test</em></strong><em>.</em></p><p>This is especially important for described above solutions. Please keep in mind that if you don’t correctly capture ReferenceObserver reference within a block, test may succeed false-positively. <br>If you are really afraid of it, you can add for instance an extra guard to a ReferenceObserver implementation and let it notify about deinit only after an explicit point in a test or manager reference lifetime by introducing extra scope using do{}. I would rather suggest to stick with a good-practice approach rather than adding an extra code. If you are interested, sample test with a safe-guard is <a href="https://gist.github.com/polac24/5de6a79a3c48e140304fb10abcb18cfe">available in this gist</a>.</p><h3><strong>Summary</strong></h3><p>Presented solution suits very well for verifying “not-called” scenario that is fast and reliable. You may also find it useful to check whether something still keeps a reference to a block (with no reason) and potentially introduces memory leak.</p><p>Within couple of lines required to implement ReferenceObserver, you are finally sure that a given block will never be called without any delay. So now you can add this technique into you developer toolbox and protect yourself from unexpected Completion Inquisition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=170fd08f8783" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Listing all cases in an enum]]></title>
            <link>https://medium.com/@londeix/listing-all-cases-in-an-enum-3b057f2c1432?source=rss-455e6a104b5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b057f2c1432</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Bartosz Polaczyk]]></dc:creator>
            <pubDate>Tue, 29 Aug 2017 21:10:17 GMT</pubDate>
            <atom:updated>2018-03-19T17:59:04.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTyIwivV9npR_mHebgpHyA.jpeg" /></figure><h4>Safety over simplicity</h4><p>Swift language was designed with a focus on “safe by default” approach (do not confuse with “safe by design” — Swift does not prevents you from doing dangerous actions but only encourages for good practices). One of such incentive is a great support for sum and product data types, enum and struct, respectively. These types are great to limit number of potential states during compilation time so we don’t have to write any unit tests of cases that should never occur — you definitely prefer to never reach given state, rather than covering it with an obvious unit test.</p><h3>Problem statement</h3><p>Despite enums are super-powerful feature in our toolbox, you may find out that there is no simple and safe way to list all cases in an enum (I mean an enum without associated values, of course). I run into a problem of presenting UI picker with all potential states (modelled as an enum) that user could choose from. I needed just an array but Swift does not provide it out-of-the-box and <a href="https://github.com/apple/swift-evolution/pull/114">swift-evolution proposal is still waiting</a> for its turn for a review (detailed discussion and its history is available <a href="https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006876.html">here</a>).</p><h3>Workarounds</h3><p>Very often, Swift community suggests two workarounds to solve my problem (inspiration comes from <a href="https://theswiftdev.com/2017/01/05/18-swift-gist-generic-allvalues-for-enums/">https://theswiftdev.com/2017/01/05/18-swift-gist-generic-allvalues-for-enums/</a>):</p><ul><li>make an enum representable by Int and increment a counter until you cannot anymore create a case:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e444c334b25c14673863a7ff47da6561/href">https://medium.com/media/e444c334b25c14673863a7ff47da6561/href</a></iframe><ul><li>cast raw memory representation into an enum case</li></ul><p>Both of those workarounds are not ideal: first assumes that developer assigns subsequent values (starting from 1 here) for all enums, while second solution may break when Swift changes enum memory representation (we still lack ABI stability in Swift).</p><p>In this post I wish to present another technique to list all of enum cases that is safe and independent of Swift implementation details .</p><p><strong>TLDR;</strong><br><em>To achieve that we can define dedicated </em><em>RawRepresentable type for your enum and make this type expressible by </em><em>String or </em><em>Int literal. Keep in mind that if we try to initialise an enum using </em><em>init(rawValue:), Swift takes all values of your </em><em>RawRepresentable (that have corresponding case) one by one and compare it with your </em><em>rawValue until finding equal value. Therefore, if we try to initialise with some </em><em>rawValue that does not match any case, we will have a chance to gather all rawValues with corresponding enum inside </em><em>== operator implementation.</em></p><h3>Dedicated RawRepresentable type</h3><p>Let’s define our goal: find an array with all cases of BestEnum that is represented by aString value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01b1c510c2ed7bfb4dc15bd8369fb804/href">https://medium.com/media/01b1c510c2ed7bfb4dc15bd8369fb804/href</a></iframe><p>Keep in mind that enum BestEnum: String is actually just a syntactic sugar for conforming to RawRepresentable protocol with RawValue = String. Let’s see how could we implement it manually:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9028523d49da178cfb1d2406a5447cef/href">https://medium.com/media/9028523d49da178cfb1d2406a5447cef/href</a></iframe><blockquote>We all love language features that generate boilerplate for us (other examples include: Codable protocol in Swift 4 and so awaited <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md">auto-synthesized </a><a href="https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md">Equatableconformance in Swift 5</a>).</blockquote><p>Unfortunately, for auto-conforming to RawRepresentable we can only use String or Int rawValues. If you try to use there your own type (let’s say enum BestEnum: TypeToBeAutoRepresentable), Swift compiler complains with:</p><blockquote><strong>raw type ‘TypeToBeAutoRepresentable’ is not expressible by any literal</strong></blockquote><p>Error message is actually a great hint and reveals that my previous statement that “<em>only </em><em>String and </em><em>Int are possible</em>” was invalid — it is enough that your type <strong>has to be expressible by a literal.</strong></p><p>Fair enough, let’s define our new type that meets this requirement and call itBestEnumRaw. It has no special logic — it just stores String literal as a property value and allows to initialize it with no argument (I will discuss later why do we need dummyinit()):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/629f6e2f49630d023d9086ba0e76f3e6/href">https://medium.com/media/629f6e2f49630d023d9086ba0e76f3e6/href</a></iframe><p>If we now try to use this struct as a raw representation(enum BestEnum: BestEnumRaw), swift compiler still complains:</p><blockquote><strong>‘BestEnum’ declares raw type ‘BestEnumRaw’, but does not conform to RawRepresentable and conformance could not be synthesized</strong></blockquote><p>On the other hand, this error message is a bit misleading: our BestEnumRaw actually conforms to RawRepresentable, why does Swift suggest that conformance cannot be synthesized? Solutions is really simple: let’s conform to Equatable protocol and the error goes away:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1be59e275dcc18983e96071e05e52ed/href">https://medium.com/media/f1be59e275dcc18983e96071e05e52ed/href</a></iframe><p>So far, so good. Our code compiles and definition of our enum is self-explanatory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ef6d55462bd81d9a15042e0d73b029d/href">https://medium.com/media/0ef6d55462bd81d9a15042e0d73b029d/href</a></iframe><p>Here comes a trick: let’s think what happens if you try to initialise BestEnum with some BestEnumRaw, let’s sayBestEnum(rawValue: BestEnumRaw())? Inference type says that a result of this expression is BestEnum?, so result of this expression should return someBestEnum case or nil, when provided rawValue does not correspond to any case. One may ask: how does Swift check if a given rawValue corresponds to an existing case? It just iterates over all cases and checks if its representable is equal to the value provided in an initialiser. Don’t be scared, it’s really simple. In our case it checks if:</p><ul><li>BestEnumRaw() == BestEnumRaw(stringLiteral:&quot;my_case&quot;) ?</li><li>BestEnumRaw() == BestEnumRaw(stringLiteral:&quot;other_case&quot;) ?</li></ul><blockquote><em>Now it makes sense why does compiler complain when </em><em>BestEnumRaw does not conform to </em><em>Equatable protocol — otherwise it wouldn’t be able to compare both </em>RawRepresentables<em> and therefore impossible to create an </em><em>enum with </em><em>init(rawValue:).</em></blockquote><p>Of course both comparisons return false so our initialiser fails and returnsnil. Nevertheless, we had a chance to catch all possible BestEnumRaw instance that actually have corresponding enum case. Ha! By having a list of all instance of raw representation, it is so trivial to create a list of all enum cases!</p><h3>Catching all rawValues</h3><p>So let’s add static variable all to our enum as a bucket for all rawValues:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56f1a6442a1b67f836aaf598233f4738/href">https://medium.com/media/56f1a6442a1b67f836aaf598233f4738/href</a></iframe><p>and fill it whenever Swift observers comparison of non-trivialBestEnumRaw:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c115265045d71f36c05c2a755e53d79f/href">https://medium.com/media/c115265045d71f36c05c2a755e53d79f/href</a></iframe><blockquote>Do you remember that we have a dummy initializer of BestEnumRaw? Thanks to that if rawString == nil we know that it was not initialized from any literal so does not correspond to any enum.</blockquote><p>Implementation is ready: we just need to call dummy initializer BestEnum(rawValue: BestEnumRaw()) and BestEnum.all contains String values of all cases 🎉</p><blockquote>If you want to achieve an array of actual cases instead of Strings, just map them to a raw object and later flatMap to an enum.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/148cba687094494138d35cdbe0562612/href">https://medium.com/media/148cba687094494138d35cdbe0562612/href</a></iframe><h3>Skip boilerplate code with third-party library</h3><p>Solution described above is straightforward and you can implement it within couple of minutes for your enum (have a look on <a href="https://gist.github.com/polac24/64a4d5e6cef873428df58df8bb1f532e">gist</a> for a final code). However, if you feel it is cumbersome to implement custom RawRepresentable type for each enum, you can use third-party library <a href="https://github.com/polac24/EnumList">EnumList</a> that does it for you. EnumList provides generic struct that you can use as a RawRepresentable. Let me show you how we can define our sample BestEnum for EnumList:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2115d2a4f13a0546f8f033cec4cfa19/href">https://medium.com/media/b2115d2a4f13a0546f8f033cec4cfa19/href</a></iframe><p>Just use EnumListStringRaw&lt;T&gt; (or EnumListIntRaw&lt;T&gt;) as raw representable, where T defines a bucket struct to keep all rawValues. I suggest nested struct Values into your enum, so that fetching all values expression is self-explanatory: BestEnum.Values.all.</p><blockquote>If you need to parse your enum into/from JSON, EnumList works perfectly with <em>Codable</em> protocol.</blockquote><p><a href="https://github.com/polac24/EnumList">polac24/EnumList</a></p><h3><strong>Summary</strong></h3><p>This post describes how to solve particular problem to list all enum cases, which Swift does not provide out-of-the box. Even if you hardly ever need to use it, my aim was to encourage you to find some non-obvious workarounds before compromising Swift safety.</p><p>If you think that enum with incrementing Int rawValue is easier to implement, I want to warn you that it works nicely only for Int representation and it can be a trap for new developers not aware of continuous rawValues requirement. On the other hand, playing with withUnsafePointer is <a href="https://www.mikeash.com/pyblog/friday-qa-2017-08-11-swiftunmanaged.html">quite dangerous</a> since compiler will not warn us if something has changed with in-memory representation— in such a case application would crash during runtime or worse.</p><p>Think twice if you ever have to compromise —<strong> <em>Compilation-time</em> safety first!</strong></p><h4>Update (03/19/18):</h4><p>Great news! Swift 4.2 will include out-of-the box solution with auto-conformance for CaseIterable protocol that provides allCases colletion. Credits go to Robert Widmann for implementing <a href="https://github.com/apple/swift/commit/dac06898e94b24b5a6b83533d2e0bae356a64529">SE-0194</a>.</p><p>More info <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0194-derived-collection-of-enum-cases.md">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b057f2c1432" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>