<rss version="2.0">
  <channel>
    <title>Figure</title>
    <link>https://figure.ink/</link>
    <description></description>
    
    <language>en</language>
    
    <lastBuildDate>Sun, 08 Aug 2021 01:00:00 -0500</lastBuildDate>
    <item>
      <title>What to Do with Localized Errors</title>
      <link>https://figure.ink/2021/08/08/what-to-do.html</link>
      <pubDate>Sun, 08 Aug 2021 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2021/08/08/what-to-do.html</guid>
      <description>&lt;p&gt;&lt;a href=&#34;http://www.figure.ink/blog/2021/7/18/practical-localized-error-values&#34;&gt;Last week&lt;/a&gt; we found the easiest way to retrieve localized context from an error. This gives us three values to play with:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Description&lt;/li&gt;
&lt;li&gt;Failure Reason&lt;/li&gt;
&lt;li&gt;Recovery Suggestion&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;But how do we use these to effectively communicate an error to our users?&lt;/p&gt;
&lt;p&gt;To figure it out, we should start by looking at the invariant — the one thing out of our power to control; the values native frameworks give to &lt;em&gt;their&lt;/em&gt; errors. Here’s a small list:&lt;/p&gt;
&lt;h2 id=&#34;apple-framework-examples&#34;&gt;Apple Framework Examples&lt;/h2&gt;
&lt;h3 id=&#34;network-connection-without-entitlement&#34;&gt;Network Connection without Entitlement:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Description:&lt;/strong&gt; ‘The operation couldn’t be completed. Operation not permitted’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reason:&lt;/strong&gt; ‘Operation not permitted’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recovery:&lt;/strong&gt; N/A&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;network-timeout&#34;&gt;Network Timeout:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Description:&lt;/strong&gt; ‘The request timed out.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reason:&lt;/strong&gt;&lt;em&gt;N/A&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recovery:&lt;/strong&gt;&lt;em&gt;N/A&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;network-is-offline&#34;&gt;Network is Offline:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Description:&lt;/strong&gt; ‘The Internet connection appears to be offline.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reason:&lt;/strong&gt;&lt;em&gt;N/A&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recovery:&lt;/strong&gt;&lt;em&gt;N/A&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;file-not-found&#34;&gt;File Not Found:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Description:&lt;/strong&gt; ‘The file “hello” couldn’t be opened because there is no such file.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reason:&lt;/strong&gt; ‘The file doesn’t exist.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recovery:&lt;/strong&gt;&lt;em&gt;N/A&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;bad-file-url&#34;&gt;Bad File URL:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Description:&lt;/strong&gt; ‘The file couldn’t be opened because URL type http isn’t supported.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reason:&lt;/strong&gt; ‘The specified URL type isn’t supported.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recovery:&lt;/strong&gt;&lt;em&gt;N/A&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&#34;file-exists&#34;&gt;File exists:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Description:&lt;/strong&gt; ‘“hello” couldn’t be copied to “Users” because an item with the same name already exists.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reason:&lt;/strong&gt; ‘A file with the name “hello” already exists.’&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Recovery:&lt;/strong&gt; ‘To save the file, either provide a different name, or move aside or delete the existing file, and try again.’&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&#34;localized-lessons&#34;&gt;Localized Lessons&lt;/h2&gt;
&lt;p&gt;The first thing we learn is that these values are not supported equally across Apple’s libraries. While there’s always a description present, the recovery suggestion in particular is rarely used.&lt;/p&gt;
&lt;p&gt;But we do see a pattern. Generally, the failure reason (when present) provides a short and conscience explanation of the error. Quick and to the point.&lt;/p&gt;
&lt;p&gt;The description often restates the failure, but goes more in-depth. It might identify the particular error or some of the values involved, for example.&lt;/p&gt;
&lt;p&gt;Finally, if the error is specific enough that a workaround can be assumed by the library author, that is written up and given in the recovery suggestion.&lt;/p&gt;
&lt;h2 id=&#34;hi-alert&#34;&gt;Hi, Alert&lt;/h2&gt;
&lt;p&gt;These usages suggest an easy mapping with the standard Alert dialog.&lt;/p&gt;
&lt;p&gt;First we &lt;a href=&#34;http://www.figure.ink/blog/2021/7/18/practical-localized-error-values&#34;&gt;cast the incoming error as an &lt;code&gt;NSError&lt;/code&gt;&lt;/a&gt;. Then we derive a title from its failure reason (or substitute a default title in case there’s no reason specified):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let bridge = myError as NSError

let title = 
  bridge.localizedFailureReason 
  ?? &amp;quot;An Error Occurred&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we take the description and the recovery suggestion (if it exists) and create a message body by joining them together with a space between:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let message = [
  bridge.localizedDescription,
  bridge.localizedRecoverySuggestion,
]
.compactMap { $0 }
.joined(separator: &amp;quot;\n\n&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that we don’t need to give a default here. The localized description of an &lt;code&gt;NSError&lt;/code&gt; will never be empty. And if there’s no recovery suggestion, we just don’t add it.&lt;/p&gt;
&lt;p&gt;Once we have a our title and message, we can pass them along to our alert controller:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let alert = UIAlertController(
  title: title, 
  message: message, 
  preferredStyle: .alert
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we present it, it’ll look something like:&lt;/p&gt;
&lt;img src=&#34;https://pub.figure.ink/img/localized_errors/example.png&#34; width=&#34;220&#34;&gt;
&lt;h2 id=&#34;breaking-with-tradition&#34;&gt;Breaking with Tradition&lt;/h2&gt;
&lt;p&gt;To some long-time Cocoa developers, this may look a little strange. After all, AppKit provides a &lt;code&gt;presentError(_:)&lt;/code&gt; method on &lt;code&gt;NSWindow&lt;/code&gt; that uses the description as the &lt;em&gt;title&lt;/em&gt; and only renders a message if there’s a recovery suggestion given:&lt;/p&gt;
&lt;img src=&#34;https://pub.figure.ink/img/localized_errors/cocoa.png&#34; width=&#34;300&#34;&gt;
&lt;p&gt;Why not adopt this style ourselves? We’ll talk about this more next week when we dissect how to write a good error.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Practical Localized Error Values in Swift</title>
      <link>https://figure.ink/2021/07/18/practical-localized-error.html</link>
      <pubDate>Sun, 18 Jul 2021 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2021/07/18/practical-localized-error.html</guid>
      <description>&lt;p&gt;How many times have we stared at code like:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;do&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;try&lt;/span&gt; writeEverythingToDisk()
} &lt;span style=&#34;color:#66d9ef&#34;&gt;catch&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; error {
  &lt;span style=&#34;color:#75715e&#34;&gt;// ???&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;or even:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; result {
&lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; .failure(&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; error):
  &lt;span style=&#34;color:#75715e&#34;&gt;// ???&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;and asked ourselves “How am I going to communicate that error?”&lt;/p&gt;
&lt;p&gt;The thing is, that error likely contains a lot of information that could help us out. But getting to it is not always straight forward.&lt;/p&gt;
&lt;p&gt;To see why, let’s look at the techniques at our disposal for attaching information to errors.&lt;/p&gt;
&lt;h2 id=&#34;the-new-localizederror&#34;&gt;The New: &lt;code&gt;LocalizedError&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;In Swift we pass around errors that conform to the &lt;code&gt;Error&lt;/code&gt; protocol. The &lt;code&gt;LocalizedError&lt;/code&gt; protocol inherits from this and extends it with some useful properties:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;errorDescription&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;failureReason&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;recoverySuggestion&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;By conforming to &lt;code&gt;LocalizedError&lt;/code&gt; instead of &lt;code&gt;Error&lt;/code&gt; (and providing an implementation for these properties), we can stuff our error with a bunch of useful information that can be communicated at runtime (NSHipster goes &lt;a href=&#34;https://nshipster.com/swift-foundation-error-protocols/&#34;&gt;&lt;em&gt;way&lt;/em&gt; more in-depth on this&lt;/a&gt;):&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;enum&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;MyError&lt;/span&gt;: LocalizedError {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; badReference

  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; errorDescription: String? {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;self&lt;/span&gt; {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; .badReference:
      &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;The reference was bad.&amp;#34;&lt;/span&gt;
    }
  }
    
  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; failureReason: String? {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;self&lt;/span&gt; {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; .badReference:
      &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Bad Reference&amp;#34;&lt;/span&gt;
    }
  }

  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; recoverySuggestion: String? {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;self&lt;/span&gt; {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; .badReference:
      &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Try using a good one.&amp;#34;&lt;/span&gt;
    }
  }
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;the-old-userinfo&#34;&gt;The Old: &lt;code&gt;userInfo&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;Good old &lt;code&gt;NSError&lt;/code&gt; provides a &lt;code&gt;userInfo&lt;/code&gt; dictionary that we can fill with anything we want. But it also provides some predefined keys:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;NSLocalizedDescriptionKey&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;NSLocalizedFailureReasonErrorKey&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;NSLocalizedRecoverySuggestionErrorKey&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We might note these are very similar in name to the properties &lt;code&gt;LocalizedError&lt;/code&gt; provides. And, in fact, they perform a similar role:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; info = [ 
  NSLocalizedDescriptionKey:
    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;The reference was bad.&amp;#34;&lt;/span&gt;,
  NSLocalizedFailureReasonErrorKey:
    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Bad Reference&amp;#34;&lt;/span&gt;,
  NSLocalizedRecoverySuggestionErrorKey:
    &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Try using a good one.&amp;#34;&lt;/span&gt;
]

&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; badReferenceNSError = NSError(
  domain: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;ReferenceDomain&amp;#34;&lt;/span&gt;, 
  code: &lt;span style=&#34;color:#ae81ff&#34;&gt;42&lt;/span&gt;, 
  userInfo: info
)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;So seems like &lt;code&gt;LocalizedError&lt;/code&gt; and &lt;code&gt;NSError&lt;/code&gt; ought to be mostly interchangeable then, right? Well, therein lies the rub.&lt;/p&gt;
&lt;h2 id=&#34;the-old-meets-the-new&#34;&gt;The Old Meets the New&lt;/h2&gt;
&lt;p&gt;See, &lt;code&gt;NSError&lt;/code&gt; implements &lt;code&gt;Error&lt;/code&gt;, but &lt;em&gt;not&lt;/em&gt; &lt;code&gt;LocalizedError&lt;/code&gt;. Which is to say:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;badReferenceNSError &lt;span style=&#34;color:#66d9ef&#34;&gt;is&lt;/span&gt; NSError        &lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; true&lt;/span&gt;
badReferenceNSError &lt;span style=&#34;color:#66d9ef&#34;&gt;is&lt;/span&gt; Error          &lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; true&lt;/span&gt;
badReferenceNSError &lt;span style=&#34;color:#66d9ef&#34;&gt;is&lt;/span&gt; LocalizedError &lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; false&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This means if we try to get data out of some unknown error in the obvious way, it works as expected for &lt;code&gt;Error&lt;/code&gt; and &lt;code&gt;LocalizedError&lt;/code&gt;, but only reports a &lt;code&gt;localizedDescription&lt;/code&gt; for  &lt;code&gt;NSError&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#75715e&#34;&gt;// The obvious way that doesn’t work:&lt;/span&gt;
&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;log&lt;/span&gt;(error: Error) {
  print(error.localizedDescription)
  &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; localized = error &lt;span style=&#34;color:#66d9ef&#34;&gt;as&lt;/span&gt;? LocalizedError {
    print(localized.failureReason)
    print(localized.recoverySuggestion)
  }
}

log(error: MyError.badReference)
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; The reference was bad.&lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; Bad Reference&lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; Try using a good one.&lt;/span&gt;

log(error: badReferenceNSError)
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; The reference was bad.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;That’s pretty annoying because we &lt;em&gt;know&lt;/em&gt; our &lt;code&gt;NSError&lt;/code&gt; has a failure reason and recovery suggestion defined in its &lt;code&gt;userInfo&lt;/code&gt;. It’s just, for whatever reason, not exposed via &lt;code&gt;LocalizedError&lt;/code&gt; conformance.&lt;/p&gt;
&lt;h2 id=&#34;the-new-becomes-the-old&#34;&gt;The New Becomes the Old&lt;/h2&gt;
&lt;p&gt;At this point we may despair, picturing long &lt;code&gt;switch&lt;/code&gt; statements  trying to sort types and test existence of various &lt;code&gt;userInfo&lt;/code&gt; properties. But never fear! There &lt;em&gt;is&lt;/em&gt; an easy solution. It’s just non-obvious.&lt;/p&gt;
&lt;p&gt;See, &lt;code&gt;NSError&lt;/code&gt; has convenience methods defined on it for extracting localized description, failure reason, and recovery suggestion from the &lt;code&gt;userInfo&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;badReferenceNSError.localizedDescription
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; &amp;#34;The reference was bad.&amp;#34;&lt;/span&gt;

badReferenceNSError.localizedFailureReason
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; &amp;#34;Bad Reference&amp;#34;&lt;/span&gt;

badReferenceNSError.localizedRecoverySuggestion
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; &amp;#34;Try using a good one.&amp;#34;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Which is great for handling an &lt;code&gt;NSError&lt;/code&gt;, but doesn’t help us get these values out of a Swift &lt;code&gt;LocalizedError&lt;/code&gt;… or does it?&lt;/p&gt;
&lt;p&gt;It turns out Swift’s &lt;code&gt;Error&lt;/code&gt; is bridged by the compiler to &lt;code&gt;NSError&lt;/code&gt;. Which means we can treat an &lt;code&gt;Error&lt;/code&gt; as an &lt;code&gt;NSError&lt;/code&gt; with a simple cast:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; bridgedError: NSError
bridgedError = MyError.badReference &lt;span style=&#34;color:#66d9ef&#34;&gt;as&lt;/span&gt; NSError
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;More impressively, though, when we cast a &lt;code&gt;LocalizedError&lt;/code&gt; in this way, the bridge &lt;em&gt;does the right thing&lt;/em&gt; and wires up &lt;code&gt;localizedDescription&lt;/code&gt;, &lt;code&gt;localizedFailureReason&lt;/code&gt;, and &lt;code&gt;localizedRecoverySuggestion&lt;/code&gt; to point to the appropriate values!&lt;/p&gt;
&lt;p&gt;So if we want a consistent interface to pull localized information out of &lt;code&gt;Error&lt;/code&gt;, &lt;code&gt;LocalizedError&lt;/code&gt;, &lt;em&gt;and&lt;/em&gt; &lt;code&gt;NSError&lt;/code&gt;, we just need to blindly cast everything to an &lt;code&gt;NSError&lt;/code&gt; first:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;log&lt;/span&gt;(error: Error) {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; bridge = error &lt;span style=&#34;color:#66d9ef&#34;&gt;as&lt;/span&gt; NSError
  print(bridge.localizedDescription)
  print(bridge.localizedFailureReason)
  print(bridge.localizedRecoverySuggestion)
}

log(error: MyError.badReference)
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; The reference was bad.&lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; Bad Reference&lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; Try using a good one.&lt;/span&gt;

log(error: badReferenceNSError)
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; The reference was bad.&lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; Bad Reference&lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; Try using a good one.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Once we have all this delicious context about our errors, what should we do with it? That&amp;rsquo;s the &lt;a href=&#34;https://www.figure.ink/blog/2021/8/8/what-to-do-with-localized-errors&#34;&gt;topic of next week’s post&lt;/a&gt;. See you then!&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Cleaning up Async Without Swift 5.5</title>
      <link>https://figure.ink/2021/06/14/cleaning-up-async.html</link>
      <pubDate>Mon, 14 Jun 2021 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2021/06/14/cleaning-up-async.html</guid>
      <description>&lt;p&gt;It’s finally here! After seven years of callbacks and completion handlers, we now have a way to cleanly and correctly make asynchronous calls in Swift without endless nesting. It&amp;rsquo;s async/await and it’s awesome.&lt;/p&gt;
&lt;p&gt;Sadly, these new features require runtime support. Which means, at least for the time being, &lt;a href=&#34;https://forums.swift.org/t/will-swift-concurrency-deploy-back-to-older-oss/49370/4&#34;&gt;async is iOS 15-/macOS 12-only&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;For those of us supporting older deployment targets, this can be a bit of a let down. But not all hope is lost! We can build clean, flattened-out async handling on our own. And maybe learn a thing or two about the nature of asynchrony along the way?&lt;/p&gt;
&lt;h2 id=&#34;asyncawait&#34;&gt;async/await&lt;/h2&gt;
&lt;p&gt;Let’s start with a description of the problem and how Swift 5.5 solves it.&lt;/p&gt;
&lt;p&gt;Given a series of dependent, asynchronous calls, we currently have to write them in a bunch of nested callbacks:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchPortrait&lt;/span&gt;(
  user: UUID, 
  completion: (Image)-&amp;gt;Void
) { 
  fetchAvatar(user: user) { url &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
    fetchImage(url: url) { image &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
      completion(image)
    } 
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This works, but execution jumps all over the place spatially &lt;em&gt;and temporally&lt;/em&gt; making the code hard to reason about and prone to errors. We would like to specify our async calls procedurally, instead. One right after the other, no nesting.&lt;/p&gt;
&lt;p&gt;Swift 5.5 solves this with async/await:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchPortrait&lt;/span&gt;(user: UUID) async -&amp;gt; Image {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; url = await fetchAvatar(user: user)
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; image = await fetchImage(url: url)
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; image
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;How are they doing that? &lt;a href=&#34;https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID639&#34;&gt;Swift.org sheds some illumination&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;An asynchronous function … is a special kind of function that can be suspended while it’s partway through execution.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Long time readers will &lt;a href=&#34;http://www.figure.ink/blog/2017/9/4/expressive-coroutines&#34;&gt;recognize this as a coroutine&lt;/a&gt;. A coroutine is ideal for handling asynchronous work because we can suspend it just after it begins its async job, then resume it again right where it left off when the job completes and we&amp;rsquo;re ready to continue.&lt;/p&gt;
&lt;h2 id=&#34;coroutines-on-the-cheap&#34;&gt;Coroutines on the Cheap&lt;/h2&gt;
&lt;p&gt;This flow of events might sound familiar. Let’s look a little closer look at the execution of a standard “completion handler” function:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;prettyHTML&lt;/span&gt;(
  url: URL, 
  completion: (HTML)-&amp;gt;Void
) {
  getPage(url: url) { html &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
    &lt;span style=&#34;color:#75715e&#34;&gt;// Do work to format the HTML...&lt;/span&gt;
    completion(html)
  }
}
  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;In this example, &lt;code&gt;prettyHTML&lt;/code&gt; starts getting some HTML via &lt;code&gt;getPage&lt;/code&gt;… and then &lt;em&gt;returns&lt;/em&gt;. Some time later, the closure we passed to &lt;code&gt;getPage&lt;/code&gt;  is called, and work is done to pretty up the HTML.&lt;/p&gt;
&lt;p&gt;In other words, &lt;code&gt;prettyHTML&lt;/code&gt; is essentially “suspended while it’s partway through execution.” And then, at some later time, its execution is resumed again from that very spot it left off.&lt;/p&gt;
&lt;p&gt;Yup. Completions handlers are the poor man’s coroutine. They just require that we bundle up all the state needed to “resume the coroutine” in a closure. It’s &lt;em&gt;that closure&lt;/em&gt; that leads to the nesting and non-linear execution flow.&lt;/p&gt;
&lt;p&gt;So we already have the building blocks for decent async handling. What we &lt;em&gt;really&lt;/em&gt; need is a better way to manage those completion closures.&lt;/p&gt;
&lt;h2 id=&#34;cps-strike&#34;&gt;CPS Strike&lt;/h2&gt;
&lt;p&gt;So let’s zoom in on our completion handlers. Imagine the simple function:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchAvatar&lt;/span&gt;(user: UUID) -&amp;gt; URL
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;If we want to make this asynchronous by rewriting it as a “cheap coroutine” with completion handler, what do we need to do? Rather than &lt;em&gt;returning&lt;/em&gt; the &lt;code&gt;URL&lt;/code&gt; we’ll move it to the argument of a &lt;em&gt;new closure&lt;/em&gt; we pass in as a parameter:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchAvatar&lt;/span&gt;(user: UUID, complete: (URL)-&amp;gt;Void)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;There&amp;rsquo;s a name for rewriting functions this way — it&amp;rsquo;s called &lt;a href=&#34;https://en.wikipedia.org/wiki/Continuation-passing_style&#34;&gt;Continuation Passing Style&lt;/a&gt; or CPS. And the closure we pass when we do this is called a &lt;a href=&#34;https://en.wikipedia.org/wiki/Continuation&#34;&gt;continuation&lt;/a&gt;. Which makes sense — it’s the thing we call to “continue” where we left off.&lt;/p&gt;
&lt;p&gt;Let’s make a type to represent a continuation:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;typealias&lt;/span&gt; Continuation&amp;lt;Ret&amp;gt; = (Ret) -&amp;gt; Void
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Our CPS version of &lt;code&gt;fetchAvatar&lt;/code&gt; could then look like:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchAvatar&lt;/span&gt;(user: UUID, c: Continuation&amp;lt;URL&amp;gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;In fact, if we rewrite the signature of all the functions from our async example, above, we might notice something striking:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchPortrait&lt;/span&gt;(
  user: UUID, 
  c: Continuation&amp;lt;Image&amp;gt;
)
&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchAvatar&lt;/span&gt;(user: UUID, c: Continuation&amp;lt;URL&amp;gt;)
&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchImage&lt;/span&gt;(url: URL, c: Continuation&amp;lt;Image&amp;gt;)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;They &lt;em&gt;all&lt;/em&gt; take a &lt;code&gt;Continuation&lt;/code&gt; type — the only difference is the generic type  representing the value they’ll eventually be called with. If we had a way to transform a &lt;code&gt;Continuation&amp;lt;URL&amp;gt;&lt;/code&gt; to a &lt;code&gt;Continuation&amp;lt;Image&amp;gt;&lt;/code&gt; , we could chain these together!&lt;/p&gt;
&lt;p&gt;In other words, given a &lt;code&gt;Continuation&amp;lt;URL&amp;gt;&lt;/code&gt; we want a way to apply a transformation  &lt;code&gt;(T)-&amp;gt;Continuation&amp;lt;U&amp;gt;&lt;/code&gt; that results in a new &lt;code&gt;Continuation&amp;lt;Image&amp;gt;&lt;/code&gt;. This is a &lt;code&gt;flatMap&lt;/code&gt;. And &lt;a href=&#34;http://chris.eidhof.nl/post/monads-in-swift/&#34;&gt;flatMaps are the domain of Monads&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&#34;theres-a-monad-for-that&#34;&gt;There’s a Monad for That&lt;/h2&gt;
&lt;p&gt;A Continuation Monad wraps a &lt;code&gt;Continuation&lt;/code&gt;. That is, it’s what happens when you render a &lt;code&gt;Continuation&lt;/code&gt;, itself, in continuation passing style.&lt;/p&gt;
&lt;p&gt;If a &lt;code&gt;Continuation&lt;/code&gt;, conceptually, rewrites a value as a function that takes said value as its parameter, then a continuation of a &lt;code&gt;Continuation&lt;/code&gt; is a &lt;code&gt;Continuation&lt;/code&gt; rewritten as a function that takes said &lt;code&gt;Continuation&lt;/code&gt; as its parameter.&lt;/p&gt;
&lt;p&gt;Deep breath.&lt;/p&gt;
&lt;p&gt;Okay, let’s to try to illustrate this in code:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#75715e&#34;&gt;// A plain old Value:&lt;/span&gt;
Value

&lt;span style=&#34;color:#75715e&#34;&gt;// Continuation of Value:&lt;/span&gt;
(Value)-&amp;gt;Void

&lt;span style=&#34;color:#75715e&#34;&gt;// Continuation of Continuation of Value:&lt;/span&gt;
((Value)-&amp;gt;Void)-&amp;gt;Void
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Defining types for these abstractions as we go will help keep things clear. &lt;code&gt;ContinuationMonad&lt;/code&gt; is a continuation of a &lt;code&gt;Continuation&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;typealias&lt;/span&gt; ContinuationMonad&amp;lt;Value&amp;gt; = 
          (@escaping Continuation&amp;lt;Value&amp;gt;) -&amp;gt; Void
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;We can create one of these monads with a function that takes the value we eventually want to pass on to the continuation. We can name this function anything we like. &lt;code&gt;init&lt;/code&gt;, &lt;code&gt;makeMonad&lt;/code&gt;, &lt;code&gt;unit&lt;/code&gt;… &lt;a href=&#34;https://khanlou.com/2015/09/what-the-heck-is-a-monad/&#34;&gt;Khanlou’s post on monads&lt;/a&gt; covers a lot of various names traditionally used for monadic operations.&lt;/p&gt;
&lt;p&gt;Here, we’re going to name it &lt;code&gt;async&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;async&lt;/span&gt;&amp;lt;Value&amp;gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; wrappedValue: Value) 
     -&amp;gt; ContinuationMonad&amp;lt;Value&amp;gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; { continuation &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
    continuation(wrappedValue)
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This returns a function that, when called with a continuation, calls the continuation with the &lt;code&gt;wrappedValue&lt;/code&gt; passed in on creation. In other words, this returns a &lt;code&gt;ContinuationMonad&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&#34;flat-the-planet&#34;&gt;Flat the Planet&lt;/h2&gt;
&lt;p&gt;Or course, our whole goal is to be able to transform between different types of continuations. In the context of a &lt;code&gt;ContinuationMonad&lt;/code&gt;, we want to be able to, given a value &lt;code&gt;T&lt;/code&gt; from the source monad, create a new monad with a transformed value &lt;code&gt;U&lt;/code&gt;. Which is to say:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;typealias&lt;/span&gt; Transform&amp;lt;T,U&amp;gt; = 
               (T) -&amp;gt; ContinuationMonad&amp;lt;U&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;We apply this transform with our friend, &lt;code&gt;flatMap&lt;/code&gt;. But the implementation of a &lt;code&gt;flatMap&lt;/code&gt; over a continuation of a &lt;code&gt;Continuation&lt;/code&gt; is a little intense:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;flatMap&lt;/span&gt;&amp;lt;T,U&amp;gt;(
  &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; monad: @escaping ContinuationMonad&amp;lt;T&amp;gt;, 
  &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; transform: @escaping Transform&amp;lt;T,U&amp;gt;
) -&amp;gt; ContinuationMonad&amp;lt;U&amp;gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; { continuation &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
    monad { wrappedValue &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
      transform(wrappedValue)(continuation)
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Given a &lt;code&gt;ContinuationMonad&lt;/code&gt; and a &lt;code&gt;Transform&lt;/code&gt;, we return a function that, when called with a &lt;code&gt;Continuation&lt;/code&gt;, will:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Unwrap the first monad with an ad-hoc continuation we create that…&lt;/li&gt;
&lt;li&gt;Takes the original monad’s value, transforms it into a new monad using the given &lt;code&gt;Transform&lt;/code&gt;, and then…&lt;/li&gt;
&lt;li&gt;Passes the continuation into this new monad, effectively calling the continuation with our transformed value.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If this causes headaches, we are, at least, &lt;a href=&#34;https://stackoverflow.com/search?q=continuation+monad&#34;&gt;in very good company&lt;/a&gt;. My best advice is to throw it into a playground and step over it a couple or hundred times. Enlightenment will follow in its own measure.&lt;/p&gt;
&lt;p&gt;Once we get over the raw mechanics, the important thing for us to recognize is none of these transformations are actually applied at the time we call &lt;code&gt;flatMap&lt;/code&gt;. We return a thing that will call the thing that will apply the transformations when the continuation is passed in. In other words, everything is still asynchronous.&lt;/p&gt;
&lt;h2 id=&#34;spicy-curry&#34;&gt;Spicy Curry&lt;/h2&gt;
&lt;p&gt;With the &lt;code&gt;ContinuationMonad&lt;/code&gt; to guide us, our &lt;code&gt;fetchPortrait&lt;/code&gt; implementation can create a new monad wrapping the given &lt;code&gt;UUID&lt;/code&gt;, then &lt;code&gt;flatMap&lt;/code&gt; it into our &lt;code&gt;fetchAvatar&lt;/code&gt; operation:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#75715e&#34;&gt;// We’ll make this better. Promise!&lt;/span&gt;
&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchPortrait&lt;/span&gt;(
  user: UUID, 
  c: @escaping Continuation&amp;lt;String&amp;gt;
) {
  flatMap(
    async(user),
    { aUser &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt; 
      { aContinuation &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt; 
        fetchAvatar(user: t, c: u) 
      } 
    }
  )
  &lt;span style=&#34;color:#75715e&#34;&gt;//...&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Yikes! What happened in the second half of our &lt;code&gt;flatMap&lt;/code&gt;?&lt;/p&gt;
&lt;p&gt;Well, remember the &lt;code&gt;flatMap&lt;/code&gt; takes a &lt;code&gt;Transform&lt;/code&gt; that looks like :&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#75715e&#34;&gt;// Transform’s definition:&lt;/span&gt;
(T)-&amp;gt;ContinuationMonad&amp;lt;U&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;or, if we break it down a few steps further:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#75715e&#34;&gt;// Substitute ContinuationMonad’s definition:&lt;/span&gt;
(T)-&amp;gt;(Continuation&amp;lt;U&amp;gt;)-&amp;gt;Void

&lt;span style=&#34;color:#75715e&#34;&gt;// Substitute Continuation’s definition:&lt;/span&gt;
(T)-&amp;gt;((U)-&amp;gt;Void)-&amp;gt;Void
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;That&amp;rsquo;s a tricky shape to fill. And our &lt;code&gt;fetchAvatar&lt;/code&gt;’s  signature doesn’t match it:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;(UUID, (URL)-&amp;gt;Void)-&amp;gt;Void
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Though, actually, if we pull that first UUID argument off of the front, creating new function that takes &lt;em&gt;only&lt;/em&gt; the UUID, returning a function that takes what remains of the original parameters… that fits the shape we need exactly:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#75715e&#34;&gt;// What we need:&lt;/span&gt;
(T)-&amp;gt;((U)-&amp;gt;Void)-&amp;gt;Void

&lt;span style=&#34;color:#75715e&#34;&gt;// fetchAvatar after pulling first argument &lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;// into its own function:&lt;/span&gt;
(UUID)-&amp;gt;((URL)-&amp;gt;Void)-&amp;gt;Void
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;There’s a &lt;a href=&#34;https://en.wikipedia.org/wiki/Currying&#34;&gt;functional programming concept called “currying”&lt;/a&gt; that does precisely this. The details are probably worth a blog post on their own, and the Point•Free folk have &lt;a href=&#34;https://www.pointfree.co/episodes/ep5-higher-order-functions&#34;&gt;a really good series on this&lt;/a&gt; if you want to know more.&lt;/p&gt;
&lt;p&gt;But for now, suffice it to say that, given this function:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;curry&lt;/span&gt;&amp;lt;T, U, Z&amp;gt;(
  &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;ƒ&lt;/span&gt;: @escaping (T, U)-&amp;gt;Z
) -&amp;gt; (T) -&amp;gt; (U) -&amp;gt; Z {
  { t &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt; { u &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt; &lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;ƒ&lt;/span&gt;(t, u) } }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;and some function that takes two arguments like:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;example&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; i: Int, &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; d: Double) -&amp;gt; String {
  &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;\(&lt;/span&gt;i&lt;span style=&#34;color:#e6db74&#34;&gt;)&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;:&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;\(&lt;/span&gt;d&lt;span style=&#34;color:#e6db74&#34;&gt;)&lt;/span&gt;&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;both these expressions are equivalent:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;example(&lt;span style=&#34;color:#ae81ff&#34;&gt;42&lt;/span&gt;, &lt;span style=&#34;color:#ae81ff&#34;&gt;33.3&lt;/span&gt;)        &lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; &amp;#34;42:33.3&amp;#34;&lt;/span&gt;
curry(example)(&lt;span style=&#34;color:#ae81ff&#34;&gt;42&lt;/span&gt;)(&lt;span style=&#34;color:#ae81ff&#34;&gt;33.3&lt;/span&gt;) &lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; &amp;#34;42:33.3&amp;#34;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Which lets us rewrite our messy &lt;code&gt;flatMap&lt;/code&gt; above as:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchPortrait&lt;/span&gt;(
  user: UUID, 
  c: @escaping Continuation&amp;lt;String&amp;gt;
) {
  flatMap(
    flatMap(
      async(user), 
      curry(fetchAvatar)
    ),
    curry(fetchImage)
  )
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Much better!&lt;/p&gt;
&lt;h2 id=&#34;operator-operation&#34;&gt;Operator Operation&lt;/h2&gt;
&lt;p&gt;But hold the phone… the whole point of this was to get rid of nesting in our callbacks, and here we are nesting a bunch of &lt;code&gt;flatMap&lt;/code&gt;s instead? How is this an improvement?&lt;/p&gt;
&lt;p&gt;In short, there&amp;rsquo;s a big difference between nested closure implementations (and  their captured environments) and nesting identical functions with identical signatures; not the least of which is: we can chain redundant function calls by introducing an operator.&lt;/p&gt;
&lt;p&gt;When it comes to declaring an operator, there can be a lot of sturm and drang  over the choice of symbol. Haskell uses &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt; for a &lt;code&gt;flatMap&lt;/code&gt;. That’s good enough for me:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;precedencegroup FlatMapOperator { 
  &lt;span style=&#34;color:#66d9ef&#34;&gt;associativity&lt;/span&gt;: &lt;span style=&#34;color:#66d9ef&#34;&gt;left&lt;/span&gt; 
}
&lt;span style=&#34;color:#66d9ef&#34;&gt;infix&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;operator&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt;: FlatMapOperator

&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&amp;lt;&lt;/span&gt;T,U&amp;gt; (
  lhs: @escaping ContinuationMonad&amp;lt;T&amp;gt;, 
  rhs: @escaping ContinuationMonadTransform&amp;lt;T,U&amp;gt;
) -&amp;gt; ContinuationMonad&amp;lt;U&amp;gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; flatMap(lhs, rhs)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;With this, we can rewrite our monad chain, above, as:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;async(user)
&lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchAvatar)
&lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchImage)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Which is feeling pretty nice. Of course, this returns a &lt;code&gt;ContinuationMonad&lt;/code&gt; which, as we mentioned above, doesn&amp;rsquo;t actually do anything on its own. To get it jump into action, we need to give it a continuation.&lt;/p&gt;
&lt;p&gt;We could do that with a trailing closure:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;(async(user)
 &lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchAvatar)
 &lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchImage)) { image &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
  logImage(image)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;But more often than not, we&amp;rsquo;ll have a parent continuation we’ll want to resume when the monad chain completes. Because it&amp;rsquo;s already a continuation, we don&amp;rsquo;t need to make a new closure to hold it. We can just apply it to the preceding function.&lt;/p&gt;
&lt;p&gt;To make this look pretty, we’ll add a backwards application operator. Haskell uses &lt;code&gt;$&lt;/code&gt; for this, which is problematic in Swift for a number of reasons. So we’re going to steal F#’s &lt;code&gt;&amp;lt;|&lt;/code&gt; instead:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;precedencegroup BackApplication {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;associativity&lt;/span&gt;: &lt;span style=&#34;color:#66d9ef&#34;&gt;left&lt;/span&gt;
}
&lt;span style=&#34;color:#66d9ef&#34;&gt;infix&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;operator&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;&amp;lt;|&lt;/span&gt;: BackApplication

&lt;span style=&#34;color:#66d9ef&#34;&gt;public&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;&amp;lt;|&lt;/span&gt; &amp;lt;T, U&amp;gt;(&lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;ƒ&lt;/span&gt;: (T)-&amp;gt;U, t: T) -&amp;gt; U {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;ƒ&lt;/span&gt;(t)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Now we can chain async operations on our monad with &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt; and apply a continuation (which will be called, asynchronously, with the result of the whole monad chain) with &lt;code&gt;&amp;lt;|&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;async(user)
&lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchAvatar)
&lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchImage)
&lt;span style=&#34;color:#f92672&#34;&gt;&amp;lt;|&lt;/span&gt; logImage
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;1800-words-later&#34;&gt;1,800 Words Later…&lt;/h2&gt;
&lt;p&gt;Not so long ago, we set out on our quest with nothing but a nested mess of async spaghetti:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchPortrait&lt;/span&gt;(
  user: UUID, 
  completion: (Image)-&amp;gt;Void
) { 
  fetchAvatar(user: user) { url &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
    fetchImage(url: url) { image &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
      completion(image)
    } 
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;But with a little understanding of continuations (and a handful of monads and operators on loan from functional languages), we’ve ended up with:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;fetchPortrait&lt;/span&gt;(
  user: UUID,
  completion: Continuation&amp;lt;Image&amp;gt;
) {
  async(user)
  &lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchAvatar)
  &lt;span style=&#34;color:#f92672&#34;&gt;&amp;gt;&amp;gt;=&lt;/span&gt; curry(fetchImage)
  &lt;span style=&#34;color:#f92672&#34;&gt;&amp;lt;|&lt;/span&gt; completion
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Not bad! Makes me feel like there’s plenty of gas left in the tank of the ol’ runtime to get us through these golden years of iOS 12–14 support.&lt;/p&gt;
&lt;p&gt;This was a long one with a lot of scattered code, so I’ve &lt;a href=&#34;https://gist.github.com/jemmons/71104d11e8598220cab48c651c8dbf4f&#34;&gt;pulled everything together into a gist&lt;/a&gt;. You ought to be able to paste it right into a Playground and get results — at least in Xcode 12.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Moving Mental State to the Physical</title>
      <link>https://figure.ink/2020/11/25/moving-mental-state.html</link>
      <pubDate>Wed, 25 Nov 2020 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2020/11/25/moving-mental-state.html</guid>
      <description>&lt;p&gt;I &lt;a href=&#34;https://twitter.com/jemmons/status/1329785716205875200&#34;&gt;posted on twitter&lt;/a&gt; about how much I like &lt;a href=&#34;https://museapp.com&#34;&gt;Muse for iPad&lt;/a&gt;. People were curious about what was so special about it, and I thought I could sum it up in a tweet or two. But by the &lt;a href=&#34;https://twitter.com/jemmons/status/1329804016201719814&#34;&gt;third reply in the thread&lt;/a&gt; I realized “I should have put this on the blog.” So here it is…&lt;/p&gt;
&lt;h2 id=&#34;selections-in-muse&#34;&gt;Selections in Muse&lt;/h2&gt;
&lt;p&gt;Muse does a great many things well, and I could probably do a whole series on little things worth emulating in our apps. But one particularly representative example stands out to me: Selections.&lt;/p&gt;
&lt;p&gt;Anyone who’s used a graphics program — your Photoshops, your Pixelmators, your MacPaints — knows there are two ways to make a selection:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Drag a box.&lt;/li&gt;
&lt;li&gt;Lasso an arbitrary shape.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Dragging a box is simple and fast: one click, one drag — and the drag can be adjusted in real time so &lt;em&gt;only the click&lt;/em&gt; needs to be targeted. Fast. Easy. Minimal twitch factor. But not very precise.&lt;/p&gt;
&lt;p&gt;For precision (selecting around a non-box thing without cutting into background) there’s the lasso. It lets you carefully trace the path of the selection you want. &lt;em&gt;Carefully&lt;/em&gt; being the operative word. You need to target each and every point along the path as you’re selecting it. Using the lasso is sweaty.&lt;/p&gt;
&lt;p&gt;Muse lets you use either a box or a lasso to make selections. No big innovation there. You make lasso selections with the Pencil. It’s very nice to be able to use the iPad’s most precise instrument for Muse’s most precise operation, but that’s not breaking new ground either.&lt;/p&gt;
&lt;h2 id=&#34;modalitys-all-in-the-mind&#34;&gt;Modality’s All in the Mind&lt;/h2&gt;
&lt;p&gt;What’s amazing is how Muse presents modality.&lt;/p&gt;
&lt;p&gt;See, in Photoshop, etc. tools are modal. Everything behaves differently depending on what tool’s currently selected  (what &lt;em&gt;mode&lt;/em&gt; the editor is in) and — importantly — this means we, as users, need to &lt;em&gt;manage&lt;/em&gt; the state of the tools to get the results we want.&lt;/p&gt;
&lt;p&gt;If we want to make a box selection, for example, we have to be in box-selection-mode. If we’re accidentally in lasso-selection-mode instead, we end up drawing a diagonal-squiggle-selection, not the box we had originally intended.&lt;/p&gt;
&lt;p&gt;Being developers, we know there’s a variable called &lt;code&gt;currentTool&lt;/code&gt; or something buried in Photoshop that keeps track of this mode so that selection operations can refer to it later to know whether to draw a box or a lasso or what have you.&lt;/p&gt;
&lt;p&gt;What may not be as clear is that, for the user, this is also state they have to hold in their &lt;em&gt;mental model&lt;/em&gt; of the app. They have to consult the “am I in box mode?” in their brain before making a selection because different gestures (drag-a-box vs. trace-a-shape) and different levels of precision (breezy vs. sweaty) will be required, depending.&lt;/p&gt;
&lt;p&gt;This means before a user can let muscle memory take over and perform the gesture they &lt;em&gt;know&lt;/em&gt; they need to perform, they &lt;em&gt;literally need to context switch&lt;/em&gt;. Halt everything, consult state, potentially switch mode, and then attempt to resume the half-subconscious gesture they were trying to make a moment ago.&lt;/p&gt;
&lt;h2 id=&#34;lets-get-physical&#34;&gt;Let’s Get Physical&lt;/h2&gt;
&lt;p&gt;So how does Muse deal with this? You make a lasso selection with the Pencil as normal. To make a box selection instead, just hold the Pencil at a low angle, like you were shading with it:&lt;/p&gt;
&lt;p&gt;&lt;video src=&#34;https://pub.figure.ink/mov/muse-selection.mp4&#34; width=&#34;460&#34; loop=&#34;&#34; playsinline=&#34;&#34; muted=&#34;&#34; controls=&#34;&#34;&gt;&lt;/video&gt;&lt;/p&gt;
&lt;p&gt;Let’s look at that video again. That little flip of the Pencil in the hand? &lt;em&gt;That’s&lt;/em&gt; the context switch. Muse takes it completely out of mental state and turns it into a physical thing, amenable to muscle memory.&lt;/p&gt;
&lt;p&gt;This is a level up, but also not unique. Anyone who uses Photoshop does so with one hand on the keyboard so as to hold down one or more modifier keys while working. ⌥⇧⌘-drag for special behavior. That sort of thing.&lt;/p&gt;
&lt;p&gt;What impresses me is the careful thought around the interaction. The Muse developers realized they needed precise (lasso) and imprecise (box) selection UI in their app. And they realized a (small p) pencil has precise (line) and imprecise (shade) modes physically built into it.&lt;/p&gt;
&lt;p&gt;Connecting those dots isn’t hard, but thinking about a single interaction in our apps carefully enough to &lt;em&gt;see&lt;/em&gt; the dots is. It goes to show we shouldn’t take any interaction for granted. Muse certainly doesn’t, and the careful design that results makes it an absolute joy to use.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Debugging Generics in Swift</title>
      <link>https://figure.ink/2020/06/24/debugging-generics-in.html</link>
      <pubDate>Wed, 24 Jun 2020 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2020/06/24/debugging-generics-in.html</guid>
      <description>&lt;p&gt;A friend of mine was having a problem with a generic function they’d written. I’ve simplified it quite a bit to post, but the essence was:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;foo&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; n: T) -&amp;gt; T &lt;span style=&#34;color:#66d9ef&#34;&gt;where&lt;/span&gt; T: Numeric {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; n &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; (&lt;span style=&#34;color:#ae81ff&#34;&gt;4&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;as&lt;/span&gt;! T)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;They could call it with an &lt;code&gt;Int&lt;/code&gt; just fine, but when calling with a &lt;code&gt;Double&lt;/code&gt;, They’d trap:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; i: Int = &lt;span style=&#34;color:#ae81ff&#34;&gt;5&lt;/span&gt;
&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; d: Double = &lt;span style=&#34;color:#ae81ff&#34;&gt;5.5&lt;/span&gt;
foo(i) &lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; 20&lt;/span&gt;
foo(d) &lt;span style=&#34;color:#75715e&#34;&gt;//&amp;gt; 🛑 SIGABRT &lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Those steeped in the myths and traditions of generics might see the issue right away. But I didn’t. At least not in its original form. And the compiler wasn’t giving me anything. I had to dig deeper.&lt;/p&gt;
&lt;p&gt;Thankfully, with generics, that’s easy to do. They are, at the end of the day, just syntactic sugar around defining polymorphic functions. Our generic function above is functionally equivalent to writing out the same function over and over, each time replacing its &lt;code&gt;T&lt;/code&gt;s with one of the set of all the types that meet its requirements (in this case, all types that implement &lt;code&gt;Numeric&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;We can do this manually (at least over the small number of types that are interesting to us). And doing so not only gives us a clearer view into our function’s execution, it also gives the compiler an easier path for diagnostics reporting. Both are huge wins whenever we’re trying to debug.&lt;/p&gt;
&lt;p&gt;Just look at what happens when we rewrite our function with the types from our example:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;foo&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; n: Int) -&amp;gt; Int {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; n &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; (&lt;span style=&#34;color:#ae81ff&#34;&gt;4&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;as&lt;/span&gt;! Int)
}

&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;foo&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; n: Double) -&amp;gt; Double {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; n &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; (&lt;span style=&#34;color:#ae81ff&#34;&gt;4&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;as&lt;/span&gt;! Double)
  &lt;span style=&#34;color:#75715e&#34;&gt;// ⚠️ Cast from &amp;#39;Int&amp;#39; to unrelated type &lt;/span&gt;
  &lt;span style=&#34;color:#75715e&#34;&gt;// &amp;#39;Double&amp;#39; always fails&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;We probably don’t even need the compiler’s warning to see the problem: we can’t downcast from an &lt;code&gt;Int&lt;/code&gt; to a &lt;code&gt;Double&lt;/code&gt; — the one isn’t down from the other in any type hierarchy.&lt;a id=&#34;ft1back&#34; href=&#34;#ft1&#34;&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Unwinding our generic function like this also makes solution more obvious. &lt;code&gt;Double&lt;/code&gt; (like &lt;code&gt;Numeric&lt;/code&gt;… and &lt;code&gt;Int&lt;/code&gt;, obviously) implements &lt;code&gt;ExpressibleByIntegerLiteral&lt;/code&gt;. So we don’t even need the cast:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;foo&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; n: Int) -&amp;gt; Int {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; n &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;4&lt;/span&gt;
}

&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;foo&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; n: Double) -&amp;gt; Double {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; n &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;4&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Or, expressed generically:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;foo&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; n: T) -&amp;gt; T &lt;span style=&#34;color:#66d9ef&#34;&gt;where&lt;/span&gt; T: Numeric {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; n &lt;span style=&#34;color:#f92672&#34;&gt;*&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;4&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;ft1&#34;&gt;1:&lt;/span&gt; And it traps because of the &lt;code&gt;as!&lt;/code&gt;. Curious why? Ole Begemann has you covered with the magnificent post &lt;a href=&#34;https://oleb.net/2020/as/&#34;&gt;as, as?, and as!&lt;/a&gt;.&lt;a href=&#34;#ft1back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Parse, Don’t Validate</title>
      <link>https://figure.ink/2019/11/09/parse-dont-validate.html</link>
      <pubDate>Sat, 09 Nov 2019 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2019/11/09/parse-dont-validate.html</guid>
      <description>&lt;p&gt;&lt;a href=&#34;https://twitter.com/lexi_lambda&#34;&gt;Alexis King&lt;/a&gt;’s post &lt;a href=&#34;https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/&#34;&gt;“Parse, don’t validate”&lt;/a&gt; is the best thing I’ve read in months. And not just for its pitch-perfect use of “cromulent”. Please find some time and commit to reading it all — it &lt;em&gt;will&lt;/em&gt; make you a better programmer — but here’s a small taste:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The problem is that validation-based approaches make it extremely difficult or impossible to determine if everything was actually validated up front… The entire program must assume that raising an exception anywhere is not only possible, it’s regularly necessary.&lt;/p&gt;
&lt;p&gt;Parsing avoids this problem by stratifying the program into two phases — parsing and execution — where failure due to invalid input can only happen in the first phase. The set of remaining failure modes during execution is minimal by comparison, and they can be handled with the tender care they require.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It sparks in me some new thoughts with regard to my favorite &lt;a href=&#34;https://sandofsky.com/blog/third-party-libraries.html&#34;&gt;Ben Sandofsky quote&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;If the boilerplate gets mind numbing, refactor it into class methods. If that gets to be too much, build some model objects. The goal is to iterate toward your domain model. There’s a reason Apple’s frameworks only get you 80% of the way there. That remaining 20% is called ‘Your App.’&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;King’s post makes concrete for me how futile it is to pass and occasionally validate data in pursuit of this goal. It’s only through the successive &lt;em&gt;parsing&lt;/em&gt; of our data that we iterate towards our domain model. &lt;em&gt;Validating&lt;/em&gt; just rearranges deck chairs on the Titanics of our ever-growing codebases.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>SwiftUI Layout Gems</title>
      <link>https://figure.ink/2019/09/02/swiftui-layout-gems.html</link>
      <pubDate>Mon, 02 Sep 2019 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2019/09/02/swiftui-layout-gems.html</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;One of the first things presented about SwiftUI is that its views determine their own sizes, and that those sizes are fixed … This statement fundamentally changes everything you know about layout. Until you understand all of the repercussions of it, you’ll be constantly feeling like you’re fighting SwiftUI for even the simplest layouts.&lt;/p&gt;
&lt;p&gt;–Scott James Remnant, netsplit.com&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This is definitly my experience with layout in SwiftUI. It took this masterful series of posts by Scott James Remnant (yes, &lt;a href=&#34;https://en.wikipedia.org/wiki/Segfault_%28website%29&#34;&gt;that Scott James Remnant&lt;/a&gt;) to set me straight. I highly recommend starting with &lt;s&gt;&lt;a href=&#34;https://netsplit.com/swiftui/views-have-fixed-sizes/&#34;&gt;“Views Have Fixed Sizes”&lt;/a&gt;&lt;/s&gt; and continuing to click “Next” until empty.&lt;/p&gt;
&lt;p&gt;[Edit: The original site is down, but &lt;a href=&#34;https://web.archive.org/web/20200810091815/https%3A%2F%2Fnetsplit.com%2Fswiftui%2Fviews-choose-their-own-sizes%2F&#34;&gt;here’s the captured version&lt;/a&gt; from archive.org]&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Using Publishers to Prevent Hanging Timers</title>
      <link>https://figure.ink/2019/08/24/using-publishers-to.html</link>
      <pubDate>Sat, 24 Aug 2019 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2019/08/24/using-publishers-to.html</guid>
      <description>&lt;p&gt;One of the venerable &lt;code&gt;Foundation&lt;/code&gt; APIs to get a &lt;code&gt;Combine&lt;/code&gt; extension in Catalina/iOS 13 &lt;a href=&#34;https://developer.apple.com/documentation/foundation/timer/3329589-publish&#34;&gt;is the &lt;code&gt;Timer&lt;/code&gt; class&lt;/a&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;static&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;publish&lt;/span&gt;(
     every interval: TimeInterval, 
     tolerance: TimeInterval? = &lt;span style=&#34;color:#66d9ef&#34;&gt;nil&lt;/span&gt;, 
     on runLoop: RunLoop, 
     &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt; mode: RunLoop.Mode, 
     options: RunLoop.SchedulerOptions? = &lt;span style=&#34;color:#66d9ef&#34;&gt;nil&lt;/span&gt;) 
-&amp;gt; Timer.TimerPublisher
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;In practice we’d probably use it something like:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;import&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Foundation&lt;/span&gt;
&lt;span style=&#34;color:#66d9ef&#34;&gt;import&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Combine&lt;/span&gt;

&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; subscription = 
Timer.publish(every: &lt;span style=&#34;color:#ae81ff&#34;&gt;1.0&lt;/span&gt;, on: .main, &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;: .&lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;)
  .autoconnect()
  .sink { &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
    print(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;timer fired&amp;#34;&lt;/span&gt;)
  }

&lt;span style=&#34;color:#75715e&#34;&gt;// Time passes...&lt;/span&gt;

subscription.cancel()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Note that &lt;code&gt;Timer.publish&lt;/code&gt; returns &lt;a href=&#34;https://developer.apple.com/documentation/combine/connectablepublisher&#34;&gt;a &lt;code&gt;ConnectablePublisher&lt;/code&gt;&lt;/a&gt; meaning we need to call &lt;code&gt;connect&lt;/code&gt; or use &lt;code&gt;autoconnect&lt;/code&gt; to start it publishing. Otherwise this feels like a pretty straight-forward definition of a timer.&lt;/p&gt;
&lt;p&gt;So straight-forward, in fact, that it looks pretty familiar. Here’s how we might have written a timer before &lt;code&gt;Combine&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; timer = 
Timer(timeInterval: &lt;span style=&#34;color:#ae81ff&#34;&gt;1.0&lt;/span&gt;, repeats: &lt;span style=&#34;color:#66d9ef&#34;&gt;true&lt;/span&gt;) { &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
  print(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;timer fired&amp;#34;&lt;/span&gt;)
}

RunLoop.main.add(timer, forMode: .&lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;)

&lt;span style=&#34;color:#75715e&#34;&gt;// Time passes...&lt;/span&gt;

timer.invalidate()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;We explicitly add the timer to the run loop instead of using &lt;code&gt;autoconnect&lt;/code&gt; to start it. And to stop it we call &lt;code&gt;invalidate&lt;/code&gt; on the returned &lt;code&gt;timer&lt;/code&gt; ref rather than &lt;code&gt;cancel&lt;/code&gt; on an &lt;code&gt;AnyCancellable&lt;/code&gt;. But all the same pieces are there. The interval, run loop, closure to execute, etc.&lt;/p&gt;
&lt;p&gt;So it’s tempting to say that, if we’re targeting Catalina/iOS 13  but not interested in filtering timer events through a bunch of Combine operators, there’s really no benefit to using &lt;code&gt;Timer&lt;/code&gt;’s publisher API.&lt;/p&gt;
&lt;p&gt;But this overlooks a &lt;em&gt;major&lt;/em&gt; yet somewhat invisible benefit, which is life cycle management.&lt;/p&gt;
&lt;p&gt;Let’s say we have a class that uses an old-school timer:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;OldTimer&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; timer: Timer
  &lt;span style=&#34;color:#66d9ef&#34;&gt;init&lt;/span&gt;() {
    timer = 
    Timer(timeInterval: &lt;span style=&#34;color:#ae81ff&#34;&gt;1.0&lt;/span&gt;, repeats: &lt;span style=&#34;color:#66d9ef&#34;&gt;true&lt;/span&gt;) { &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
      print(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Old Timer, go!&amp;#34;&lt;/span&gt;)
    }
    RunLoop.main.add(timer, forMode: .&lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;)
  }
}

&lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; old: OldTimer? = OldTimer()

&lt;span style=&#34;color:#75715e&#34;&gt;// ⏱ Wait two seconds ⏱&lt;/span&gt;

old = &lt;span style=&#34;color:#66d9ef&#34;&gt;nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;What do we we see in our output?&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;br&gt;
&amp;hellip;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Uh oh! We forgot some crucial cleanup in our &lt;code&gt;deinit&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;OldTimer&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; timer: Timer
  
  &lt;span style=&#34;color:#75715e&#34;&gt;// ...&lt;/span&gt;

  &lt;span style=&#34;color:#66d9ef&#34;&gt;deinit&lt;/span&gt; {
    timer.invalidate()
  }  
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Now we get the expected results:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Old Timer, go!&lt;br&gt;
Old Timer, go!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;But how easy is it to forget that &lt;code&gt;deinit&lt;/code&gt;? I do it practically every time I use a &lt;code&gt;Timer&lt;/code&gt;, and often in less obvious circumstances than what’s presented here.&lt;/p&gt;
&lt;p&gt;Let’s look at the publisher case:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;NewSchool&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; subscription: AnyCancellable
  &lt;span style=&#34;color:#66d9ef&#34;&gt;init&lt;/span&gt;() {
    subscription = 
    Timer.publish(every:&lt;span style=&#34;color:#ae81ff&#34;&gt;1.0&lt;/span&gt;, on:.main, &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;:.&lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;)
      .autoconnect()
      .sink { &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
        print(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;New School, I choose you!&amp;#34;&lt;/span&gt;)
      }
  }
  
  &lt;span style=&#34;color:#66d9ef&#34;&gt;deinit&lt;/span&gt; {
    subscription.cancel()
  }
}

&lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; new: NewSchool? = NewSchool()

&lt;span style=&#34;color:#75715e&#34;&gt;// ⏱ Two seconds later ⏱&lt;/span&gt;

new = &lt;span style=&#34;color:#66d9ef&#34;&gt;nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;We see:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;New School, I choose you!&lt;br&gt;
New School, I choose you!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Not a big difference, right? Here’s the trick, though: unlike a &lt;code&gt;Timer&lt;/code&gt; which lives on irrespective of our reference to it, the life cycle of a &lt;code&gt;Subscription&lt;/code&gt; is completeley tied up in its value. If it gets set to &lt;code&gt;nil&lt;/code&gt; and/or released, it automatically cancels its connection to its publisher.&lt;/p&gt;
&lt;p&gt;So in our example, because the default behavior of properties like &lt;code&gt;subscription&lt;/code&gt; is to be retained while their object exists and automatically &lt;code&gt;nil&lt;/code&gt;’d out when it’s deallocated, we don’t need an explicit &lt;code&gt;dealloc&lt;/code&gt; statement at all! In other words:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;NewSchool&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; subscription: AnyCancellable
  &lt;span style=&#34;color:#66d9ef&#34;&gt;init&lt;/span&gt;() {
    subscription = 
    Timer.publish(every:&lt;span style=&#34;color:#ae81ff&#34;&gt;1.0&lt;/span&gt;, on:.main, &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;:.&lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;)
      .autoconnect()
      .sink { &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;
        print(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;New School, I choose you!&amp;#34;&lt;/span&gt;)
      }
  }
}

&lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; new: NewSchool? = NewSchool()

&lt;span style=&#34;color:#75715e&#34;&gt;// ⏱ Two seconds later ⏱&lt;/span&gt;

new = &lt;span style=&#34;color:#66d9ef&#34;&gt;nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;still does exactly what we want it to:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;New School, I choose you!&lt;br&gt;
New School, I choose you!&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So publishers and subscriptions present a much more intuitive way to think about cancellation, invalidation, and life cycles. And that’s great! But it’s also worth pointing out they make the default, naïve implementation the correct one. This makes them effective protection against bugs of omission — the value of which shouldn’t be underestimated.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Optional, throws, Result, and async/await</title>
      <link>https://figure.ink/2019/05/02/optional-throws-result.html</link>
      <pubDate>Thu, 02 May 2019 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2019/05/02/optional-throws-result.html</guid>
      <description>&lt;p&gt;I got to write a post over at &lt;a href=&#34;https://nshipster.com&#34;&gt;NSHipster&lt;/a&gt; (😮) this week about the &lt;a href=&#34;https://nshipster.com/optional-throws-result-async-await/&#34;&gt;past, present, and glorious future of error handling in Swift&lt;/a&gt; and how &lt;code&gt;Result&lt;/code&gt; fits in with it all. &lt;a href=&#34;https://twitter.com/jemmons&#34;&gt;Let me know&lt;/a&gt; what you think!&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Exhaustive Properties with Tuples</title>
      <link>https://figure.ink/2019/03/03/exhaustive-properties-with.html</link>
      <pubDate>Sun, 03 Mar 2019 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2019/03/03/exhaustive-properties-with.html</guid>
      <description>&lt;p&gt;One thing I really love about Swift is its exhaustive &lt;code&gt;switch&lt;/code&gt; statement. As programmers, we live with a creeping dread of change and the unforeseen consequences it can wreck on our carefully calibrated computations. And &lt;code&gt;switch&lt;/code&gt; is an excellent hammer with which we can nail down at least one future loose end.&lt;/p&gt;
&lt;p&gt;If we have code that calculates how many spaces a character can move in a game, for example:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;enum&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Character&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; elf, dwarf, human
}


&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;spaces&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; character: Character) -&amp;gt; Int {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; character {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; .elf:
    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;7&lt;/span&gt; &lt;span style=&#34;color:#75715e&#34;&gt;// Spritely!&lt;/span&gt;
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; .dwarf:
    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;3&lt;/span&gt; &lt;span style=&#34;color:#75715e&#34;&gt;// Short legs; big heart.&lt;/span&gt;
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; .human:
    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#ae81ff&#34;&gt;5&lt;/span&gt; &lt;span style=&#34;color:#75715e&#34;&gt;// Even Steven.&lt;/span&gt;
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;…and we later add a dragon:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;enum&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Character&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; elf, dwarf, human, dragon
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;No problem! The Swift compiler let’s us know there’s a spot where we haven’t considered what to do with dragons, and won’t let us continue until we deal with it:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;spaces&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;for&lt;/span&gt; character: Character) -&amp;gt; Int {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; character { &lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;🛑&lt;/span&gt; Switch must be exhaustive
    &lt;span style=&#34;color:#75715e&#34;&gt;//...&lt;/span&gt;
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This future-proofing is such a comfort to me, I cram everything I can in &lt;code&gt;switch&lt;/code&gt;es. But sometimes it’s just not feasible. Let’s look at a simple person model. It can hold a &lt;code&gt;firstName&lt;/code&gt; and/or a &lt;code&gt;lastName&lt;/code&gt;, and put those together in a &lt;code&gt;description&lt;/code&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Person&lt;/span&gt;: CustomStringConvertible {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; firstName: String?
  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; lastName: String?
  

  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; description: String {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; [firstName, lastName]
      .compactMap { $0 }
      .joined(separator: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34; &amp;#34;&lt;/span&gt;)
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;It also has utility methods for letting us know if it has a &lt;em&gt;full&lt;/em&gt; name, and for returning either the first &lt;em&gt;or&lt;/em&gt; last name, whichever is present, for more informal modes of address:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;extension&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Person&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; isFullName: Bool {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;guard&lt;/span&gt;
      firstName &lt;span style=&#34;color:#f92672&#34;&gt;!=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;nil&lt;/span&gt;,
      lastName &lt;span style=&#34;color:#f92672&#34;&gt;!=&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;nil&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;else&lt;/span&gt; {
        &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;false&lt;/span&gt;
    }
    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;true&lt;/span&gt;
  }
  

  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; firstOrLast: String? {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; firstName ?? lastName
  }
}

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;This all looks fairly straightforward, but I’m &lt;em&gt;terrified&lt;/em&gt;. What if later we add a &lt;code&gt;middleName&lt;/code&gt; property? Nothing will break, yet everything will be wrong. It will be up to whomever implements &lt;code&gt;middleName&lt;/code&gt; to search for all the places it might be relevant&lt;sup id=&#34;back1&#34;&gt;&lt;a href=&#34;#foot1&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; and incorporate it.&lt;/p&gt;
&lt;p&gt;How can we get &lt;code&gt;switch&lt;/code&gt;-like exhaustiveness when dealing with the properties of a type? The first step (and our first clue) is to treat the properties as a set. What if we put them in a tuple?&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Person&lt;/span&gt;: CustomStringConvertible {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; name: (first: String?, last: String?)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Accessing the properties of &lt;code&gt;Person&lt;/code&gt; is still painless:&lt;sup id=&#34;back2&#34;&gt;&lt;a href=&#34;#foot2&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; myPerson = Person()
myPerson.name.first = &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;Deedlit&amp;#34;&lt;/span&gt; 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;And we can now rewrite &lt;code&gt;description&lt;/code&gt; and &lt;code&gt;isFullName&lt;/code&gt; in terms of the tuple:&lt;sup id=&#34;back3&#34;&gt;&lt;a href=&#34;#foot3&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; description: String {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; (first, last) = name
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; [first, last]
    .compactMap { $0 }
    .joined(separator: &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34; &amp;#34;&lt;/span&gt;)
}


&lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; isFullName: Bool {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;guard&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; (&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt;?, &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt;?) = name &lt;span style=&#34;color:#66d9ef&#34;&gt;else&lt;/span&gt; {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;false&lt;/span&gt;
  }
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;true&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;But &lt;code&gt;firstOrLast&lt;/code&gt;, which only depends on a first and last name and doesn’t care if we ever add more, can reference the values of the tuple directly:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; firstOrLast: String? {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; name.first ?? name.last
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;em&gt;Now&lt;/em&gt; what happens if we add a middle name?&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;class&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Person&lt;/span&gt;: CustomStringConvertible {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; name: (
    first: String?, 
    middle: String?, 
    last: String?
  )


  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; description: String {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; (first, last) = name
    &lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;🛑&lt;/span&gt; tuples have a different number of elements
	&lt;span style=&#34;color:#75715e&#34;&gt;// ...&lt;/span&gt;
  }
}



&lt;span style=&#34;color:#66d9ef&#34;&gt;extension&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Person&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; isFullName: Bool {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;guard&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; (&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt;?, &lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt;?) = name &lt;span style=&#34;color:#66d9ef&#34;&gt;else&lt;/span&gt; {
    &lt;span style=&#34;color:#960050;background-color:#1e0010&#34;&gt;🛑&lt;/span&gt; tuples have a different number of elements
    }
	&lt;span style=&#34;color:#75715e&#34;&gt;// ...&lt;/span&gt;
  }


  &lt;span style=&#34;color:#66d9ef&#34;&gt;var&lt;/span&gt; firstOrLast: String? {
    &lt;span style=&#34;color:#75715e&#34;&gt;// ...&lt;/span&gt;
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;&lt;code&gt;description&lt;/code&gt; and &lt;code&gt;isFullName&lt;/code&gt; are both flagged with compiler warnings, &lt;code&gt;firstOrLast&lt;/code&gt; just keeps on trucking, and I cut my antacid budget by 4×.&lt;/p&gt;
&lt;p&gt;So, to be clear, habitually shoving all properties into a tuple won’t scale well. But it &lt;em&gt;is&lt;/em&gt; a useful tactic to employ when dealing with models, mocks or anything that has:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;naturally constrained state,&lt;/li&gt;
&lt;li&gt;logic that depends on the shape of said state, and&lt;/li&gt;
&lt;li&gt;a strong affinity towards change in the face of shifting requirements&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When we are confronted with such beasts, we can save our future-selves some consternation by popping properties into tuples.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;foot1&#34;&gt;1:&lt;/span&gt; Think of all the places &lt;code&gt;extension Person&lt;/code&gt; could live if you really want to break out in a cold sweat.&lt;a href=&#34;#back1&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot2&#34;&gt;2:&lt;/span&gt; Though, outside the forced reality of a blog example, the &lt;code&gt;Person&lt;/code&gt; model should be a &lt;code&gt;struct&lt;/code&gt;, its &lt;code&gt;name&lt;/code&gt; should be a &lt;code&gt;let&lt;/code&gt;, and everything immutable. Still, it’s good to know mutable tuples are a thing. &lt;a href=&#34;#back2&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot3&#34;&gt;3:&lt;/span&gt; The &lt;code&gt;(_?, _?)&lt;/code&gt; in &lt;code&gt;isFullName&lt;/code&gt; might look odd. It is a combination of &lt;a href=&#34;https://docs.swift.org/swift-book/ReferenceManual/Patterns.html#ID420&#34;&gt;the Wildcard Pattern&lt;/a&gt; and &lt;a href=&#34;https://docs.swift.org/swift-book/ReferenceManual/Patterns.html#ID520&#34;&gt;the Optional Pattern&lt;/a&gt;. It means, roughly, “a tuple of two non-optional things.” We’ve talked about the Optional Pattern before, &lt;a href=&#34;http://www.figure.ink/blog/2015/12/6/matching-with-swifts-optional-pattern&#34;&gt;over here&lt;/a&gt;.&lt;a href=&#34;#back3&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Conditional Compilation in Swift</title>
      <link>https://figure.ink/2018/07/27/conditional-compilation-in.html</link>
      <pubDate>Fri, 27 Jul 2018 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2018/07/27/conditional-compilation-in.html</guid>
      <description>&lt;p&gt;These great posts (&lt;a href=&#34;https://davedelong.com/blog/2018/07/25/conditional-compilation-in-swift-part-1/&#34;&gt;part1&lt;/a&gt;, &lt;a href=&#34;https://davedelong.com/blog/2018/07/25/conditional-compilation-in-swift-part-2/&#34;&gt;part2&lt;/a&gt;) from &lt;a href=&#34;https://stackoverflow.com/users/115730/dave-delong&#34;&gt;Dave DeLong&lt;/a&gt; show off all sorts of cool tricks we can use to get the most out of our &lt;code&gt;.xcconfig&lt;/code&gt; files. They&amp;rsquo;re of particular interest to those targeting disperate plaforms and architectures, but we can all benefit from a little extra xcconfig-fu.&lt;/p&gt;
&lt;p&gt;H/T: &lt;a href=&#34;https://mjtsai.com/blog/&#34;&gt;Michel Tsai&lt;/a&gt; (who, by the way, just &lt;a href=&#34;https://www.patreon.com/mjtsai/posts&#34;&gt;launched a patrion worthy of your consideration&lt;/a&gt;).&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Custom Types for Powerful Matching</title>
      <link>https://figure.ink/2018/07/23/custom-types-for.html</link>
      <pubDate>Mon, 23 Jul 2018 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2018/07/23/custom-types-for.html</guid>
      <description>&lt;p&gt;Most modern apps have to deal with URLs in one way or another. Let’s say we have an embedded &lt;code&gt;WKWebView&lt;/code&gt;, for example, and we need to decide how to route tapped links. A naive implementation might look something like this:&lt;sup id=&#34;back1&#34;&gt;&lt;a href=&#34;#foot1&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;webView&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; webView: WKWebView,
     decidePolicyFor action: WKNavigationAction, 
     decisionHandler: @escaping [...]) {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;guard&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; url = action.request.url &lt;span style=&#34;color:#66d9ef&#34;&gt;else&lt;/span&gt; {
    decisionHandler(.cancel)
  }
  &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; app = UIApplication.shared

  &lt;span style=&#34;color:#75715e&#34;&gt;//If the URL has one of these special &lt;/span&gt;
  &lt;span style=&#34;color:#75715e&#34;&gt;//schemes, let the OS deal with it.&lt;/span&gt;
  &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;tel&amp;#34;&lt;/span&gt; == url.scheme
     &lt;span style=&#34;color:#f92672&#34;&gt;||&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;sms&amp;#34;&lt;/span&gt; == url.scheme
     &lt;span style=&#34;color:#f92672&#34;&gt;||&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;mailto&amp;#34;&lt;/span&gt; == url.scheme {
    app.open(url, options: [:]) {&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;}
    decisionHandler(.cancel)

  &lt;span style=&#34;color:#75715e&#34;&gt;//Natively handle these paths that&lt;/span&gt;
  &lt;span style=&#34;color:#75715e&#34;&gt;//have special meaning.&lt;/span&gt;
  } &lt;span style=&#34;color:#66d9ef&#34;&gt;else&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; url.path == &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/logout&amp;#34;&lt;/span&gt; {
    performLogout()
    decisionHandler(.cancel)

  } &lt;span style=&#34;color:#66d9ef&#34;&gt;else&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;if&lt;/span&gt; url.path == &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/about&amp;#34;&lt;/span&gt; {
    showAbout()
    decisionHandler(.cancel)

  &lt;span style=&#34;color:#75715e&#34;&gt;//Otherwise, just load it.&lt;/span&gt;
  } &lt;span style=&#34;color:#66d9ef&#34;&gt;else&lt;/span&gt; {
    decisionHandler(.allow)
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;As time passes and our code grows, long chains of &lt;code&gt;if...else&lt;/code&gt; statements like these are just asking for trouble. They encourage a very imperative style that can be hard to decipher after the fact. And it’s hard to know where to insert new conditionals or how said conditions will affect existing flow.&lt;/p&gt;
&lt;h2 id=&#34;an-if-by-any-other-name&#34;&gt;An “if” by Any Other Name&lt;/h2&gt;
&lt;p&gt;A better solution might be to arrange everything in a &lt;code&gt;switch&lt;/code&gt;… but things get ugly fast:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; url {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; u &lt;span style=&#34;color:#66d9ef&#34;&gt;where&lt;/span&gt; u.scheme == &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;tel&amp;#34;&lt;/span&gt;
       &lt;span style=&#34;color:#f92672&#34;&gt;||&lt;/span&gt; u.scheme == &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;sms&amp;#34;&lt;/span&gt;
       &lt;span style=&#34;color:#f92672&#34;&gt;||&lt;/span&gt; u.scheme == &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;mailto&amp;#34;&lt;/span&gt;:
    app.open(url, options: [:]) {&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;}
    decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; u &lt;span style=&#34;color:#66d9ef&#34;&gt;where&lt;/span&gt; u.path == &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/logout&amp;#34;&lt;/span&gt;:
    performLogout()
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; u &lt;span style=&#34;color:#66d9ef&#34;&gt;where&lt;/span&gt; u.path == &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/about&amp;#34;&lt;/span&gt;:
    showAbout()
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;:
    decisionHandler(.allow)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The problem here is we have no way to directly match the parts of the URL we’re interested in. We have to &lt;a href=&#34;https://docs.swift.org/swift-book/ReferenceManual/Patterns.html#//appleref/swift/grammar/value-binding-pattern&#34;&gt;bind the whole thing&lt;/a&gt; and then use a &lt;code&gt;where&lt;/code&gt; clause tease out the components we care about. But &lt;code&gt;where&lt;/code&gt; is essentially just an &lt;code&gt;if&lt;/code&gt; with a different name. The conditional clauses we give it are the same as the ones we passed to &lt;code&gt;if&lt;/code&gt; — complete with all the imperative and readability issues we outlined above.&lt;/p&gt;
&lt;h2 id=&#34;declarative-types&#34;&gt;Declarative Types&lt;/h2&gt;
&lt;p&gt;What we’d really like is a more declarative way to simply tell &lt;code&gt;switch&lt;/code&gt; exactly what we want:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; url {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;mailto:&amp;#34;&lt;/span&gt;:
    &lt;span style=&#34;color:#75715e&#34;&gt;//...&lt;/span&gt;
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; &lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/logout&amp;#34;&lt;/span&gt;:
    &lt;span style=&#34;color:#75715e&#34;&gt;//...&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;The big problem here, though, is most &lt;code&gt;URL&lt;/code&gt; components we care about are indistinguishable by type. They&amp;rsquo;re all &lt;code&gt;String&lt;/code&gt;s in Swift. And not only do they all sort of blend together as we read them, the compiler can’t make heads or tails of it.&lt;sup id=&#34;back2&#34;&gt;&lt;a href=&#34;#foot2&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;So let’s unique everything by adding a few types of our own:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;extension&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;URL&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;struct&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Scheme&lt;/span&gt; {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; value: String
    &lt;span style=&#34;color:#66d9ef&#34;&gt;init&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; value: String) {
      &lt;span style=&#34;color:#66d9ef&#34;&gt;self&lt;/span&gt;.value = value
    }
  }

  &lt;span style=&#34;color:#66d9ef&#34;&gt;struct&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;Path&lt;/span&gt; {
    &lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; value: String
    &lt;span style=&#34;color:#66d9ef&#34;&gt;init&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; value: String) {
      &lt;span style=&#34;color:#66d9ef&#34;&gt;self&lt;/span&gt;.value = value
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Now we can write:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; url {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;tel&amp;#34;&lt;/span&gt;),
	   URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;sms&amp;#34;&lt;/span&gt;),
	   URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;mailto&amp;#34;&lt;/span&gt;):
	app.open(url, options: [:]) {&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;}
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Path(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/logout&amp;#34;&lt;/span&gt;):
	performLogout()
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Path(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/about&amp;#34;&lt;/span&gt;):
	showAbout()
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;:
	decisionHandler(.allow)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;And it looks gorgeous! But, of course, none of this compiles because Swift doesn’t understand how to match a &lt;code&gt;Scheme&lt;/code&gt; or a &lt;code&gt;Path&lt;/code&gt; to a &lt;code&gt;URL&lt;/code&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Expression pattern of type &amp;lsquo;URL.Scheme&amp;rsquo; cannot match values of type &amp;lsquo;URL&amp;rsquo;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;No worries. As &lt;a href=&#34;http://www.figure.ink/blog/2015/2/14/custom-switch-matchers-in-swift&#34;&gt;we talked about earlier&lt;/a&gt; we can teach Swift new &lt;a href=&#34;https://docs.swift.org/swift-book/ReferenceManual/Patterns.html#//appleref/swift/grammar/expression-pattern&#34;&gt;expression patterns&lt;/a&gt; by overloading the &lt;code&gt;~=&lt;/code&gt; operator:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#75715e&#34;&gt;//Given a control expression that evaluates&lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//to a URL, and our Scheme type for the pattern, &lt;/span&gt;
&lt;span style=&#34;color:#75715e&#34;&gt;//Swift will call this to determine a match: &lt;/span&gt;
&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;~=&lt;/span&gt;(pattern: URL.Scheme, value: URL) -&amp;gt; Bool {
  &lt;span style=&#34;color:#75715e&#34;&gt;//We can then use it to compare our `Scheme` &lt;/span&gt;
  &lt;span style=&#34;color:#75715e&#34;&gt;//pattern directly to URL’s `scheme` property.&lt;/span&gt;
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; pattern.value == value.scheme
}


&lt;span style=&#34;color:#75715e&#34;&gt;//Ditto for a URL and our custom Path type:&lt;/span&gt;
&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;~=&lt;/span&gt;(pattern: URL.Path, value: URL) -&amp;gt; Bool {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; pattern.value == value.path
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;h2 id=&#34;composition-considerations&#34;&gt;Composition Considerations&lt;/h2&gt;
&lt;p&gt;One nice side-effect of this “define a type and matching operator” alternative to endless &lt;code&gt;if...else&lt;/code&gt; or &lt;code&gt;case...where&lt;/code&gt; clauses is it provides a better path for composability.&lt;/p&gt;
&lt;p&gt;Imagine our domain logic has some need to match a secure path; that is, a URL with a given path and the added requirement that the scheme is “https”. &lt;code&gt;switch&lt;/code&gt;s are good at handling one pattern &lt;em&gt;&lt;strong&gt;or&lt;/strong&gt;&lt;/em&gt; another:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; url {
&lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Path(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/logout&amp;#34;&lt;/span&gt;),
     URL.Path(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/signout&amp;#34;&lt;/span&gt;):
  &lt;span style=&#34;color:#75715e&#34;&gt;//kill user credentials when *either*&lt;/span&gt;
  &lt;span style=&#34;color:#75715e&#34;&gt;//path is encountered.&lt;/span&gt;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;But they’re not so great when it comes to &lt;em&gt;&lt;strong&gt;and&lt;/strong&gt;&lt;/em&gt;:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; url {
&lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;https&amp;#34;&lt;/span&gt;):
  &lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; url {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Path(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/about&amp;#34;&lt;/span&gt;):
    &lt;span style=&#34;color:#75715e&#34;&gt;//we have to nest our statements to&lt;/span&gt;
    &lt;span style=&#34;color:#75715e&#34;&gt;//compose a scheme *and* a path.&lt;/span&gt;
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;Thankfully we can just define a new type that represents our domain requirements:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;extension&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;URL&lt;/span&gt; {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;struct&lt;/span&gt; &lt;span style=&#34;color:#a6e22e&#34;&gt;SecurePath&lt;/span&gt; {
	&lt;span style=&#34;color:#66d9ef&#34;&gt;let&lt;/span&gt; value: String
	&lt;span style=&#34;color:#66d9ef&#34;&gt;init&lt;/span&gt;(&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; value: String) {
	  &lt;span style=&#34;color:#66d9ef&#34;&gt;self&lt;/span&gt;.value = value
	}
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;And then compose our &lt;code&gt;~=&lt;/code&gt; overload from existing matchers:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;func&lt;/span&gt; &lt;span style=&#34;color:#f92672&#34;&gt;~=&lt;/span&gt;(pattern: URL.SecurePath, value: URL) -&amp;gt; Bool {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;return&lt;/span&gt; URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;https&amp;#34;&lt;/span&gt;) &lt;span style=&#34;color:#f92672&#34;&gt;~=&lt;/span&gt; value 
         &lt;span style=&#34;color:#f92672&#34;&gt;&amp;amp;&amp;amp;&lt;/span&gt; URL.Path(pattern.value) &lt;span style=&#34;color:#f92672&#34;&gt;~=&lt;/span&gt; value
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;p&gt;It’s hard to argue with the readability of the results:&lt;/p&gt;
&lt;div class=&#34;highlight&#34;&gt;&lt;pre tabindex=&#34;0&#34; style=&#34;color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4&#34;&gt;&lt;code class=&#34;language-swift&#34; data-lang=&#34;swift&#34;&gt;&lt;span style=&#34;color:#66d9ef&#34;&gt;switch&lt;/span&gt; url {
  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;tel&amp;#34;&lt;/span&gt;),
	   URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;sms&amp;#34;&lt;/span&gt;),
	   URL.Scheme(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;mailto&amp;#34;&lt;/span&gt;):
	app.open(url, options: [:]) {&lt;span style=&#34;color:#66d9ef&#34;&gt;_&lt;/span&gt; &lt;span style=&#34;color:#66d9ef&#34;&gt;in&lt;/span&gt;}
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.Path(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/logout&amp;#34;&lt;/span&gt;),
       URL.Path(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/signout&amp;#34;&lt;/span&gt;):
	performLogout()
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;case&lt;/span&gt; URL.SecurePath(&lt;span style=&#34;color:#e6db74&#34;&gt;&amp;#34;/about&amp;#34;&lt;/span&gt;):
	showAbout()
	decisionHandler(.cancel)

  &lt;span style=&#34;color:#66d9ef&#34;&gt;default&lt;/span&gt;:
	decisionHandler(.allow)
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;foot1&#34;&gt;1:&lt;/span&gt; If you&amp;rsquo;re not familiar with &lt;code&gt;WKWebView&lt;/code&gt;’s navigation delegate, don’t fret. The important thing to know is the &lt;code&gt;action&lt;/code&gt; contains a URL, and based on that we decide whether we want the web view to load it (&lt;code&gt;decisionHandler(.allow)&lt;/code&gt;) or not load so we can do something else instead (&lt;code&gt;decisionHandler(.cancel)&lt;/code&gt;).&lt;a href=&#34;#back1&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot2&#34;&gt;2:&lt;/span&gt; We could do something “clever” and regex the string looking for a trailing &lt;code&gt;:&lt;/code&gt; to denote a scheme, a leading &lt;code&gt;/&lt;/code&gt; for a path, or an internal &lt;code&gt;.&lt;/code&gt; for a host, etc. Edge cases abound, however. And at that point, we’re essentially reimplementing our own type system on top of &lt;code&gt;String&lt;/code&gt;. Swift has a perfectly good type system already, so I’ll leave the implementation (and attendant disillusionment) as an exercise for the reader.&lt;a href=&#34;#back2&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Optionals as Collections</title>
      <link>https://figure.ink/2018/03/29/optionals-as-collections.html</link>
      <pubDate>Thu, 29 Mar 2018 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2018/03/29/optionals-as-collections.html</guid>
      <description>&lt;p&gt;Sometimes when working on a thing, I get the sense I’m swimming up stream — that it’s just a little &lt;em&gt;too&lt;/em&gt; hard and there has to be a &lt;em&gt;better way&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Sometimes this prompts me to do a little more research and I’ll find the solution staring me in the face. But sometimes I continue to miss the obvious, post about it, and rely on the kindness of smarter people to straighten me out.&lt;/p&gt;
&lt;p&gt;In the case of my last post on &lt;a href=&#34;http://www.figure.ink/blog/2018/3/27/optional-forward-application&#34;&gt;applying optional values to failable initializers&lt;/a&gt;, the role of smarter people is played by &lt;a href=&#34;https://twitter.com/olebegemann/status/978728867883044869&#34;&gt;Ole Begemann&lt;/a&gt;, &lt;a href=&#34;https://twitter.com/willhains/status/978736744521613313&#34;&gt;Will Hains&lt;/a&gt;, and &lt;a href=&#34;https://www.reddit.com/r/swift/comments/87lauh/an_optional_forward_application_operator_in_swift/dwdsheb/&#34;&gt;a bunch of helpful redditors&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&#34;tldr&#34;&gt;TL:DR;&lt;/h2&gt;
&lt;p&gt;I re-invented the wheel with &lt;code&gt;applyOptional&lt;/code&gt;, which is functionally identical to calling &lt;code&gt;flatMap&lt;/code&gt; on an optional type.&lt;/p&gt;
&lt;p&gt;And given this, &lt;a href=&#34;https://www.haskell.org/tutorial/monads.html&#34;&gt;Haskell already has an operator&lt;/a&gt; for calling &lt;code&gt;flatMap&lt;/code&gt; (a.k.a. &lt;code&gt;bind&lt;/code&gt;) on an &lt;code&gt;Optional&lt;/code&gt; (a.k.a. &lt;code&gt;Maybe&lt;/code&gt;) and it’s &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt;. To avoid confusion, we should probably use this if an operator proves necessary.&lt;/p&gt;
&lt;p&gt;Further, this all sounds familiar enough that I think I might have known it at one point or another. But I never really &lt;em&gt;understood&lt;/em&gt; it, not on an intuitive level. When the time came, binding an optional via &lt;code&gt;flatMap&lt;/code&gt; never occurred to me.&lt;/p&gt;
&lt;p&gt;So in an effort to make the lesson stick this time, I&amp;rsquo;ve tried to go back to basics. Thus, the rest of this post.&lt;sup id=&#34;back1&#34;&gt;&lt;a href=&#34;#foot1&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;h2 id=&#34;flattened-arrays&#34;&gt;Flattened Arrays&lt;/h2&gt;
&lt;p&gt;First, how on earth does &lt;code&gt;flatMap&lt;/code&gt; apply to optionals anyway? Isn’t it supposed to deal with nested arrays or something?&lt;/p&gt;
&lt;p&gt;Well, sort of. Let’s start by looking a little more into that nested &lt;code&gt;Array&lt;/code&gt; scenario. We can think of a plain ol’ &lt;code&gt;map&lt;/code&gt; on an &lt;code&gt;Array&lt;/code&gt; like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[T].map((T)-&amp;gt;U) -&amp;gt; [U]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which is to say, &lt;code&gt;map&lt;/code&gt; is a method on an array of &lt;code&gt;T&lt;/code&gt;s that, given a function that turns a lone &lt;code&gt;T&lt;/code&gt; into a &lt;code&gt;U&lt;/code&gt;, will return an array of &lt;code&gt;U&lt;/code&gt;s.&lt;/p&gt;
&lt;p&gt;Now, we can imagine giving our &lt;code&gt;map&lt;/code&gt; a function that returns an &lt;em&gt;array&lt;/em&gt; of &lt;code&gt;U&lt;/code&gt;s instead of a single &lt;code&gt;U&lt;/code&gt;, and then we would end up with something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[T].map((T)-&amp;gt;[U]) -&amp;gt; [[U]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;See how now we&amp;rsquo;re returned a nested &lt;code&gt;[[U]]&lt;/code&gt;? That’s not always super useful. Sometimes we just want &lt;code&gt;[U]&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;flatMap&lt;/code&gt; deals with this by adding an operation that “flattens” the output before returning it. In this case it will unwrap our &lt;code&gt;[[U]]&lt;/code&gt; into a simple &lt;code&gt;[U]&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[T].flatMap((T)-&amp;gt;[U]) -&amp;gt; [U]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This seems like a useful (if rather niche) utility. But how does it apply to &lt;code&gt;Optional&lt;/code&gt;s?&lt;/p&gt;
&lt;h2 id=&#34;flattened-optionals&#34;&gt;Flattened Optionals&lt;/h2&gt;
&lt;p&gt;My big mistake was thinking about optionals as just another &lt;code&gt;enum&lt;/code&gt; when, in several situations, Swift treats them more like &lt;a href=&#34;https://twitter.com/olebegemann/status/978771153778077696&#34;&gt;a collection of zero or one elements&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Viewed in this light, the same examples we used above for arrays can be applied to optionals. A &lt;code&gt;map&lt;/code&gt; works like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;T?.map((T)-&amp;gt;U) -&amp;gt; U?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is, given a collection of zero or one &lt;code&gt;T&lt;/code&gt;s and a function that turns a &lt;code&gt;T&lt;/code&gt; into a &lt;code&gt;U&lt;/code&gt;, &lt;code&gt;map&lt;/code&gt; will return a collection of zero or one &lt;code&gt;U&lt;/code&gt;s.&lt;sup id=&#34;back2&#34;&gt;&lt;a href=&#34;#foot2&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;And just as with our array example, we can imagine a scenario where we pass this &lt;code&gt;map&lt;/code&gt; a function that returns a collection of zero or one &lt;code&gt;U&lt;/code&gt;s instead of a lone &lt;code&gt;U&lt;/code&gt;. This would result in:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;T?.map((T)-&amp;gt;U?) -&amp;gt; U??
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note the &lt;code&gt;Optional&amp;lt;Optional&amp;lt;U&amp;gt;&amp;gt;&lt;/code&gt; at the end there. We’d pretty much always want this to be unwrapped or “flattened” a level before we’d use it, and that’s exactly what &lt;code&gt;flatMap&lt;/code&gt; on an optional does:&lt;sup id=&#34;back3&#34;&gt;&lt;a href=&#34;#foot3&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;T?.flatMap((T)-&amp;gt;U?) -&amp;gt; U?
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&#34;where-have-i-seen-this-before&#34;&gt;Where Have I Seen this Before?&lt;/h2&gt;
&lt;p&gt;If we think back to &lt;a href=&#34;http://www.figure.ink/blog/2018/3/27/optional-forward-application&#34;&gt;the previous post&lt;/a&gt;, I was bemoaning how some failable initializers in Foundation such as &lt;code&gt;URL(string:)&lt;/code&gt; don’t take optional parameters. But looking at it now, we see the signatures of these existing initializers exactly fit what &lt;code&gt;flatMap&lt;/code&gt; expects as a parameter:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;//Takes a String, returns a URL?:
URL.init?(string: String)
//Takes a T, returns a U?:
(T)-&amp;gt;U?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With no further modification we can pass these initializers into a &lt;code&gt;flapMap&lt;/code&gt; on an optional like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let urlString: String? = textField.text
let maybeURL = urlString.flatMap(URL.init)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And so it’s now clear to me why &lt;code&gt;URL(string:)&lt;/code&gt; doesn’t support optional parameters. It would break compatibility with a crucial part of Swift’s collection-processing toolkit.&lt;/p&gt;
&lt;p&gt;But moreover, adding an optional param would be akin to asking &lt;code&gt;URL.init&lt;/code&gt; to accept an array of strings. It’s not &lt;code&gt;URL&lt;/code&gt;’s responsibility to know which elements of what collections to use to instantiate itself. Instead, it’s our program’s job to whip our collections into the accepted element(s), and pass &lt;em&gt;those&lt;/em&gt; on to &lt;code&gt;URL&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;And while it’s sometimes difficult to remember &lt;code&gt;Optional&lt;/code&gt; can, in this sense,  be a collection in need of whipping, it none the less has a full complement of higher order functions (including &lt;code&gt;flatMap&lt;/code&gt;) making it up to the challenge, regardless.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;foot1&#34;&gt;1:&lt;/span&gt; As the &lt;a href=&#34;https://fieldnotesbrand.com&#34;&gt;Field Notes folks say&lt;/a&gt;, “I’m not writing it down to remember it later, I’m writing it down to remember it now.”&lt;a href=&#34;#back1&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot2&#34;&gt;2:&lt;/span&gt; We don’t see this used much in practice because Swift gives us the optional chaining operator as a language feature. Functionally,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let str = maybeURL.map { $0.absoluteString }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let str = maybeURL?.absoluteString
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;are equivalent.&lt;a href=&#34;#back2&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot3&#34;&gt;3:&lt;/span&gt; Note this is also the rational for why the &lt;a href=&#34;https://github.com/apple/swift-evolution/blob/master/proposals/0187-introduce-filtermap.md&#34;&gt;recently deceased&lt;/a&gt; &lt;code&gt;Sequence.flatMap&lt;/code&gt; worked the way it did. If:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[T].map((T)-&amp;gt;[U]) -&amp;gt; [[U]]
[T].flatMap((T)-&amp;gt;[U]) -&amp;gt; [U]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;T?.map((T)-&amp;gt;U?) -&amp;gt; U??
T?.flatMap((T)-&amp;gt;U?) -&amp;gt; U?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;then&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[T].map((T)-&amp;gt;U?) -&amp;gt; [U?]
[T].flatMap((T)-&amp;gt;U?) -&amp;gt; [U]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;makes a certain amount of sense. Especially if we consider both arrays and optionals to be sequences of zero or more elements.&lt;a href=&#34;#back3&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Optional Forward Application</title>
      <link>https://figure.ink/2018/03/27/optional-forward-application.html</link>
      <pubDate>Tue, 27 Mar 2018 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2018/03/27/optional-forward-application.html</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt;&lt;/em&gt;
&lt;a href=&#34;https://twitter.com/olebegemann/status/978728867883044869&#34;&gt;Ole Begemann&lt;/a&gt;, &lt;a href=&#34;https://twitter.com/willhains/status/978736744521613313&#34;&gt;Will Hains&lt;/a&gt;, and &lt;a href=&#34;https://www.reddit.com/r/swift/comments/87lauh/an_optional_forward_application_operator_in_swift/dwdsheb/&#34;&gt;a bunch of helpful redditors&lt;/a&gt; all point out a fundamental oversight I&amp;rsquo;ve made here:&lt;/p&gt;
&lt;p&gt;My implementation of &lt;code&gt;applyOptional&lt;/code&gt;, below, is functionally identical to calling &lt;code&gt;flatMap&lt;/code&gt; on an optional type. And given this, there&amp;rsquo;s already prior art for an operator that calls &lt;code&gt;flatMap&lt;/code&gt; (a.k.a. &lt;code&gt;bind&lt;/code&gt;) on an &lt;code&gt;Optional&lt;/code&gt; (a.k.a. a &lt;code&gt;Maybe&lt;/code&gt; monad): &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://www.figure.ink/blog/2018/3/29/optionals-as-collections&#34;&gt;I talk a little more about this in this post&lt;/a&gt;, but the takeaway is, just use the built-in &lt;code&gt;flatMap&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let urlString: String? = textField.text
let maybeURL = urlString.flatMap(URL.init) 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And if we want to define an operator for this, we should use &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt; instead of my made up &lt;code&gt;|?&amp;gt;&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;infix operator &amp;gt;&amp;gt;=
func &amp;gt;&amp;gt;= &amp;lt;T, U&amp;gt;(x: T?, f: (T)-&amp;gt;U?) -&amp;gt; U? {
  return x.flatMap(f)
}
let urlString: String? = textField.text
let maybeURL = urlString &amp;gt;&amp;gt;= URL.init
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The original post follows:&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Swift’s out-of-the-box compatibility with existing ObjC frameworks is an amazing technical feat and one of its greatest strengths. But that doesn’t mean I’m never annoyed when using, say, Foundation. Among my biggest pet peeves is the lack of optional overloads to common failable initializers like &lt;code&gt;URL(string:)&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let urlString: String? = textField.text
let maybeURL: URL?
if let someString = urlString {
  maybeURL = URL(string: someString)
} else {
  maybeURL = nil
}
// Do something with `maybeURL`...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It’s wordy. It’s got that dangling uninitialized &lt;code&gt;let&lt;/code&gt;
just sort of hanging out. It has branching execution for no good reason.&lt;/p&gt;
&lt;p&gt;And ultimately it just feels unnecessary. The whole idea of a failable initializer is that it can return a &lt;code&gt;nil&lt;/code&gt; in response to invalid input. It seems a small jump to extended the input to include optional types — the &lt;code&gt;.none&lt;/code&gt; values of which we would presume to be invalid. Then &lt;code&gt;nil&lt;/code&gt;s would just pass through.&lt;/p&gt;
&lt;p&gt;But for whatever reason, that’s not how the API were translated to Swift. I’ve worked around this in a number of ways over the years. I started out using the nil coalescing operator:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let urlString: String? = textField.text
let maybeURL = URL(string: urlString ?? &amp;quot;🚫&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;“🚫” is an invalid URL, so when &lt;code&gt;urlString&lt;/code&gt; is &lt;code&gt;nil&lt;/code&gt;, &lt;code&gt;maybeURL&lt;/code&gt; is &lt;code&gt;nil&lt;/code&gt; as well.&lt;/p&gt;
&lt;p&gt;I don’t hate this — it’s concise and has a sort of literal readability to it. But it’s always felt like a hack based on undefined behavior. Eventually I moved to a more conventional solution:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension URL {
  init?(maybeString: String?) {
    guard let string = maybeString else {
      return nil
    }
    self.init(string: string)
  }
}

let urlString: String? = textField.text
let maybeURL = URL(maybeString: urlString)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This works well enough. But it’s just as wordy as our original solution. The only difference is we give it a name behind an extension.&lt;/p&gt;
&lt;p&gt;And therein lies another weakness: we have to define an extension like this for every failable initializer we use. There’s a fair amount of boiler plate in each, and there’s always the chance for collisions when extending Foundation like this.&lt;/p&gt;
&lt;p&gt;Eventually I settled on generic solution in the form of a free function:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func applyOptional&amp;lt;T, U&amp;gt;
     (_ x: T?, to f: (T)-&amp;gt;U?) -&amp;gt; U? {
  guard let someX = x else {
    return nil
  }
  return f(someX)
}

let urlString: String? = textField.text
let maybeURL = applyOptional(urlString,
                  to: URL.init(string:))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This has a lot going for it. Not only can it generically handle optional initializers, it can be applied to functions returning optionals generally. This enhances its potential for reuse and thus its value as an abstraction.&lt;/p&gt;
&lt;p&gt;But it’s never felt quite right. The first parameter feels buried. “Optional” isn’t descriptive enough to give me a sense of its purpose. And I keep reading &lt;code&gt;URL.init(string:)&lt;/code&gt; as a newly created URL rather than a function reference. Something is missing.&lt;/p&gt;
&lt;p&gt;I didn’t realize what until I started watching the excellent &lt;a href=&#34;https://www.pointfree.co&#34;&gt;Point•Free video series&lt;/a&gt;.&lt;sup id=&#34;back1&#34;&gt;&lt;a href=&#34;#foot1&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; Early on they create a Swift version of F#’s forward application operator, &lt;code&gt;|&amp;gt;&lt;/code&gt;. I realized their implementation was very similar to my &lt;code&gt;applyOptional(_:to:)&lt;/code&gt;, and that got me thinking about free functions in terms of operators:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;infix operator |?&amp;gt;

public func |?&amp;gt; &amp;lt;T, U&amp;gt;(x: T?, f: (T)-&amp;gt;U?) -&amp;gt; U? {
  guard let someX = x else {
    return nil
  }
  return f(someX)
}

let urlString: String? = textField.text
let maybeURL = urlString |?&amp;gt; URL.init(string:)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So yeah, I took the triangle operator and put a question mark in it to make it more optional-looking. Nothing ground-breaking, but it feels loads better to use. Freed from their parentheses, the bare &lt;code&gt;urlString&lt;/code&gt; and &lt;code&gt;URL.init(string:)&lt;/code&gt; stand out in their purpose. And the way the operator points the optional into the function ref makes their relation clear in a way the &lt;code&gt;to:&lt;/code&gt; label never quite captured.&lt;/p&gt;
&lt;p&gt;Not that there aren’t tradeoffs, of course. &lt;code&gt;applyOptional&lt;/code&gt; is way easier to google for than &lt;code&gt;|?&amp;gt;&lt;/code&gt;, for one thing. But until Foundation adds &lt;code&gt;init?(string: String?)&lt;/code&gt; initializers,&lt;sup id=&#34;back2&#34;&gt;&lt;a href=&#34;#foot2&#34;&gt;2&lt;/a&gt;&lt;/sup&gt; expect my code to be dotted with these little FP gems.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;foot1&#34;&gt;1:&lt;/span&gt; If you’re reading this blog, I can’t imagine you wouldn’t find entertainment and value in &lt;a href=&#34;https://www.pointfree.co&#34;&gt;these videos&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;My favorite part? Each one is accompanied by a carefully edited transcription. I don’t always have the time or energy to watch a presentation. Reading is sometimes more comfortable. And transcriptions make searching for half-remembered concepts a snap, as well.&lt;a href=&#34;#back1&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot2&#34;&gt;2:&lt;/span&gt; Which I’m still not ruling out…&lt;a href=&#34;#back2&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Dealing with Weak in Closure-based Delegation</title>
      <link>https://figure.ink/2018/03/18/dealing-with-weak.html</link>
      <pubDate>Sun, 18 Mar 2018 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2018/03/18/dealing-with-weak.html</guid>
      <description>&lt;p&gt;&lt;a href=&#34;https://medium.com/anysuggestion/preventing-memory-leaks-with-swift-compile-time-safety-49b845df4dc6&#34;&gt;This post&lt;/a&gt; by &lt;a href=&#34;https://twitter.com/olegdreyman&#34;&gt;Oleg Dreyman&lt;/a&gt; is so clever, clear, and useful, I&amp;rsquo;m temped to call it a &lt;em&gt;must read&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;In a nutshell, using closures for delegates puts the responsibility of ownership management on the delegatee rather than the delegator. But by packaging the delegate into a setter, &lt;a href=&#34;https://medium.com/anysuggestion/preventing-memory-leaks-with-swift-compile-time-safety-49b845df4dc6&#34;&gt;Oleg shows us&lt;/a&gt; we can control how it’s captured with respect to the closure (and, as a bonus, reduce our free-floating closures with more trailing closure syntax).&lt;/p&gt;
&lt;p&gt;While I&amp;rsquo;m not sold this needing to be its own dependency, I&amp;rsquo;m absolutely going to adopt the pattern post haste. Thanks, Oleg!&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Better Strategies Through Types</title>
      <link>https://figure.ink/2018/03/11/better-strategies-through.html</link>
      <pubDate>Sun, 11 Mar 2018 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2018/03/11/better-strategies-through.html</guid>
      <description>&lt;h2 id=&#34;figuring-out-what-not-to-do&#34;&gt;Figuring Out What Not to Do&lt;/h2&gt;
&lt;p&gt;Imagine we’ve written a &lt;code&gt;UIControl&lt;/code&gt; that wraps a button to do some animations whenever it’s tapped:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class BouncyButton: UIControl {
  private weak var button: UIButton!
   
  override init(frame: CGRect) {
    super.init(frame: frame)

    do {
      let b = UIButton(type: .system)
      addSubview(b)
      button = b
    }
    button.addTarget(self,
         action: #selector(handleTap),
         for: .touchUpInside)
 
	// Set frame or constraints...
  }

  @objc func handleTap() {
    //Do some bouncy animations here...
    sendActions(for: .touchUpInside)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We could hardcode our animation in the &lt;code&gt;handleTap()&lt;/code&gt; method, but maybe we need our button to bounce different ways in different contexts. Encapsulating the behavior of a thing in a swappable container is a common enough practice in software design that it has its own pattern — &lt;a href=&#34;https://en.wikipedia.org/wiki/Strategy_pattern&#34;&gt;the strategy pattern&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In Cocoa, strategies have traditionally be implemented via delegates:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protocol BouncyDelegate {
  func animateBounce(for view: UIView)
}
 
class BouncyButton: UIControl {
  let delegate: BouncyDelegate //🤔
  //...
  
  init(frame: CGRect, delegate: BouncyDelegate) {
    self.delegate = delegate
    //...
  }
  
  @objc func handleTap() {
    delegate.animateBounce(for: button)
    sendActions(for: .touchUpInside)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This seems straight-forward enough, but there’s a problem. The delegate is strongly held by our control. You can imagine a view controller with this button in its hierarchy setting itself as the button’s delegate. Then the view controller would own the button, which owns the delegate, which owns the button, which owns… a retain cycle!&lt;/p&gt;
&lt;p&gt;For this reason, the Cocoa convention is to make all delegates &lt;code&gt;weak&lt;/code&gt;. No problem:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;weak let delegate: BouncyDelegate
//🛑: &#39;weak&#39; must be a mutable variable
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Oh, I mean:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;weak var delegate: BouncyDelegate
//🛑: &#39;weak&#39; may not be applied to 
//     non-class-bound protocol
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hmm. We can fix&lt;sup id=&#34;back1&#34;&gt;&lt;a href=&#34;#foot1&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; this with:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protocol BouncyDelegate: class { ... }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But this will prevent us from using &lt;code&gt;struct&lt;/code&gt;s or &lt;code&gt;enum&lt;/code&gt;s to implement our strategy and, at this point, ought make us a little suspicious of what’s going on.&lt;/p&gt;
&lt;h2 id=&#34;something-rotten-in-the-state&#34;&gt;Something Rotten in the State&lt;/h2&gt;
&lt;p&gt;We have to limit our delegate to &lt;code&gt;class&lt;/code&gt; implementations because delegates are assumed to hold mutable state.&lt;/p&gt;
&lt;p&gt;Since they have state, they need to be instantiated. If they need to be instantiated, we have to provision storage for them. If we have to provision storage for them, questions around ownership need to be resolved. Qualifiers like &lt;code&gt;weak&lt;/code&gt; and (the implicit) strong become necessary.&lt;/p&gt;
&lt;p&gt;If we could somehow define our strategies to be stateless things, all of this would cease to be relevant.&lt;/p&gt;
&lt;p&gt;But moreover, the thought of mixing state and strategies ought to give us the heebie-jeebies.&lt;sup id=&#34;back2&#34;&gt;&lt;a href=&#34;#foot2&#34;&gt;2&lt;/a&gt;&lt;/sup&gt; Storing state means a strategy might behave differently depending on the values kept within it. Unless we’re writing a parser, no one wants to have think about every other thing that might have mutated our delegate before us and in what order.&lt;sup id=&#34;back3&#34;&gt;&lt;a href=&#34;#foot3&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;So we want to do away with state in our strategies. And if we’re going to do away with state, then instances are nothing more than chunks of memory we don’t use but still need to manage ownership of. We should get rid of those, too.&lt;/p&gt;
&lt;h2 id=&#34;type-method-acting&#34;&gt;Type Method Acting&lt;/h2&gt;
&lt;p&gt;So rather than holding our strategy’s implementation in instance methods that need to be instantiated, we’re going to move it all up into &lt;a href=&#34;https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html#//apple_ref/doc/uid/TP40014097-CH15-ID241&#34;&gt;type methods on the type&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Let’s start with the protocol:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protocol BouncyDelegate {
  static func animateBounce(for view: UIView)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;static&lt;/code&gt; here indicates a type conforming to &lt;code&gt;BouncyDelegate&lt;/code&gt; must have &lt;code&gt;animageBounce(for:)&lt;/code&gt; defined on its type. Anything can technically conform to this, but I like to use &lt;code&gt;enum&lt;/code&gt;s &lt;a href=&#34;https://www.natashatherobot.com/swift-enum-no-cases/&#34;&gt;because they can never be instantiated&lt;/a&gt;, even accidentally.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;enum ShakeStrategy: BouncyDelegate {
  static func animateBounce(for view: UIButton) {
    let base = CGAffineTransform.identity
    let offset = base.translatedBy(x: 30, y: 0)
    view.transform = offset
    UIView.animate(withDuration: 0.5, delay: 0, 
         usingSpringWithDamping: 0.2, 
         initialSpringVelocity: 0, 
         options: [], 
         animations: { view.transform = base }
         completion: nil)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Great! We have our strategy type defined. Now we have to change our button a bit to use it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class BouncyButton: UIControl {
  let delegate: BouncyDelegate.Type
  //...
  
  init(
       frame: CGRect, 
       delegate: BouncyDelegate.Type) {
    self.delegate = delegate
    //...
  }
  
  @objc func handleTap() {
    delegate.animateBounce(for: button)
    sendActions(for: .touchUpInside)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note we’ve had to change the type of &lt;code&gt;delegate&lt;/code&gt; from &lt;code&gt;BouncyDelegate&lt;/code&gt;, which would be an &lt;em&gt;instance&lt;/em&gt; of a type conforming to our protocol, to &lt;code&gt;BouncyDelegate.Type&lt;/code&gt;, which is the conforming type, &lt;em&gt;itself&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;We’ll initialize our button by passing in our strategy &lt;em&gt;type&lt;/em&gt; like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let button = BouncyButton(
     frame: someRect,
     delegate: ShakeStrategy.self)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note the use of &lt;code&gt;.self&lt;/code&gt; to indicate we want to use the type &lt;em&gt;itself&lt;/em&gt; as our delegate.&lt;/p&gt;
&lt;h2 id=&#34;generic-brand-awareness&#34;&gt;Generic Brand Awareness&lt;/h2&gt;
&lt;p&gt;If all this &lt;code&gt;.Type&lt;/code&gt; and &lt;code&gt;.self&lt;/code&gt; stuff feels a little awkward, it’s probably because Swift already supports this kind of thing as a language feature. It has a specific syntax just for passing around types that are used to specialize implementations. We know it as “generics”.&lt;/p&gt;
&lt;p&gt;We can rewrite our button like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class BouncyButton&amp;lt;Strategy&amp;gt;: UIControl
     where Strategy: BouncyDelegate {
  //...
  
  init(frame: CGRect) {
    //...
  }
  
  @objc func handleTap() {
    Strategy.animateBounce(for: button)s
    sendActions(for: .touchUpInside)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that not only do we get to drop the ownership qualifiers around our &lt;code&gt;delegate&lt;/code&gt; property, we don’t need a &lt;code&gt;delegate&lt;/code&gt; property at all! This, in turn, simplifies our &lt;code&gt;init&lt;/code&gt; and ditches all the confusing &lt;code&gt;.Type&lt;/code&gt; stuff.&lt;sup id=&#34;back4&#34;&gt;&lt;a href=&#34;#foot4&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;.self&lt;/code&gt; stuff disappears, too. We now create our button like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let button = 
  BouncyButton&amp;lt;ShakeStrategy&amp;gt;(frame: someRect)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Cool! But a further, easy-to-overlook benefit is how we’ve moved responsibility for specifying strategy away from init params and into the type. Now if we ever find ourselves allergic to angle brackets&lt;sup id=&#34;back5&#34;&gt;&lt;a href=&#34;#foot5&#34;&gt;5&lt;/a&gt;&lt;/sup&gt; we can alias the whole thing away with another of Swift’s type-related language features:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;typealias ShakyButton = BouncyButton&amp;lt;ShakeStrategy&amp;gt;
let button = ShakyButton(frame: someRect)
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;foot1&#34;&gt;1:&lt;/span&gt; Almost. We’ll still have to make &lt;code&gt;BouncyDelegate&lt;/code&gt; optional, as well.&lt;a href=&#34;#back1&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot2&#34;&gt;2:&lt;/span&gt; The Cocoa convention of passing delegate methods the operative object as their first parameter (&lt;em&gt;i.e.&lt;/em&gt; &lt;code&gt;tableView(_:heightForRowAt:)&lt;/code&gt;) could be seen as a suggestive push in the direction of stateless delegation.&lt;a href=&#34;#back2&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot3&#34;&gt;3:&lt;/span&gt; And those writing parsers wish they didn’t have to.&lt;a href=&#34;#back3&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot4&#34;&gt;4:&lt;/span&gt; Though, as &lt;a href=&#34;https://mjtsai.com/blog/2018/03/12/better-strategies-through-types/&#34;&gt;Michael Tsai points out&lt;/a&gt;, “unlike delegates, the type cannot change at runtime.” Dynamism is a key feature not only of delegates, but also of the strategy pattern, generally. Be aware that once we move to generics, we&amp;rsquo;re giving that up (though we can still swap out types with &lt;code&gt;.self&lt;/code&gt; at runtime, as per the previous example).&lt;a href=&#34;#back4&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot5&#34;&gt;5:&lt;/span&gt; Or if we’re shipping a framework and want to, say, restrict 3rd party customization of our controls beyond certain pre-defined combinations of strategies…&lt;a href=&#34;#back5&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Killing </title>
      <link>https://figure.ink/2017/12/28/killing-tmp-with.html</link>
      <pubDate>Thu, 28 Dec 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/12/28/killing-tmp-with.html</guid>
      <description>&lt;p&gt;How many times have we all caught ourselves writing code like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func makeNext() -&amp;gt; Int {
  let tmp = state
  state += 1
  return tmp
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We want to manipulate some state, but we also want to return it in its pre-manipulated condition. In other words we&amp;rsquo;d like to insert a bit of code right after our return statement:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// No, this doesn&#39;t work.
func makeNext() -&amp;gt; Int {
  return state
  state += 1
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But we can&amp;rsquo;t because nothing after the &lt;code&gt;return&lt;/code&gt; will get executed. So instead we stick our state in a &lt;code&gt;tmp&lt;/code&gt; variable, do what we gotta do, and then return the &lt;code&gt;tmp&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;So what? It&amp;rsquo;s just one more line of code, right?&lt;/p&gt;
&lt;p&gt;The danger here (and with tmp variables everywhere) is that, by definition, they&amp;rsquo;re exact copies of types we&amp;rsquo;re actively working with in the same scope. How they differ isn&amp;rsquo;t semantically clear, and neither the compiler nor code review can stop us from  accidentally substituting one for the other:&lt;sup id=&#34;back1&#34;&gt;&lt;a href=&#34;#foot1&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func makeNext() -&amp;gt; Int {
 let tmp = state
 state += 1
 return state //uh oh!
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thankfully Swift does provide a way for us to squeeze code in after the &lt;code&gt;return&lt;/code&gt; of a method — the documentation just doesn&amp;rsquo;t make this immediately obvious:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Use defer to write a block of code that is executed after all other code in the function…&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Yay!&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;…just before the function returns.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Oh… Um… Well it turns out they&amp;rsquo;re talking about the function returning on the stack and not the &lt;code&gt;return&lt;/code&gt; statement executing in code. So doing something like this works perfectly:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func makeNext() -&amp;gt; Int {
  defer {
    state += 1
  }
  return state
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is true regardless of whether &lt;code&gt;state&lt;/code&gt; has value semantics or not.&lt;/p&gt;
&lt;p&gt;Note this not only avoids confusing our original and &lt;code&gt;tmp&lt;/code&gt; variables, but now the intent of our code has been made clear:&lt;/p&gt;
&lt;p&gt;Before we couldn&amp;rsquo;t know why we were forking off a &lt;code&gt;tmp&lt;/code&gt; unless we analyzed everything that messed with the original &lt;em&gt;and&lt;/em&gt; followed it all the way through to the eventual return of its &lt;code&gt;tmp&lt;/code&gt; copy.&lt;sup id=&#34;back2&#34;&gt;&lt;a href=&#34;#foot2&#34;&gt;2&lt;/a&gt;&lt;/sup&gt; Here, it&amp;rsquo;s clear from the get-go we want to do some stuff with &lt;code&gt;state&lt;/code&gt;. But first we&amp;rsquo;re going to return it.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;foot1&#34;&gt;1:&lt;/span&gt; Actually, in this trivial example, the compiler will warn us that &lt;code&gt;tmp&lt;/code&gt; is unused. But we can easily imagine situations where that will not be the case.&lt;a href=&#34;#back1&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;foot2&#34;&gt;2:&lt;/span&gt; And then, if you&amp;rsquo;re anything like me, all the way back to the top to find where &lt;code&gt;tmp&lt;/code&gt; was made in an attempt to remember what it was before we changed it.&lt;a href=&#34;#back2&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Much Ado About iOS App Architecture</title>
      <link>https://figure.ink/2017/11/08/much-ado-about.html</link>
      <pubDate>Wed, 08 Nov 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/11/08/much-ado-about.html</guid>
      <description>&lt;p&gt;&lt;em&gt;Finally&lt;/em&gt; an &lt;a href=&#34;http://aplus.rs/2017/much-ado-about-ios-app-architecture/&#34;&gt;architecture think piece&lt;/a&gt; for the rest of us:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;PSA: No one is forcing you to implement multiple DataSources in one Controller. To initiate network calls in viewDidLoad. To parse JSONs in UIViewController. To hard-wire Views with Singleton instances.&lt;/p&gt;
&lt;p&gt;If you do that, it’s your fault; don’t blame MVC.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I whole-heartedly endorce all the advice &lt;a href=&#34;https://twitter.com/radiantav&#34;&gt;Aleksandar&lt;/a&gt; gives within.&lt;/p&gt;
&lt;p&gt;(Thanks to &lt;a href=&#34;https://twitter.com/rrenna&#34;&gt;Ryan&lt;/a&gt; for the link!)&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Moving Safety into Types</title>
      <link>https://figure.ink/2017/10/15/moving-safety-into.html</link>
      <pubDate>Sun, 15 Oct 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/10/15/moving-safety-into.html</guid>
      <description>&lt;p&gt;Let&amp;rsquo;s say we have a truck. We want it to be safe, so we give it some seatbelts and airbags.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct Truck {
  var seatbeltFastened: Bool
  var airbagsEnabled: Bool
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And because we care about safety, we don&amp;rsquo;t want to let the truck drive unless the seatbelts are fastened.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension Truck {
  func drive() throws {
    guard seatbeltFastened else {
      throw SafetyError.seatbelt
    }
	guard airbagsEnabled else {
      throw SafetyError.airbag
    }
    // drive away...
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can drive with confidence:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;do {
  myTruck.drive()
} catch {
  print(&amp;quot;Safety violation! Driving disabled!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is pretty nice. To be safe, we have to verify the seatbelt is fastened and the airbags are enabled before we drive. By putting the check in &lt;code&gt;drive()&lt;/code&gt; itself, we don&amp;rsquo;t have to remember to make the check every time we use the truck. And &lt;code&gt;throws&lt;/code&gt; gives us a handy way to recover from any exceptional situations where driving isn&amp;rsquo;t safe.&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s the thing about &lt;code&gt;throws&lt;/code&gt;, though; it tends to leak up into abstractions built on top of it.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s say we&amp;rsquo;re building a shipping API, for example. We might want to ship a package via a truck:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func ship(package: Package, truck: Truck) throws {
  truck.add(package)
  try truck.drive() 
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our &lt;code&gt;ship(package:, truck:)&lt;/code&gt; function looks pretty clean, but note that it&amp;rsquo;s marked &lt;code&gt;throws&lt;/code&gt;. Some logic around how our truck drives has leaked up into our shipping logic, forcing us to deal with it whenever we ship:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;do {
  ship(package: myPackage, truck: myTruck)
} catch {
  //???
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This exposes a few problems:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We&amp;rsquo;re just trying to ship a package. We shouldn&amp;rsquo;t have to manage trucks to do that.&lt;/li&gt;
&lt;li&gt;Even if we wanted to manage trucks, it&amp;rsquo;s not clear from calling &lt;code&gt;ship()&lt;/code&gt; that any errors will come from driving or that the solution might be to, say, fasten seatbelts.&lt;sup id=&#34;r1back&#34;&gt;&lt;a href=&#34;#r1foot&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/li&gt;
&lt;li&gt;We have to write this error checking code &lt;em&gt;every time&lt;/em&gt; we ship something — even when using the same truck!&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We want our truck to be safe. But if we validate its safety when we use it, we leak details up to anything that calls it, limiting its composability.&lt;/p&gt;
&lt;p&gt;This is an example of &lt;a href=&#34;https://www.infoq.com/presentations/Simple-Made-Easy&#34;&gt;complected concerns&lt;/a&gt;. We have two concepts here, driving and safety. We have to pull the two apart:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension Truck {
  func validateSafety() throws {
    guard seatbeltFastened else {
      throw SafetyError.seatbelt
    }
	guard airbagsEnabled else {
      throw SafetyError.airbag
    }
  }

  func drive() {
    // just drive...
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is cool in the sense that, having separated our validation from action, &lt;code&gt;ship(...)&lt;/code&gt; no longer has to care about the state of the &lt;code&gt;Truck&lt;/code&gt; we pass it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;do {
  try myTruck.validateSafety()
  ship(package: myPackage, truck: myTruck)
} catch {
  print(&amp;quot;Safety Violation!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But &lt;em&gt;now&lt;/em&gt; we have to remember to check the safety of our truck &lt;em&gt;every time&lt;/em&gt; before we use it! If we forget once, disaster.&lt;sup id=&#34;r2back&#34;&gt;&lt;a href=&#34;#r2foot&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;So what if instead of verifying safety in a method, we make safety a feature of a type?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct SafeTruck {
  let value: Truck
  
  init(_ truck: Truck) throws {
	try truck.validateSafety()
	value = truck
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We&amp;rsquo;ve taken &lt;code&gt;Truck&lt;/code&gt; and wrapped it in a new type, &lt;code&gt;SafeTruck&lt;/code&gt;, which can only be created with a &lt;code&gt;Truck&lt;/code&gt; that meets its safety requirements.&lt;/p&gt;
&lt;p&gt;Which means we can now rewrite &lt;code&gt;ship(package:, truck:)&lt;/code&gt; to take a &lt;code&gt;SafeTruck&lt;/code&gt; instead of a &lt;code&gt;Truck&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func ship(package: Package, truck: SafeTruck) {
  truck.value.add(package)
  truck.value.drive()
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now Swift does all the work for us:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ship(package: myPackage, truck: myTruck)
//🛑 Cannot convert value of type &#39;Truck&#39; 
//   to expected argument type &#39;SafeTruck&#39;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This isn&amp;rsquo;t magic. We haven&amp;rsquo;t somehow abstracted away the need to catch validation errors. We&amp;rsquo;ve just moved the implicit check we&amp;rsquo;d previously made whenever we used a truck into an explicit check we make on initialization:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;do {
  let safeTruck = try SafeTruck(myTruck)
} catch {
  print(&amp;quot;Truck is not safe!&amp;quot;)
} 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;First, note that by moving validation from a thing that happens on &lt;em&gt;use&lt;/em&gt; (where it could be buried beneath twelve layers of abstraction) to something that happens on &lt;em&gt;creation&lt;/em&gt;, we&amp;rsquo;ve front-loaded it. We now get to handle errors where we have the most specific knowledge about them. To put it another way: there&amp;rsquo;s little doubt why &lt;code&gt;try SafeTruck(myTruck)&lt;/code&gt; might fail.&lt;/p&gt;
&lt;p&gt;But we&amp;rsquo;ve also isolated our checks. We only have to write &lt;code&gt;try...catch&lt;/code&gt; once (on initialization). After that (if our use case permits) we can reuse our safe, validated truck without having to recheck its safety.&lt;sup id=&#34;r3back&#34;&gt;&lt;a href=&#34;#r3foot&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;And because we&amp;rsquo;ve made safety a feature of our type, we have all the brains of Swift&amp;rsquo;s tireless type checker behind us, making sure we never make a mistake.&lt;/p&gt;
&lt;p&gt;After all, when given a type safe language it only makes sense to put safety in types.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;r1foot&#34;&gt;1:&lt;/span&gt; True, we can deduce this information by matching for a specific error (&lt;code&gt;SafetyError.seatbelt&lt;/code&gt; in this case). But knowing the specific error requires we know the implementation of &lt;code&gt;ship(...)&lt;/code&gt; well enough to know what methods on &lt;code&gt;Truck&lt;/code&gt; get called — and then know &lt;code&gt;Truck&lt;/code&gt; well enough to know which methods throw and why.&lt;a href=&#34;#r1back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;r2foot&#34;&gt;2:&lt;/span&gt; Whereby &amp;ldquo;disaster&amp;rdquo; I mean &amp;ldquo;a bug&amp;rdquo;.&lt;a href=&#34;#r2back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;r3foot&#34;&gt;3:&lt;/span&gt; Note this is only true because &lt;code&gt;Truck&lt;/code&gt; is a value type. If &lt;code&gt;SafeTruck&lt;/code&gt; stored a reference to a truck instead of a value, &lt;code&gt;truck&lt;/code&gt; could be mutated behind its back. There&amp;rsquo;d be no way to guarantee a truck that was safe at initialization would still be safe later when actually used.&lt;a href=&#34;#r3back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Deep Thought of the Day Expressed by Reference to Increasingly Irrelevant and Soon to be Forgotten Cartoon Characters</title>
      <link>https://figure.ink/2017/09/20/deep-thought-of.html</link>
      <pubDate>Wed, 20 Sep 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/09/20/deep-thought-of.html</guid>
      <description>&lt;p&gt;Wile E. Coyote&amp;rsquo;s problem wasn&amp;rsquo;t that the Roadrunner was fast (roadrunners top out at 32 km/h, coyotes at 69km/h), it was that he was wily. If he did the obvious, simplest thing and ran the bird down instead of trying to be clever, he&amp;rsquo;d have no difficulty.&lt;/p&gt;
&lt;p&gt;Meditate on this before writing each line of code.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Why Coroutines</title>
      <link>https://figure.ink/2017/09/04/why-coroutines.html</link>
      <pubDate>Mon, 04 Sep 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/09/04/why-coroutines.html</guid>
      <description>&lt;p&gt;Remember how, when Swift introduced us to the concept of &lt;code&gt;Optional&lt;/code&gt;, all of a sudden &lt;a href=&#34;http://www.javiersoto.me/post/106875422394&#34;&gt;explanations&lt;/a&gt; around the &lt;a href=&#34;http://codeplease.io/2015/08/05/monads/&#34;&gt;theory&lt;/a&gt; and &lt;a href=&#34;http://khanlou.com/2015/09/what-the-heck-is-a-monad/&#34;&gt;implementation&lt;/a&gt; of monads became relevant&lt;sup id=&#34;q1back&#34;&gt;&lt;a href=&#34;#q1foot&#34;&gt;1&lt;/a&gt;&lt;/sup&gt; and interesting?&lt;sup id=&#34;q2back&#34;&gt;&lt;a href=&#34;#q2foot&#34;&gt;2&lt;/a&gt;&lt;/sup&gt; Thanks to the &lt;a href=&#34;https://gist.github.com/lattner/429b9070918248274f25b714dcfc7619&#34;&gt;await/async proposal currently being discussed in Swift evolution&lt;/a&gt;, the same is about to happen to another rather computer-sciencey concept: coroutines.&lt;/p&gt;
&lt;p&gt;We&amp;rsquo;re still a long way off from any concrete implementation of coroutines in Swift, but that doesn&amp;rsquo;t mean we can&amp;rsquo;t explore some of the conceptual underpinnings around how and why we might like to use them.&lt;/p&gt;
&lt;p&gt;But to do that we need to begin at the beginning.&lt;/p&gt;
&lt;h2 id=&#34;starting-with-subroutines&#34;&gt;Starting with Subroutines&lt;/h2&gt;
&lt;p&gt;What&amp;rsquo;s a subroutine? Technically it&amp;rsquo;s &lt;a href=&#34;https://en.wikipedia.org/wiki/Subroutine&#34;&gt;a sequence of program instructions that perform a specific task, packaged as a unit&lt;/a&gt;. But we know it better as simple, everyday &lt;em&gt;function&lt;/em&gt;.&lt;sup id=&#34;q3back&#34;&gt;&lt;a href=&#34;#q3foot&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;We tend to take functions for granted, and many of their characteristics get overlooked as just &amp;ldquo;the way things work&amp;rdquo;. For example, the execution of instructions in a function always starts at the top, never in the middle. And when we leave a function (via explicit or implicit &lt;code&gt;return&lt;/code&gt;) we tear it down and can never get back into it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func makeSplines() -&amp;gt; [Spline] {
  var splines = [Spline(1)] // We always start here
  return splines            // Once we leave here…
  splines.append(Spline(2)) // …this never happens.
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, this is so familiar to us it hardly seems worth mentioning. This is just the way functions work. But it&amp;rsquo;s not always desirable. Consider the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func reticulate(splines: [Spline]) -&amp;gt; [Spline] {
  let encabulated = encabulate(splines)
  let frobbed = frob(encabulated)
  return frobbed
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because subroutines always start at the top and can only exit once, any call to &lt;code&gt;reticulate&lt;/code&gt; has to wait for &lt;code&gt;encabulate&lt;/code&gt; and &lt;code&gt;frob&lt;/code&gt; to complete before moving on. If these subroutines block us for a long time, we might wish we could return from &lt;code&gt;reticulate&lt;/code&gt; early to do some work. But as we saw above, once we exit we can never get back — everything after the return gets thrown away.&lt;/p&gt;
&lt;h2 id=&#34;handling-completion-handlers&#34;&gt;Handling Completion Handlers&lt;/h2&gt;
&lt;p&gt;The customary way of working around this in Swift is with completion handlers:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func reticulate(splines: [Spline],
                completion: ([Spline]) -&amp;gt; Void) {
  encabulate(splines) { encabulated in
    frob(encabulated) { frobbed in
      completion(frobbed)
    }
  }
  return
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But let&amp;rsquo;s examine what we&amp;rsquo;ve actually done here. We&amp;rsquo;ve moved the entire body of &lt;code&gt;reticulate&lt;/code&gt; into closures passed to &lt;code&gt;encabulate&lt;/code&gt; and &lt;code&gt;frob&lt;/code&gt;. Then we moved all our return values into these closures&#39; parameters. This frees up &lt;code&gt;reticulate&lt;/code&gt; to exit immediately because it has no body left to execute and no values left to return.&lt;/p&gt;
&lt;p&gt;But remember, subroutines are thrown out the moment they exit. If that&amp;rsquo;s true and &lt;code&gt;reticulate&lt;/code&gt; returns before &lt;code&gt;encabulate&lt;/code&gt; or &lt;code&gt;frob&lt;/code&gt; are done with their work, how does any of this still exist when we try to run their completion handlers?&lt;/p&gt;
&lt;p&gt;The answer lies in our use of closures. From the section on closures in &lt;a href=&#34;https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID103&#34;&gt;The Swift Programming Language&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;A closure can capture constants and variables from the surrounding context in which it is defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We can see this even more clearly if we do a little work in &lt;code&gt;reticulate&lt;/code&gt; before calling &lt;code&gt;encabulate&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func reticulate(splines: [Spline],
                completion: ([Spline]) -&amp;gt; Void) {
  let sorted = splines.sorted
  let reversed = sorted.reversed()
  encabulate(splines) { encabulated in
    completion(encabulated + sorted + reversed)
  }
  return
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here we see that not only does our completion closure still exist, it&amp;rsquo;s able to make use of values defined in &lt;code&gt;reticulate&lt;/code&gt; long after it&amp;rsquo;s exited.&lt;/p&gt;
&lt;p&gt;In fact, from a certain point of view, when we define this closure we&amp;rsquo;re saving the &lt;em&gt;state&lt;/em&gt; and &lt;em&gt;position&lt;/em&gt; of execution within &lt;code&gt;reticulate&lt;/code&gt;. And when we run the closure, we&amp;rsquo;re sort of &lt;em&gt;resuming&lt;/em&gt; execution of &lt;code&gt;reticulate&lt;/code&gt; right where it left off.&lt;/p&gt;
&lt;p&gt;When a closure is used to preserve the execution environment of a routine like this, it&amp;rsquo;s called a &lt;a href=&#34;https://en.wikipedia.org/wiki/Continuation&#34;&gt;continuation&lt;/a&gt;. And passing continuations into other routines to be called in lieu of returning is known as &lt;a href=&#34;https://en.wikipedia.org/wiki/Continuation-passing_style&#34;&gt;continuation passing style&lt;/a&gt; (CPS).&lt;/p&gt;
&lt;h2 id=&#34;wrangling-continuations-with-coroutines&#34;&gt;Wrangling Continuations with Coroutines&lt;/h2&gt;
&lt;p&gt;All of which is a pretty cool trick! But it&amp;rsquo;s also messy:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func reticulate(splines: [Spline],
                completion: ([Spline]) -&amp;gt; Void) {
  // ❶ Execution starts here.
  // ❷ But immediately jumps over this...
  encabulate(splines) { encabulated in
    // ❹ sometime later this is called...
    frob(encabulated) { frobbed in
      // ❻ finally we call the completion
      // which acts like a return even though 
      // it&#39;s deeply nested.
      completion(frobbed)
    }
    // ❺ ...but returns immediately
  }
  // ❸ ...and returns down here
  return
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Between the rat&amp;rsquo;s nest of closures and the execution path that bounces up and down like an EKG, this CPS syntax is far from ideal. All we really want is a way to say &amp;ldquo;suspend self, pass control, be ready to resume.&amp;rdquo; But the concept is so antithetical to the core definition of a subroutine (start at top, exit once forever) that it&amp;rsquo;s hard to express.&lt;/p&gt;
&lt;p&gt;Enter coroutines.&lt;sup id=&#34;q4back&#34;&gt;&lt;a href=&#34;#q4foot&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;Coroutines are different from subroutines. Actually, they&amp;rsquo;re a &lt;a href=&#34;https://en.wikipedia.org/wiki/Coroutine#Comparison_with_subroutines&#34;&gt;more general form of subroutines&lt;/a&gt; that don&amp;rsquo;t follow the &amp;ldquo;has to start at top&amp;rdquo; and &amp;ldquo;can only exit once&amp;rdquo; rules. Instead, coroutines can exit whenever they call other coroutines. And the next time they&amp;rsquo;re called, instead of starting from the top again, they pick up right where they left off.&lt;/p&gt;
&lt;p&gt;This makes them naturally suited to expressing the &amp;ldquo;suspend self, pass control, be ready to resume&amp;rdquo; concept subroutines have such trouble with. To a coroutine, that&amp;rsquo;s just a simple call. They don&amp;rsquo;t need to pass around all that continuation baggage.&lt;sup id=&#34;q5back&#34;&gt;&lt;a href=&#34;#q5foot&#34;&gt;5&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;Once we have the ability to define coroutines, we can rewrite our example (using &lt;a href=&#34;https://gist.github.com/lattner/429b9070918248274f25b714dcfc7619&#34;&gt;the proposed Swift syntax&lt;/a&gt;) as simply:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func reticulate(splines: [Spline])
     async -&amp;gt; [Splines] {
  let encabulated = await encabulate(splines)
  let frobbed = await frob(encabulated)
  return frobbed
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;async&lt;/code&gt; in the &lt;code&gt;func&lt;/code&gt; declaration marks this as a coroutine.  The &lt;code&gt;await&lt;/code&gt; operator marks locations the coroutine can suspend itself (and, later, resume from).&lt;/p&gt;
&lt;p&gt;Compare this to our original, blocking piece of code:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func reticulate(splines: [Spline]) -&amp;gt; [Spline] {
  let encabulated = encabulate(splines)
  let frobbed = frob(encabulated)
  return frobbed
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can see that simply switching from a subroutine to a coroutine gives us our desired non-blocking behavior with near identical expressiveness and zero boilerplate.&lt;/p&gt;
&lt;h2 id=&#34;the-future-and-futures&#34;&gt;The Future (and Futures?)&lt;/h2&gt;
&lt;p&gt;And that&amp;rsquo;s just the tip of the coroutine iceberg. They&amp;rsquo;re the foundation of handy abstractions like &lt;a href=&#34;https://en.wikipedia.org/wiki/Actor_model&#34;&gt;Actors&lt;/a&gt; and &lt;a href=&#34;https://en.wikipedia.org/wiki/Futures_and_promises&#34;&gt;Futures&lt;/a&gt;. They&amp;rsquo;re an &lt;a href=&#34;http://www.boost.org/doc/libs/1_65_0/libs/coroutine/doc/html/coroutine/motivation.html#coroutine.motivation.recursive_sax_parsing&#34;&gt;incredible tool&lt;/a&gt; for parsing and lexing.&lt;/p&gt;
&lt;p&gt;And, if we think about it, coroutines are essentially tiny little state machines. What &lt;em&gt;can&amp;rsquo;t&lt;/em&gt; we do with tiny little state machines?!&lt;/p&gt;
&lt;p&gt;Exploring all these will have to wait for future posts, though. Probably after we get a Swift implementation to play around with. Let&amp;rsquo;s keep our fingers crossed for v5!&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;q1foot&#34;&gt;1:&lt;/span&gt; For geeky values of &amp;ldquo;relevant&amp;rdquo;.&lt;a href=&#34;#q1back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;q2foot&#34;&gt;2:&lt;/span&gt; For &lt;em&gt;highly&lt;/em&gt; geeky values of &amp;ldquo;interesting&amp;rdquo;.&lt;a href=&#34;#q2back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;q3foot&#34;&gt;3:&lt;/span&gt; Or, in cases where the subroutine has access to the state of an object, &lt;em&gt;method&lt;/em&gt;.&lt;a href=&#34;#q3back&#34;&gt;t↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;q4foot&#34;&gt;4:&lt;/span&gt; FINALLY! &lt;a href=&#34;#q4back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;q5foot&#34;&gt;5:&lt;/span&gt; At least conceptually. Coroutines have to stash the state of their execution environment somewhere. And in theory Swift&amp;rsquo;s coroutine implementation could just be sugar for rewriting&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let foo = await bar()
//rest of the body
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;into&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bar(continuation: { foo in
  //rest of the body
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But as an abstraction, coroutines lets us think about suspending and resuming rather than passing continuations. And they do this regardless of how they &amp;ldquo;actually&amp;rdquo; work under the hood.&lt;a href=&#34;#q5back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Author&#39;s Note</title>
      <link>https://figure.ink/2017/08/16/authors-note.html</link>
      <pubDate>Wed, 16 Aug 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/08/16/authors-note.html</guid>
      <description>&lt;p&gt;Some of you have probably noticed I almost never use the second person here (and rarely the first). It&amp;rsquo;s because I don&amp;rsquo;t feel like &lt;em&gt;I&amp;rsquo;m&lt;/em&gt; writing to &lt;em&gt;you&lt;/em&gt;. I feel like &lt;em&gt;we&amp;rsquo;re&lt;/em&gt; working together, here. Trying to understand the misunderstood and fix the broken. Figuring it out.&lt;/p&gt;
&lt;p&gt;But now I&amp;rsquo;m writing to you.&lt;/p&gt;
&lt;p&gt;I&amp;rsquo;m asking you, actually. I&amp;rsquo;m asking, “What do you think about the Google manifesto?”&lt;/p&gt;
&lt;p&gt;Do you think it&amp;rsquo;s been blown out of proportion? That maybe it made some good points? Do you think there&amp;rsquo;s an equivalence between diverse, inclusive speech and speech against diversity and inclusion?&lt;/p&gt;
&lt;p&gt;Fair enough. How about the Nazis who showed up in Charlottesville?&lt;/p&gt;
&lt;p&gt;They have the same manifesto. Do you support them? If you&amp;rsquo;ve already bought into the genetic inferiority of all women, it&amp;rsquo;s really not much of a jump to throw blacks and jews on the fire as well, is it?&lt;/p&gt;
&lt;p&gt;If you believe we have to be “open and honest” about women&amp;rsquo;s genetic limitations so we can “help” them find their proper role in tech, maybe you would stand arm-in-arm with the alt-right to defend that statue of Robert E. Lee? Lee, who wrote “the blacks are immeasurably better off” as slaves and “the painful discipline they are undergoing, is necessary for their instruction as a race” and “will prepare &amp;amp; lead them to better things.” It&amp;rsquo;s the same manifesto.&lt;/p&gt;
&lt;p&gt;The Charlottesville Nazis, the alt-right, who proudly march alongside them, our president, who makes excuses for each, and this Google manifesto prat — they are all of a piece and they are all selling the same scam. Support for one is support for all.&lt;/p&gt;
&lt;p&gt;And support of any means you will find no support here. There will never be a “we” that includes you. Your only goal is to misinform and break.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;We&amp;rsquo;re&lt;/em&gt; here to understand and fix.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Lazy Cartesian Products in Swift</title>
      <link>https://figure.ink/2017/07/30/lazy-cartesian-products.html</link>
      <pubDate>Sun, 30 Jul 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/07/30/lazy-cartesian-products.html</guid>
      <description>&lt;h2 id=&#34;would-you-like-to-play-a-game&#34;&gt;Would you like to play a game?&lt;/h2&gt;
&lt;p&gt;Let&amp;rsquo;s play some battleship! Assuming a standard 10x10 board, we&amp;rsquo;ll need two collections:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let xs = 1...10
let ys = [&amp;quot;A&amp;quot;, &amp;quot;B&amp;quot;, &amp;quot;C&amp;quot;, &amp;quot;D&amp;quot;, &amp;quot;E&amp;quot;, 
          &amp;quot;F&amp;quot;, &amp;quot;G&amp;quot;, &amp;quot;H&amp;quot;, &amp;quot;I&amp;quot;, &amp;quot;J&amp;quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we wanted to hit every square on the grid, we&amp;rsquo;d have to iterate over both lists in a nested loop. &lt;sup id=&#34;p1back&#34;&gt;&lt;a href=&#34;#p1foot&#34;&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;for x in xs {
  for y in ys {
    target(x, y)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There&amp;rsquo;s nothing wrong with this as far as it goes. But it doesn&amp;rsquo;t do a great job of expressing what we&amp;rsquo;re actually trying to accomplish — that is, iterating over every ordered pair of &lt;code&gt;ys&lt;/code&gt; and &lt;code&gt;xs&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;A more declarative way to go about our task might be to generate a new collection which is explicitly the &lt;a href=&#34;https://en.wikipedia.org/wiki/Cartesian_product&#34;&gt;cartesian product&lt;/a&gt; of the two sets, and iterate over that:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;product(xs, ys).forEach { x, y in
  target(x, y)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Great! Only one minor problem: &lt;code&gt;product&lt;/code&gt; doesn&amp;rsquo;t exist.&lt;/p&gt;
&lt;h2 id=&#34;force-majeure&#34;&gt;Force Majeure&lt;/h2&gt;
&lt;p&gt;Building something like &lt;code&gt;product&lt;/code&gt; isn&amp;rsquo;t super hard. The trickiest part is getting all the generics right so it can be used with, say, a closed range just as well as with an array.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func product&amp;lt;X, Y&amp;gt;(_ xs: X, _ ys: Y) -&amp;gt;
  [(X.Element, Y.Element)]
  where X: Collection, Y: Collection {
    var orderedPairs: [(X.Element, Y.Element)] = []
    for x in xs {
      for y in ys {
        orderedPairs.append((x, y))
      }
    }
    return orderedPairs
 }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But when we calculate all the ordered pairs of two sets, the size of the resultant set is (as the name implies) the &lt;em&gt;product&lt;/em&gt; of both sets. That&amp;rsquo;s no big deal when we&amp;rsquo;re talking a 10x10 grid. But if we&amp;rsquo;re dealing with 10k elements, we can benefit from a more lazy approach that stores the individual sets and generates their products on the fly, as needed.&lt;/p&gt;
&lt;h2 id=&#34;walls-first-virtue&#34;&gt;Wall&amp;rsquo;s First Virtue&lt;/h2&gt;
&lt;p&gt;Let&amp;rsquo;s start by building an iterator:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public struct CartesianProductIterator&amp;lt;X, Y&amp;gt;: 
     IteratorProtocol where
     X: IteratorProtocol, 
     Y: Collection {

  public typealias Element = (X.Element, Y.Element)
 
  public mutating func next() -&amp;gt; Element? {
    //...
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Why is our generic type &lt;code&gt;X&lt;/code&gt; an iterator but we force &lt;code&gt;Y&lt;/code&gt; to conform to &lt;code&gt;Collection&lt;/code&gt;? If you look at the nested loop in our naive example above, you&amp;rsquo;ll see that while we iterate over &lt;code&gt;xs&lt;/code&gt; only once, we actually loop over &lt;code&gt;ys&lt;/code&gt; a number of times (an &lt;code&gt;xs.count&lt;/code&gt; number of times, to be precise).&lt;/p&gt;
&lt;p&gt;&lt;code&gt;IteratorProtocol&lt;/code&gt; allows us to iterate over a set exactly once, so it&amp;rsquo;s perfect for our &lt;code&gt;X&lt;/code&gt; type. But only &lt;code&gt;Collection&lt;/code&gt; guarantees us the ability to non-destructively traverse a sequence over and over. So &lt;code&gt;Y&lt;/code&gt; must be a little more constrained.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s add an initializer to store our iterator, collection, and related curiosities as properties:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private var xIt: X
private let yCol: Y
 
private var x: X.Element?
private var yIt: Y.Iterator

public init(xs: X, ys: Y) {
  xIt = xs
  yCol = ys
 
  x = xIt.next()
  yIt = yCol.makeIterator()
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;First note &lt;code&gt;xIt&lt;/code&gt; is a &lt;code&gt;var&lt;/code&gt;. Iterators mutate themselves in the course of serving up &lt;code&gt;next()&lt;/code&gt;, so our copy of &lt;code&gt;xs&lt;/code&gt; must be mutable.&lt;/p&gt;
&lt;p&gt;Also, our ultimate goal here is to take values from &lt;code&gt;xIt&lt;/code&gt; and for each of them iterate over the all the values of &lt;code&gt;yCol&lt;/code&gt;. We prep for this by pulling the first value out of &lt;code&gt;xIt&lt;/code&gt; into &lt;code&gt;x&lt;/code&gt; and making an iterator for &lt;code&gt;yCol&lt;/code&gt; called &lt;code&gt;yIt&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;And note &lt;code&gt;x&lt;/code&gt; needs to be optional. We&amp;rsquo;ll ultimately iterate over &lt;code&gt;xIt&lt;/code&gt; until we hit the end — and we&amp;rsquo;ll know we hit the end when &lt;code&gt;x&lt;/code&gt; is &lt;code&gt;nil&lt;/code&gt;.&lt;sup id=&#34;p2back&#34;&gt;&lt;a href=&#34;#p2foot&#34;&gt;2&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;With all that settled, let&amp;rsquo;s move on to our implementation of &lt;code&gt;next()&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&#34;the-next-step&#34;&gt;The NeXT Step&lt;/h2&gt;
&lt;p&gt;The first step of &lt;code&gt;next()&lt;/code&gt; is simple; pull a value out of &lt;code&gt;yIt&lt;/code&gt; each time it&amp;rsquo;s called and pair it with the same ol&#39; &lt;code&gt;x&lt;/code&gt; we set in the initializer (providing, of course, &lt;code&gt;x&lt;/code&gt; isn&amp;rsquo;t &lt;code&gt;nil&lt;/code&gt;)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public mutating func next() -&amp;gt; Element? {
  guard let someX = x else {
    return nil
  }
 
  guard let someY = yIt.next() else {
    return nil
  }
 	 
  return (someX, someY)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There. Now each call to &lt;code&gt;next()&lt;/code&gt; returns &lt;code&gt;x&lt;/code&gt; and whatever the next value of &lt;code&gt;yIt&lt;/code&gt; is. But what do we do once we hit the end of &lt;code&gt;yIt&lt;/code&gt;? We want to bump &lt;code&gt;x&lt;/code&gt; to the next value of &lt;code&gt;xIt&lt;/code&gt;, create a new &lt;code&gt;yIt&lt;/code&gt; from our collection — and then do the whole thing over again.&lt;/p&gt;
&lt;p&gt;Anytime we say to ourselves &amp;ldquo;…and then do the whole thing over again,&amp;rdquo; it&amp;rsquo;s a sign recursion is in our future.&lt;/p&gt;
&lt;h2 id=&#34;the-end-is-the-beginning-is-the-end&#34;&gt;The End is the Beginning is the End&lt;/h2&gt;
&lt;p&gt;There&amp;rsquo;s nothing magical about recursion. To do it, we just need to call a method from within the implementation of itself. We&amp;rsquo;ll do it here when we run out of values in &lt;code&gt;yIt&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public mutating func next() -&amp;gt; Element? {
  guard let someX = x else {
    return nil
  }
 
  guard let someY = yIt.next() else {
    return next() //Recursion!
  }
 	 
  return (someX, someY)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But there are two things we need to pay attention to whenever we write recursive routines.&lt;/p&gt;
&lt;p&gt;The first is making sure we don&amp;rsquo;t loop indefinitely. We&amp;rsquo;ll do that by setting &lt;em&gt;conditions for terminating&lt;/em&gt; the recursion, and then making sure we &lt;em&gt;move towards that condition&lt;/em&gt; with each iteration.&lt;/p&gt;
&lt;p&gt;Our termination condition already exists. It&amp;rsquo;s that top &lt;code&gt;guard&lt;/code&gt;. If &lt;code&gt;x&lt;/code&gt; is ever &lt;code&gt;nil&lt;/code&gt;, we&amp;rsquo;re out.&lt;/p&gt;
&lt;p&gt;So all we have to do is make sure we&amp;rsquo;re moving towards a state where &lt;code&gt;x&lt;/code&gt; is &lt;code&gt;nil&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public mutating func next() -&amp;gt; Element? {
  guard let someX = x else {
    return nil
  }
 
  guard let someY = yIt.next() else {
	    yIt = yCol.makeIterator()
	    x = xIt.next()
	    return next()
	  }
 	 
  return (someX, someY)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There. Now every time we hit the end of &lt;code&gt;yIt&lt;/code&gt;, we not only make a new one from our collection, but we also pull the next &lt;code&gt;x&lt;/code&gt; from &lt;code&gt;xIt&lt;/code&gt;. Eventually, &lt;code&gt;xIt&lt;/code&gt; will run out of elements, and &lt;code&gt;x&lt;/code&gt; will be &lt;code&gt;nil&lt;/code&gt;. End of recursion.&lt;/p&gt;
&lt;h2 id=&#34;adventures-in-meta&#34;&gt;Adventures in Meta&lt;/h2&gt;
&lt;p&gt;The second thing to look out for when writing recursively is blowing the stack. A &lt;a href=&#34;https://en.wikipedia.org/wiki/Stack_overflow&#34;&gt;stack overflow&lt;/a&gt; happens when you call too many functions in a row without returning.&lt;sup id=&#34;p3back&#34;&gt;&lt;a href=&#34;#p3foot&#34;&gt;3&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;We can easily see how recursion might cause this to happen. Basically, when we call &lt;code&gt;next()&lt;/code&gt; from inside &lt;code&gt;next()&lt;/code&gt; we dig one level deeper in the stack. If calling &lt;code&gt;next()&lt;/code&gt; in &lt;code&gt;next()&lt;/code&gt; causes us to call &lt;code&gt;next()&lt;/code&gt;, now we&amp;rsquo;re another level deep. Get too deep, and we error out with a busted stack.&lt;/p&gt;
&lt;p&gt;Thankfully we can see the only time we call &lt;code&gt;next()&lt;/code&gt; from inside &lt;code&gt;next()&lt;/code&gt; is when &lt;code&gt;yIt.next()&lt;/code&gt; returns &lt;code&gt;nil&lt;/code&gt;. So the only way we can dig deeper in the stack is if &lt;code&gt;yIt.next()&lt;/code&gt; returns &lt;code&gt;nil&lt;/code&gt; many times in a row. And the only way that could happen is if &lt;code&gt;yCol&lt;/code&gt; is empty.&lt;sup id=&#34;p4back&#34;&gt;&lt;a href=&#34;#p4foot&#34;&gt;4&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;So we&amp;rsquo;ll short circuit that specific case with a &lt;code&gt;guard&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public mutating func next() -&amp;gt; Element? {
  guard !yCol.isEmpty else {
    return nil
  }
 
  guard let someX = x else {
    return nil
  }
 
  guard let someY = yIt.next() else {
	    yIt = yCol.makeIterator()
	    x = xIt.next()
	    return next()
	  }
 	 
  return (someX, someY)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&#34;free-as-in-function&#34;&gt;Free as in Function&lt;/h2&gt;
&lt;p&gt;And so, finally, we can lazily iterate over every ordered pair of our collections — all while only storing the collections themselves, not their product. But the syntax is a bit awkward:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let xs = 1...10
let ys = [&amp;quot;A&amp;quot;, &amp;quot;B&amp;quot;, &amp;quot;C&amp;quot;, &amp;quot;D&amp;quot;, &amp;quot;E&amp;quot;, 
          &amp;quot;F&amp;quot;, &amp;quot;G&amp;quot;, &amp;quot;H&amp;quot;, &amp;quot;I&amp;quot;, &amp;quot;J&amp;quot;]
var it = CartesianProductIterator(
     xs: xs.makeIterator(), 
     ys: ys)
while let (x, y) = it.next() {
  target(x, y)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&amp;rsquo;s wrap this in a &lt;code&gt;Sequence&lt;/code&gt; to get access to &lt;code&gt;for...in&lt;/code&gt;, &lt;code&gt;forEach&lt;/code&gt;, and &lt;a href=&#34;https://developer.apple.com/documentation/swift/sequence#2850533&#34;&gt;the rest&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public struct CartesianProductSequence&amp;lt;X, Y&amp;gt;: 
     Sequence where 
     X: Sequence,
     Y: Collection {
  public typealias Iterator =
       CartesianProductIterator&amp;lt;X.Iterator, Y&amp;gt;
  
  private let xs: X
  private let ys: Y
  
  public init(xs: X, ys: Y) {
    self.xs = xs
    self.ys = ys
  }
  
  public func makeIterator() -&amp;gt; Iterator {
    return Iterator(xs: xs.makeIterator(), 
                    ys: ys)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And as a finishing touch let&amp;rsquo;s add a a top-level function to make chaining little more readable:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public func product&amp;lt;X, Y&amp;gt;(_ xs: X, _ ys: Y) -&amp;gt;
     CartesianProductSequence&amp;lt;X, Y&amp;gt; where 
     X: Sequence, 
     Y: Collection {
  return CartesianProductSequence(xs: xs, ys: ys)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And just like that, our battleship dreams have become reality:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let xs = 1...10
let ys = [&amp;quot;A&amp;quot;, &amp;quot;B&amp;quot;, &amp;quot;C&amp;quot;, &amp;quot;D&amp;quot;, &amp;quot;E&amp;quot;,
          &amp;quot;F&amp;quot;, &amp;quot;G&amp;quot;, &amp;quot;H&amp;quot;, &amp;quot;I&amp;quot;, &amp;quot;J&amp;quot;]

product(xs, ys).forEach { x, y in
  target(x, y)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As ever, &lt;a href=&#34;https://gist.github.com/jemmons/d3ca0e29ae3b913ce1c42b21790d807c&#34;&gt;here&amp;rsquo;s a gist&lt;/a&gt; of all this together in one place. Compliments of the house.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;&lt;span id=&#34;p1foot&#34;&gt;1:&lt;/span&gt; I know Battleship™ was invented before Descartes or something, and insists on calling out the lettered Y axis before the numbered X one. I tried a version of this post where the imaginary &lt;code&gt;target(_:_:)&lt;/code&gt; function took its &lt;code&gt;y&lt;/code&gt; parameter before the &lt;code&gt;x&lt;/code&gt;. I was constitutionally incapable of publishing it.&lt;a href=&#34;#p1back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;p2foot&#34;&gt;2:&lt;/span&gt; Or it could be &lt;code&gt;nil&lt;/code&gt; right now. If &lt;code&gt;xIt&lt;/code&gt; is an iterator over an empty set, &lt;code&gt;x&lt;/code&gt; will be &lt;code&gt;nil&lt;/code&gt; by the end of initialization.&lt;a href=&#34;#p2back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;p3foot&#34;&gt;3:&lt;/span&gt; Ironically, I didn&amp;rsquo;t find the &lt;a href=&#34;https://stackoverflow.com/questions/26158/how-does-a-stack-overflow-occur-and-how-do-you-prevent-it&#34;&gt;answer here&lt;/a&gt; particularly compelling.&lt;a href=&#34;#p3back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;span id=&#34;p4foot&#34;&gt;4:&lt;/span&gt; Specifically: if &lt;code&gt;yCol&lt;/code&gt; is empty, then every time we call &lt;code&gt;next()&lt;/code&gt;, we&amp;rsquo;re going to immediately call &lt;code&gt;return next()&lt;/code&gt; over and over again until we hit the end of &lt;code&gt;xIt&lt;/code&gt;. If &lt;code&gt;xIt&lt;/code&gt; is long, this could easily be enough to overflow the stack.&lt;a href=&#34;#p4back&#34;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Update: Matching NSErrors</title>
      <link>https://figure.ink/2017/07/24/update-matching-nserrors.html</link>
      <pubDate>Mon, 24 Jul 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/07/24/update-matching-nserrors.html</guid>
      <description>&lt;p&gt;Good news, everyone!&lt;/p&gt;
&lt;p&gt;While &lt;a href=&#34;http://www.figure.ink/blog/2017/7/23/matching-nserror-in-catch&#34;&gt;my original post on this topic&lt;/a&gt; might be of some small interest in a general &amp;ldquo;strategies for using expression patterns&amp;rdquo; kind of way, Swift provides a &lt;em&gt;much better solution&lt;/em&gt; for the specific problem of matching &lt;code&gt;NSError&lt;/code&gt;s.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;https://twitter.com/jckarter/status/889522879812976641&#34;&gt;Joe Groff tweets&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;NSErrors&lt;/code&gt; are bridged to error structs in Swift.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;What does that mean in practice? You can find all the gory details in &lt;a href=&#34;https://github.com/apple/swift-evolution/blob/master/proposals/0112-nserror-bridging.md&#34;&gt;SE-0112&lt;/a&gt;, but the long and the short of it is, depending on the &lt;code&gt;domain&lt;/code&gt; of a given &lt;code&gt;NSError&lt;/code&gt;, Swift automatically bridges it to a struct describing that domain. In the case of &lt;code&gt;NSURLErrorDomain&lt;/code&gt;, for example, Swift will bridge to a &lt;a href=&#34;https://developer.apple.com/documentation/foundation/urlerror&#34;&gt;URLError&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let error = NSError(domain: NSURLErrorDomain,
                code: NSURLErrorTimedOut)
error is URLError //&amp;gt; true
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This alone lets us deal with &lt;code&gt;NSError&lt;/code&gt;s in a much more declarative way without thinking about domains (and that&amp;rsquo;s not to mention all the goodies it gives us that we used to have to dig through &lt;code&gt;userInfo&lt;/code&gt; for — like &lt;a href=&#34;https://developer.apple.com/documentation/foundation/urlerror/2293717-failingurl&#34;&gt;failingURL&lt;/a&gt;!)&lt;/p&gt;
&lt;p&gt;But &lt;a href=&#34;https://twitter.com/jckarter/status/889525440393523200&#34;&gt;there&amp;rsquo;s more&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Looks like Foundation provides the &lt;code&gt;~=(T.Code, T)&lt;/code&gt; matcher for you.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So to match a timeout in Swift without writing &lt;em&gt;any&lt;/em&gt; code, it&amp;rsquo;s actually as simple as:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;catch URLError.timedOut {
  print(&amp;quot;timed out!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wow! As &lt;a href=&#34;https://twitter.com/dgregor79/status/889542643067138048&#34;&gt;Doug Gregor writes&lt;/a&gt;,&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;You shouldn&amp;rsquo;t need to match on &lt;code&gt;NSError&lt;/code&gt; nowadays, unless someone is vending an error code not marked with &lt;code&gt;NS_ERROR_ENUM&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I wish I had learned about this a lot earlier. Spread the word! Please and thank you.&lt;/p&gt;
</description>
    </item>
    
    <item>
      <title>Matching NSError in a catch</title>
      <link>https://figure.ink/2017/07/23/matching-nserror-in.html</link>
      <pubDate>Sun, 23 Jul 2017 01:00:00 -0500</pubDate>
      
      <guid>http://figure.micro.blog/2017/07/23/matching-nserror-in.html</guid>
      <description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;EXCITING UPDATE!&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Swift is way more on top of this than I originally gave it credit for. The TL;DR is you can actually match &lt;code&gt;NSError&lt;/code&gt;s using their structs like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;catch URLError.timedOut {
  print(&amp;quot;timed out!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;a href=&#34;http://www.figure.ink/blog/2017/7/24/update-matching-nserrors&#34;&gt;updated post over here&lt;/a&gt; has all the details.&lt;/p&gt;
&lt;p&gt;For context, the rest of the original is provided blow. But seriously, &lt;a href=&#34;http://www.figure.ink/blog/2017/7/24/update-matching-nserrors&#34;&gt;check out the update&lt;/a&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;Say we&amp;rsquo;re writing some sort of networking library on top of &lt;code&gt;URLSession&lt;/code&gt;. We might define some domain-specific errors that only make sense in the context of our library — unexpected headers or things like that:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;enum RequestError: Error {
  case missingContentType
  case missingBody
  //...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And these would be really easy for a client using our library to catch:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let net = AmazingNetworkThing()
do {
  try net.fetchRequest(myRequest)
} catch RequestError.missingContentType {
  print(&amp;quot;unknown content type&amp;quot;)
} catch {
  //...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But the vast majority of network-related errors would actually be raised by the &lt;a href=&#34;https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes&#34;&gt;URL loading system itself&lt;/a&gt;. And that&amp;rsquo;s &lt;code&gt;Foundation&lt;/code&gt;-level API, which means it raises &lt;code&gt;NSError&lt;/code&gt;s. Which, in turn, means a consumer of our library would have to catch a simple timeout something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;do {
  try net.fetchRequest(myRequest)
} catch let error as NSError where
     error.domain == NSURLErrorDomain &amp;amp;&amp;amp;
     error.code == NSURLErrorTimedOut {
  print(&amp;quot;timed out!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By comparison, this feels overly wordy and very imperative.&lt;/p&gt;
&lt;p&gt;We could, of course, catch every &lt;code&gt;NSError&lt;/code&gt; thrown by &lt;code&gt;URLSession&lt;/code&gt; in our library, and wrap it in a custom &lt;code&gt;enum&lt;/code&gt;-based error for easier matching by the client. But a few problems with this approach:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;That&amp;rsquo;s a lot of boilerplate. &lt;code&gt;NSURLErrorDomain&lt;/code&gt; defines constants for 49 error codes. And there could be more that are undocumented. Which brings us to…&lt;/li&gt;
&lt;li&gt;We don&amp;rsquo;t control &lt;code&gt;URLSession&lt;/code&gt;. By abstracting over part of its API in our library, we&amp;rsquo;re putting ourselves on the hook for keeping pace with Apple devs from point-release to point-release. And they have a bigger team than ours. Which also suggests…&lt;/li&gt;
&lt;li&gt;&lt;code&gt;URLSession&lt;/code&gt; is much more widely adopted than our library. Consumers of our lib way down the stack might be expecting a &lt;code&gt;NSURLErrorDomain&lt;/code&gt; error rather than our custom, one-off wrapper.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;So rather than wrapping the error, a better solution is to wrap &lt;em&gt;the matcher.&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct ErrorMatcher {
  let domain: String
  let code: Int
}
 
func ~=(p: ErrorMatcher, v: Error) -&amp;gt; Bool {
  return 
     p.domain == (v as NSError).domain &amp;amp;&amp;amp;
     p.code == (v as NSError).code
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;See &lt;a href=&#34;http://www.figure.ink/blog/2015/2/14/custom-switch-matchers-in-swift&#34;&gt;this post&lt;/a&gt; for more on that funky &lt;code&gt;~=&lt;/code&gt; operator.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Using this, we can more elegantly and declaratively match &lt;em&gt;any&lt;/em&gt; &lt;code&gt;NSError&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;do {
  try net.fetchRequest(myRequest)
} catch ErrorMatcher(
     domain: NSURLErrorDomain,
     code: NSURLErrorTimedOut) {
  print(&amp;quot;timed out!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And if we were to add a little sugar for a domain of particular concern to us, well who would blame us?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension ErrorMatcher {
  static func urlDomain(_ c: Int) -&amp;gt; ErrorMatcher {
    return ErrorMatcher(
       domain: NSURLErrorDomain, 
       code: c)
}
 
// Then...
do {
  try net.fetchRequest(myRequest)
} catch ErrorMatcher.urlDomain(NSURLErrorTimedOut){
  print(&amp;quot;timed out!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And if a given domain/code pair were common enough, we could even:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension ErrorMatcher {  
  static let urlTimeout = 
     ErrorMatcher.urlDomain(NSURLErrorTimedOut)
}

// Thus...
do {
  try net.fetchRequest(myRequest)
} catch ErrorMatcher.urlTimeout {
  print(&amp;quot;timed out!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thankfully we don&amp;rsquo;t have to toss out all these existing, localized, very well documented &lt;code&gt;NSError&lt;/code&gt; babies with the bath water of imperative matching. Leveraging Swift&amp;rsquo;s expression patterns, we can have declarative &lt;code&gt;enum&lt;/code&gt;-like matching in our &lt;code&gt;catch&lt;/code&gt; clauses — even with &lt;code&gt;NSError&lt;/code&gt;s.&lt;/p&gt;
</description>
    </item>
    
  </channel>
</rss>
