<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Måns Bernhardt on Medium]]></title>
        <description><![CDATA[Stories by Måns Bernhardt on Medium]]></description>
        <link>https://medium.com/@mans.bernhardt?source=rss-19780e21de4f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0hS-q02ODGup8dTsPo0faw.jpeg</url>
            <title>Stories by Måns Bernhardt on Medium</title>
            <link>https://medium.com/@mans.bernhardt?source=rss-19780e21de4f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:16:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mans.bernhardt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introducing Form — Layout, styling, and event handling]]></title>
            <link>https://medium.com/@mans.bernhardt/introducing-form-layout-styling-and-event-handling-b668d09bb4e6?source=rss-19780e21de4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b668d09bb4e6</guid>
            <category><![CDATA[styling]]></category>
            <category><![CDATA[reactive]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Måns Bernhardt]]></dc:creator>
            <pubDate>Fri, 29 Jun 2018 11:21:38 GMT</pubDate>
            <atom:updated>2018-07-01T13:36:05.631Z</atom:updated>
            <content:encoded><![CDATA[<p>Building UIs for iOS applications means to layout, style and react to events. Even though UIKit provides most of what we need, there are still areas where the experience can be improved. For example, the indirection enforced by the pervasive use of delegates and selectors forces your code to be split apart. It would also be nice if we could have access to more of Swift’s expressive power such as value types and generics when working with UIKit.</p><p>With the introduction of the <a href="https://medium.com/izettle-engineering/introducing-flow-42de51988aea">Flow framework</a> we presented a fundamental programming model for working with UI events. We followed up with the <a href="https://medium.com/izettle-engineering/introducing-presentation-presenting-ui-made-easy-134d3fbe9311">Presentation framework</a> for a more formalized way of presenting view controllers from model to result. Form, introduced in this article, concludes by focusing on the content inside our view controllers.</p><p>To showcase the main ideas behind the <a href="https://github.com/iZettle/Form">Form framework</a> we will build a simple messages application based on a Message model:</p><pre>struct Message: Hashable {<br>  var title: String<br>  var body: String<br>}</pre><p>The application will consist of a view listing our messages and a view for composing new messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnXSYq9xbVLMnffhmvwt0w.png" /><figcaption>Messages and compose views using system styling</figcaption></figure><h4>Building table-like UIs</h4><p>We start out by building a form for composing new messages. We want our form to be styled and laid out as a table view. Table-like layouts are common in iOS applications, such as iOS’s general settings. However, building forms using table views can be tricky because of the indirection enforced by data sources, delegates, and cells. If we on top of that introduce some dynamism to our table’s content, this can result in some serious juggling of section and row indices.</p><p>Form provides UI components that with the help of Flow, removes this indirection by building tables using stack views laid out and styled as table views.</p><p>In our compose message example below, we extend UIViewController with a presentComposeMessage() method that adds two fields for editing the title and body of a message. The method also adds navigation items for canceling and saving, that when tapped will complete the future returned from the method to notify that we are done:</p><pre>extension UIViewController {<br>  func presentComposeMessage() -&gt; Future&lt;Message&gt; {<br>    self.displayableTitle = &quot;Compose Message&quot;<br><br>    let form = FormView()<br>    let section = form.appendSection()<br><br>    let title = section.appendRow(title: &quot;Title&quot;).append(UITextField(placeholder: &quot;title&quot;))<br>    let body = section.appendRow(title: &quot;Body&quot;).append(UITextField(placeholder: &quot;body&quot;))<br><br>    let isValid = combineLatest(title, body).map {<br>      !$0.isEmpty &amp;&amp; !$1.isEmpty<br>    }<br><br>    let save = navigationItem.addItem(UIBarButtonItem(system: .save), position: .right)<br>    let cancel = navigationItem.addItem(UIBarButtonItem(system: .cancel), position: .left)<br><br>    return Future { completion in<br>      let bag = DisposeBag()<br><br>      bag += isValid.atOnce().bindTo(save, \.enabled)<br><br>      bag += save.onValue {<br>        let message = Message(title: title.value, body: body.value)<br>        completion(.success(message))<br>      }<br><br>      bag += cancel.onValue { <br>        completion(.failure(CancelError()))<br>      }<br><br>      bag += self.install(form) { scrollView in<br>        bag += scrollView.chainAllControlResponders(shouldLoop: true, returnKey: .next)<br>        title.provider.becomeFirstResponder()<br>      }<br><br>      return bag<br>    }<br>  }<br>}</pre><p>When creating the fields and bar items above we use convenience initializers that take a style parameter with a default value. The defaults used for these initializers can be globally overridden such as shown in the following screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rj9_sbr8eO2cuWxKv_F3rQ.png" /><figcaption>Messages and compose views using custom styling</figcaption></figure><p>However, you can create your own styles and explicitly pass them when constructing your UI components:</p><pre>extension TextStyle {<br>  static let header = TextStyle(font: ...)<br>}<br><br>let header = UILabel(value: &quot;Welcome&quot;, style: .header)</pre><h4>Populate table views</h4><p>While you can use forms (introduced above) for building tables with uniform row types, such as:</p><pre>let messages: [Message]<br>for message in messages {<br>  section.appendRow(title: message.title, subtile: message.body)<br>}</pre><p>this would not be efficient for large tables. To solve this, Form provides utilities for rendering these using UITableViews instead. This is showcased in the view controller presenting the messages list presented below. In this example, we pass the messages as a signal. That way we can listen for changes and update the UI when the messages list is updated, for example after composing a new message:</p><pre>extension UIViewController {<br>  // Returns a `Disposable` to keep activities alive while being presented.<br>  func present(messages: ReadSignal&lt;[Message]&gt;) -&gt; Disposable {<br>    displayableTitle = &quot;Messages&quot;<br>    let bag = DisposeBag()<br><br>    let tableKit = TableKit&lt;EmptySection, Message&gt;(bag: bag)<br><br>    bag += messages.atOnce().onValue {<br>      tableKit.set(Table(rows: $0))<br>    }<br><br>    bag += install(tableKit)<br><br>    return bag<br>  }<br>}</pre><p>To be able to present our Message model in a table cell, we need to describe how to create views from it and how to reuse them. This is handled by conforming your model to the Reusable protocol:</p><pre>extension Message: Reusable {<br>  static func makeAndConfigure() -&gt; (make: RowView, configure: (Message) -&gt; Disposable) {<br>    let row = RowView(title: &quot;&quot;, subtitle: &quot;&quot;)<br>    return (row, { message in<br>      row.title = message.title<br>      row.subtitle = message.body<br>      // Returns a `Disposable` to keep activities alive while being presented.<br>      return NilDisposer() // No activities.<br>    })<br>  }<br>}</pre><p>Both the messages’ and compose view’s tables, even though implemented differently, are styled using the same styles and use the same defaults.</p><h4>Bring it all together</h4><p>To complete our sample app, we will show how we can add a compose button to the messages view to present the compose view and then update our messages model with the newly composed message:</p><pre>let bag = DisposeBag()<br>let messages = ReadWriteSignal([Message(...), ...])<br>let messagesController = UIViewController()<br><br>// Handle presentation of messagesController<br><br>bag += messagesController.present(messages: messages.readOnly())<br><br>bag += messagesController.navigationItem<br>  .addItem(UIBarButtonItem(system: .compose), position: .right)<br>  .onValue {<br>     let composeController = UIViewController()<br>     composeController.presentComposeMessage().onValue { message in<br>        messages.value.insert(message, at: 0)<br>        // Handle dismissal of composeController<br>     }<br>     <br>     // Handle presentation of composeController<br>  }</pre><h4>Summary</h4><p>If you have read the <a href="https://medium.com/izettle-engineering/introducing-presentation-presenting-ui-made-easy-134d3fbe9311">Introducing Presentation</a> article you will recognize that it builds on the same messages example shown above. However, in that article, we focused on the presentation of view controllers and the data going in and out, whereas in this article we have focused on what goes into a view controllers view.</p><p>Even though <a href="https://github.com/iZettle/Presentation">Presentation</a> and <a href="https://github.com/iZettle/Form">Form</a> can be used independently, they were evolved and designed to work together. At <a href="https://izettle.com/">iZettle</a>, we use both frameworks throughout the iZettle app with the benefit of having a more consistent and robust code-base that is easier to reason and more fun to maintain.</p><p>In this article, we have only showcased a small part of what Form has to offer. If you want to learn more we recommend that have a look at <a href="https://github.com/iZettle/Form">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b668d09bb4e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Presentation — Formalizing presentations from model to result]]></title>
            <link>https://medium.com/@mans.bernhardt/introducing-presentation-presenting-ui-made-easy-134d3fbe9311?source=rss-19780e21de4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/134d3fbe9311</guid>
            <category><![CDATA[presentations]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[reactive]]></category>
            <dc:creator><![CDATA[Måns Bernhardt]]></dc:creator>
            <pubDate>Tue, 15 May 2018 06:32:13 GMT</pubDate>
            <atom:updated>2018-05-15T08:38:11.352Z</atom:updated>
            <content:encoded><![CDATA[<p>View controllers play a central role when building iOS applications. However, building, managing and presenting view controllers is not always straightforward. There are many questions that need to be answered, and many alternatives to consider:</p><ul><li>How is model data passed to a controller?</li><li>How is a result passed back to the caller?</li><li>When and where to perform setup and cleanup?</li><li>Where to put our business logic?</li><li>How to test our UI?</li><li>Should we use storyboards or build our UI programmatically?</li><li>Should we use IBOutlets and delegates, or reactive programming?</li><li>How to present other controllers?</li><li>Where to place common code shared between controllers?</li></ul><p>The <a href="https://github.com/iZettle/Presentation">Presentation library</a> for Swift and iOS aims to improve the situation by:</p><ul><li>Formalizing the driving of presentations from model to result.</li><li>Introducing tools and patterns for improving separation of concerns.</li><li>Providing conveniences for presenting view controllers and managing of their lifetime.</li></ul><p>Even though Presentation is flexible it is also opinionated and has a preferred way of building presentations:</p><ul><li>Be explicit about model data and results.</li><li>Build and layout UIs programmatically.</li><li>Use reactive programming for event handling.</li><li>Prefer small reusable components and extensions to subclassing.</li></ul><p>The Presentation framework builds heavily upon the <a href="https://github.com/iZettle/Flow">Flow framework</a> to handle event handling, asynchronous flows, and lifetime management. For an introduction to Flow, we recommend reading the <a href="https://medium.com/izettle-engineering/introducing-flow-42de51988aea">Introducing Flow</a> article.</p><p>To showcase the main ideas behind Presentation we will build a simple messages application.</p><h4>Listing messages</h4><p>The main UI of our sample app will be a listing of messages described by the model:</p><pre>struct Messages {<br>  let messages: ReadSignal&lt;[Message]&gt;<br>}</pre><p>The Messages model describes the data required to present the messages UI. Here we use a basic value type Message to describe a message. As messages can be added and removed, for example, if being refreshed from a backend service or by our own UI, it will be modeled using a Signal. A signal is an abstraction for observing events over time that is part of the <a href="https://github.com/iZettle/Flow">Flow</a> library.</p><p>Given an instance of Messages, we want to materialize this into something we can present. This is formalized by the Presentable protocol:</p><pre>public protocol Presentable {<br>  associatedtype Matter<br>  associatedtype Result<br><br>  func materialize() -&gt; (Matter, Result)<br>}</pre><p>For a view controller presentation, the type of Matter is a UIViewController or a sub-class of thereof. For our Messages, the Result type will be a Disposable to indicate that there is no explicit result. Disposable abstracts lifetime management and is used to keep observers and other activities with a lifetime alive while being presented. Once the presentation is done and dismissed the returned disposable will be disposed to end those activities.</p><p>We conform Messages to Presentable by implementing materialize(). For our messages UI we need to set up a table view together with its data source and then update the table based on the messages signal:</p><pre>extension Messages: Presentable {<br>  func materialize() -&gt; (UIViewController, Disposable) {    <br>    // Construct viewController and setup data source...<br>    let viewController = UITableViewController()<br>    let dataSource = ...<br>    <br>    // Setup event handling<br>    let bag = DisposeBag()<br><br>    // Update source and table when messages is updated<br>    bag += messages.atOnce().onValue { messages in<br>      dataSource.messages = messages<br>      viewController.tableView.reloadData()<br>    }<br><br>    return (viewController, bag)<br>  }<br>}</pre><p>Conforming Messages to Presentable not only provides a formalized way to build presentations but also provides conveniences to present those:</p><pre>let messages = Messages(...)<br>presentingViewController.present(messages)</pre><h4>Composing a message</h4><p>Let us continue by extending our app to allow the composing of new messages:</p><pre>struct ComposeMessage { }</pre><p>Our ComposeMessage presentable does not need any model data. But in comparison to Messages, it will have a result, the composed message. As this result will be produced asynchronously it will be returned as a Future&lt;Message&gt;. The Future type represents a result that might not yet be available and is also part of <a href="https://github.com/iZettle/Flow">Flow</a>.</p><p>A ComposeMessage is materialized by constructing a plain view controller and setting its view. We also set up button observers to complete the returned future when tapping send or cancel:</p><pre>extension ComposeMessage: Presentable {<br>  func materialize() -&gt; (UIViewController, Future&lt;Message&gt;) {<br>    // Setup view controller and views      <br>    let viewController = UIViewController()        <br>    let cancelButton = UIBarButtonItem(...)<br>    let postButton = UIBarButtonItem(...)<br>    viewController.view = ...<br>    <br>    return (viewController, Future { completion in<br>      // Setup event handling<br>      let bag = DisposeBag()<br>            <br>      bag += cancelButton.onValue { <br>        completion(.failure(PresentError.dismissed)) <br>      }<br>                        <br>      bag += postButton.onValue {<br>        let message = Message(...) // Construct from text fields<br>        completion(.success(message))<br>      }<br>            <br>      return bag<br>    })<br>  }<br>}</pre><p>When present() is being called with a presentable returning a future, it will in its turn also return a future that will complete with the presentable&#39;s result once the presentation is done:</p><pre>let compose = ComposeMessage(...)<br>presentingViewController.present(compose).onValue { message in<br>  // Called with a composed message on dismiss<br>}</pre><p>We can now extend Messages to provide a Presentation of a ComposeMessage.</p><pre>struct Messages {<br>  let messages: ReadSignal&lt;[Message]&gt;<br>  let composeMessage: Presentation&lt;ComposeMessage&gt;<br>}</pre><p>By adding a ComposeMessage to the model, we relieve the Messages presentable from the need to know how to construct a ComposeMessage. This is a great way to decouple the two UIs and removes the need to forward any model data needed to construct and present other presentations.</p><p>Moreover, by also wrapping the composeMessage in a Presentation we can remove details how to present it. The Presentation wrapper is basically a presentable bundled together with presentation parameters such the style of presentation to use (modal, popover, etc.).</p><p>Let us extend Messages with a compose button that will open the compose view by extending its materialize with:</p><pre>let composeButton = UIBarButtonItem(...)<br><br>bag += composeButton.onValue {<br>  viewController.present(self.composeMessage)<br>}</pre><h4>Initialize our presentables</h4><p>We have shown how to define and materialize our presentables, but not how to initialize them. It is important to realize that the data needed to initialize a presentable is not necessary data that the presentable itself need to know about. To make this decoupling of initialization and presentation more explicit, it could be useful to separate these into separate files, and potentially separate modules as well. The initializer could, for example, be given access to resources not available from the presentable’s own module.</p><p>So let us wrap up our example by writing an initializer for Messages:</p><pre>extension Messages {<br>  init(messages: [Message]) {<br>    let messagesSignal = ReadWriteSignal(messages)<br>    self.messages = messagesSignal.readOnly()<br>    <br>    let compose = Presentation(ComposeMessage(), style: .modal)<br>    self.composeMessage = compose.onValue { message in<br>      messagesSignal.value.insert(message, at: 0)<br>    }<br>  }<br>}</pre><p>Here we can see that Presentation also allows adding actions and transformations to be called upon presentation and dismissal. In this case, we will set up an action to be called once the compose presentation is being successfully dismissed with the newly composed message. The new message will just be prepended to our messagesSignal that will signal our Messages presentable to update its table view.</p><p>Note that the above initialization of Messages is just one of many potential implementations. In a more realistic example, we might include network requests and some kind of persistence store such as CoreData. But however we chose to implement this, it will not affect our presentable type and its materialize implementation. We might even have several initializers for different purposes such as production, unit-testing and sample apps.</p><p>A useful way to view a presentable is as a recipe on how to present something. Having an instance of a presentable does not mean that any UI has yet been constructed. The user might never choose to compose a message, or might compose more than one. But we still just have one instance of the compose presentable.</p><h4>Summary</h4><p>In this article, we demonstrated how we can formalize the presentation of view controllers and how the Presentation framework can help us out. We saw how we decoupled different presentables from each other as well as how we decoupled the presentation from the initialization of these. By being more formal and explicit about what is needed to present some UI and what the result of that presentation will be, our code will be easier to reason about, more testable, and easier to maintain. Presentation also makes the presentation and dismissals of view controller easier to work with and removes many issues related to view controller subclassing and handling of their lifetimes.</p><p>We hope that this article introduced you to new ways to think about view controllers and their presentation. By applying these ideas throughout our iZettle app, we not only have a more robust app, but its UI code is now more consistent and exposed for unit testing. If you want to learn more about Presentation and the ideas introduced in this article we recommend that have a look at <a href="https://github.com/iZettle/Presentation">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134d3fbe9311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Design — Deriving Future]]></title>
            <link>https://medium.com/@mans.bernhardt/deriving-future-607aea9abdee?source=rss-19780e21de4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/607aea9abdee</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Måns Bernhardt]]></dc:creator>
            <pubDate>Mon, 07 May 2018 17:58:32 GMT</pubDate>
            <atom:updated>2018-05-07T19:21:11.731Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explain what asynchronous operations are, why they are useful, and how their APIs are typically designed. Specifically, we will look at an API for performing network requests. Step by step, we will improve this API, first by introducing the Result&lt;T&gt; type, and later on, by abstracting the asynchronous operation itself, by deriving the Future&lt;T&gt; type. We will also show how these two types could be implemented and extended with useful operations. In the end, this will lead to code that is more composable, easier to reason about as well as to maintain.</p><h4>Asynchronous operations</h4><p>When building applications interacting with a user, a goal is to keep the application responsive at all time. It is thus important to not perform long-running operations that will block the UI. This is one reason why many APIs used in UI intensive applications are asynchronous. Being asynchronous means that the caller will not block while executing an operation using the API, but instead, the API will call the user back when the result is available.</p><p>A common reason for an API to be asynchronous is that it models access to external services. These services often end up accessing some hardware. As most hardware have much longer latencies than the main CPU, it does make sense to use the CPU for other work while awaiting the result. External services are also often unreliable by nature, which means that they might fail. So it is common that many asynchronous APIs need to be able to report those failures.</p><p>A common asynchronous operation is a network request. On Apple platforms, we typically use URLSession&#39;s task-based APIs such as:</p><pre>extension URLSession {<br>  func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTask<br>}</pre><p>The signature of the method hints that it is asynchronous as the expected Data result is not immediately returned. Instead, a completionHandler closure is passed to the API. This closure will be called as soon as a result is available or when the operation failed for some reason.</p><p>So let us focus in on the completionHandler. We will ignore the less used URLResponse to simplify the API a bit. What does it tell us?</p><pre>completionHandler: (Data?, Error?) -&gt; Void</pre><p>We would expect to get some data back or if something went wrong an error. But as a consumer of this API we actually have to handle four cases:</p><pre>switch (data, error) {<br>  case (data?, nil): // Received data<br>  case (nil, error?): // Received error<br>  case (data?, error?): // Received both data and an error?<br>  case (nil, nil): // Received neither data nor an error?<br>}</pre><p>By reading the documentation for dataTask() we can see that the last two cases should never occur, and it should be safe to ignore them. But it would be great if we did not have to rely on documentation to express this.</p><h4>Introducing the Result enum</h4><p>The completionHandler introduced above originates from Objective-C, and hence is limited to what can be expressed in Objective-C. Swift, on the other hand, has a more powerful type-system making it easier to express many of our ideas in a more type-safe way. One of Swift&#39;s constructs are enums with associated values. This is a really powerful construct that would let us express the either Data or Error as:</p><pre>enum Result {<br>  case success(Data)<br>  case failure(Error)<br>}</pre><p>Further, by using Swift generics, Result can be generalized to work with any success type Value instead of just Data:</p><pre>enum Result&lt;Value&gt; {<br>  case success(Value)<br>  case failure(Error)<br>}</pre><p>With Result&lt;T&gt; at our disposal, we can now simplify our network API. When at it, we will also make the API more focused on the data result than the data task itself:</p><pre>func data(at url: URL, completion: @escaping (Result&lt;Data&gt;) -&gt; Void) {<br>  dataTask(with: url) { data, _, error in<br>    if let error = error {<br>      completion(.failure(error))<br>    } else {<br>      completion(.success(data!))<br>    }<br>  }.resume()<br>}</pre><h4>Transforming results</h4><p>It is not that common to work directly with an instance of Data. Typically, we would instead transform the data into more specialized types. In most applications, this would likely be into some JSON container, or into types being deserialized from JSON. Let us investigate how we can transform Data into JSON.</p><p>For this article, we will use the framework <a href="https://github.com/izettle/Lift">Lift</a> to work with JSON. Lift wraps JSON using the Jar container type. It comes with an initializer accepting raw JSON data:</p><pre>extension Jar {<br>  init(json data: Data) throws<br>}</pre><p>So how do we go about transforming a Result&lt;Data&gt; into a Result&lt;Jar&gt;. Firstly, we need a way to extract the success value:</p><pre>extension Result {<br>  func getValue() throws -&gt; Value {<br>    switch self {<br>    case .success(let value): return value<br>    case .failure(let error): throw error<br>    }<br>  }<br>}</pre><p>And given a value or a thrown error, we need a way to put them back into a Result&lt;T&gt;. This is like running getValue() in reverse:</p><pre>extension Result {<br>  init(getValue: () throws -&gt; Value) {<br>    do {<br>      self = .success(try getValue())<br>    } catch {<br>      self = .failure(error)<br>    }<br>  }<br>}</pre><p>Combining the two, allow us to first extract the data from a Result&lt;Data&gt;, then transform it to JSON using Jar(json:), and then finally construct a Result&lt;Jar&gt; with the resulting JSON:</p><pre>let jarResult = Result&lt;Jar&gt; {<br>  try Jar(json: dataResult.getValue())<br>}</pre><p>This is called a map(), the operation of transforming a value inside a box into another one:</p><pre>extension Result {<br>  func map&lt;O&gt;(_ transform: (Value) throws -&gt; O) -&gt; Result&lt;O&gt; {<br>    return Result&lt;O&gt; { try transform(getValue()) }<br>  }<br>}</pre><p>The implementation of map() is a great example of how we can compose new methods from more general ones. The map() function is a very useful function that you will find in other box like types as well, such as Swift&#39;s optional and container types. Using map(), our new JSON method now becomes:</p><pre>func json(at url: URL, completion: @escaping (Result&lt;Jar&gt;) -&gt; Void) {<br>  return data(at: url) { result in<br>    completion(result.map { try Jar(json: $0) })<br>  }<br>}</pre><p>Here we can see how we chained two operations, one asynchronous and one synchronous, both of which might fail. Thanks to Result&lt;T&gt; and map(), we could focus on the &quot;happy cases&quot; and avoid writing explicit error handling.</p><h4>Introducing the Future type</h4><p>We now have two asynchronous APIs, one returning Data and the other Jar. As for the asynchronous part of those APIs, the completion function itself, the only thing that differs between the two is the type of their results, the T in Result&lt;T&gt;. It would be nice if we could encapsulate this completion closure in a type and make it generic:</p><pre>struct Future&lt;Value&gt; {<br>  let onResult: (@escaping (Result&lt;Value&gt;) -&gt; Void) -&gt; Void<br>}</pre><p>This would let us rewrite data(at:completion:) as:</p><pre>func data(at url: URL) -&gt; Future&lt;Data&gt; {<br>  return Future { completion in<br>    self.data(at: url, completion: completion)<br>  }<br>}</pre><p>To listen on a future’s result, we would just call onResult() and pass a completion handler:</p><pre>let dataAtURL = session.data(at: url)<br>...<br>dataAtURL.onResult { result in<br>  ...<br>}</pre><p>This is really powerful. We have abstracted the idea of an asynchronous operation and encapsulated it into a type. Instances of this type could be passed around, this without any need to know the origin of the operation nor having to drag along any of its dependencies.</p><p>Having a type representing asynchronous operations also means we can extend it with useful functionality. One of those is map(), as Future&lt;T&gt; similar to Result&lt;T&gt; also acts as a box wrapping a value:</p><pre>func map&lt;O&gt;(_ transform: @escaping (Value) throws -&gt; O) -&gt; Future&lt;O&gt; {<br>  return Future&lt;O&gt; { completion in<br>    self.onResult { result in<br>      completion(result.map(transform))<br>    }<br>  }<br>}</pre><p>Our JSON method can now be simplified to:</p><pre>func json(at url: URL) -&gt; Future&lt;Jar&gt; {<br>  return data(at: url).map { try Jar(json: $0) }<br>}</pre><p>It is now so trivial that it might not even be worth adding a convenience method for it.</p><h4>Improving the implementation</h4><p>The current implementation of Future&lt;T&gt;, although elegantly simple, has some issues. One is, that you have to call onResult() on the future to start it. If no one ever calls onResult(), its asynchronous operation will never be performed. But the expectation is that it should always perform, even though no one is interested in the result. Some APIs make this explicit by letting the completion handler be optional. You would expect, that e.g. an animation would run even though you passed a nil completion handler.</p><p>A related problem is that nothing stops us from calling onResult() more than once. This would currently result in a new asynchronous operation being kicked off for each call to onResult(). This problem did not exist when we passed a completion handler, where at most one could be passed.</p><p>Given the above, it makes sense to model Future&lt;T&gt; to always execute its work, even though there potentially are no ones interested in the result. We might attempt to restrict the number of listeners to at most one. Potentially, we could assert or complete with an error if calling onResult() a second time. But in the context of the user, there might be no way of knowing if somebody is already listening on the future or not. And even if it was, it is not obvious what the user should do with that information. So it also makes sense to allow multiple listeners, but still only execute the future once.</p><p>So let us update Future&lt;T&gt;&#39;s internals by adding an initializer that immediately calls back the provided onResult closure. The previous onResult member now becomes a function instead where we add received completions to a completions array. As the future now has internal state, we also update it to be a class instead of a struct:</p><pre>final class Future&lt;Value&gt; {<br>  var completions: [(Result&lt;Value&gt;) -&gt; Void] = []<br>  <br>  init(onResult: @escaping (@escaping (Result&lt;Value&gt;) -&gt; Void) -&gt; Void) {<br>    onResult { result in<br>      self.completions.forEach { $0(result) }<br>    }<br>  }<br>  <br>  func onResult(_ completion: @escaping (Result&lt;Value&gt;) -&gt; Void) {<br>    completions.append(completion)<br>  }<br>}</pre><p>This solves our two original issues but introduces a new one. What if the future has already been completed at the time onResult() is called? That would mean that its completion callback will never be called. This will be an issue even if we call onResult() immediately after creating the future, as the future could potentially complete even before leaving the initializer:</p><pre>Future&lt;Int&gt; { c in c(.success(1)) }.onResult { result in<br>  // Will never be called as `c` was called before `onResult()` was called. <br>}</pre><p>The solution is to keep the result around in the case someone calls onResult() after the future has completed. And once we have a result we do not need to keep the completions around any longer. So the state of a future is now either pending with an array of completions or completed with a result:</p><pre>final class Future&lt;Value&gt; {<br>  enum State {<br>    case completed(Result&lt;Value&gt;)<br>    case pending([(Result&lt;Value&gt;) -&gt; Void])<br>  }<br><br>  var state: State<br>}</pre><p>The initializer now becomes:</p><pre>init(onResult: @escaping (@escaping (Result&lt;Value&gt;) -&gt; Void) -&gt; Void) {<br>  state = .pending([])<br>  onResult { result in<br>    guard case .pending(let completions) = self.state else { return }<br>    completions.forEach { $0(result) }<br>    self.state = .completed(result)<br>  }<br>}</pre><p>And onResult() is updated to immediately call the completion back if the future has already been completed:</p><pre>func onResult(completion: @escaping (Result&lt;Value&gt;) -&gt; Void) {<br>  switch state {<br>  case .completed(let result):<br>    completion(result)<br>  case .pending(var completions):<br>    completions.append(completion)<br>    state = .pending(completions)<br>  }<br>}</pre><h4>Chaining futures</h4><p>Adding map() to Future&lt;T&gt; demonstrated how we can construct a new future from a previous one, in this case by transforming the internal value. A perhaps even more powerful transform is to be able to chain two asynchronous operations. In this case, we want to construct a new future representing one operation performed after another one, where the second operation has access to the result from the first. So we would like a version of map() where the value is not just transformed into a new one using the (A) -&gt; B transform. Instead, we would like to transform the value into the second operation using a (A) -&gt; Future&lt;B&gt; transform. This is called a flatMap(), and similar to map(), can be found on Swift optional and containers as well. It would also make sense to add flatMap() to our Result&lt;T&gt; type.</p><p>To better see how map() and flatMap() are basically the same for Optional, Array, Result and Future, we could look at the signatures of their transformation functions:</p><pre>| type      | map()    | flatMap()        |<br>|-----------|----------|------------------|<br>| A?        | (A) -&gt; B | (A) -&gt; B?        |<br>| [A]       | (A) -&gt; B | (A) -&gt; [B]       |<br>| Result&lt;A&gt; | (A) -&gt; B | (A) -&gt; Result&lt;B&gt; |<br>| Future&lt;A&gt; | (A) -&gt; B | (A) -&gt; Future&lt;B&gt; |</pre><p>Given the function signature of flatMap(), even with the addition of letting the transform to throw errors, the implementation for Future&lt;T&gt; is still quite straight-forward:</p><pre>func flatMap&lt;O&gt;(_ transform: @escaping (Value) throws -&gt; Future&lt;O&gt;) -&gt; Future&lt;O&gt; {<br>  return Future&lt;O&gt; { completion in<br>    self.onResult { result in<br>      do {<br>        try transform(result.getValue()).onResult(completion)<br>      } catch {<br>        completion(.failure(error))<br>      }<br>    }<br>  }<br>}</pre><h4>Focus on the “happy flow”</h4><p>As the transformations passed to both map() and flatMap() are called with a success value, we can conclude they will only be called if such a value is available. This normally means that all operations preceding them were successful as well. It is quite typical when working with futures that you focus on this &quot;happy flow&quot;. Failures are typically just implicitly forwarded and are explicitly handled only where required, and then normally at the end of a sequence of operations.</p><p>Where onResult() requires us to handle both failures and successes, it is often more convenient to focus on one or the other. This can easily be improved by adding an onValue() helper:</p><pre>func onValue(_ callback: @escaping (Value) throws -&gt; Void) -&gt; Future {<br>  return map { value in<br>    try callback(value)<br>    return value<br>  }<br>}</pre><p>Similarly, we can add an onError() helper.</p><p>Bringing it all together we can now build quite complex compositions, such as fetching a user’s friends:</p><pre>json(at: userURL).flatMap { jar in<br>  let user: User = try jar^<br>  return json(at: user.friendsURL)<br>}.map { jar in<br>  let friends: [Friend] = try jar^<br>  return friends<br>}.onValue { friends in<br>  // Everything was successful<br>}.onError { error in<br>  // Something failed<br>}</pre><p>If you wonder what the try jar^ is all about, it is just how <a href="https://github.com/izettle/Lift">Lift</a> converts the JSON contained inside a Jar into model values.</p><p>In this example, you can see how futures makes it easy to chain several transformations after each other. If you would try to do this with the original APIs, using completion callbacks and without Result&lt;T&gt;, the code would soon be really messy and hard to read and maintain.</p><p>In the above example, it might not be obvious at first how much could fail. Both requests could fail, transforming data to JSON could fail, and constructing our model values could fail as well. If all goes well, we end up in onValue()&#39;s callback. If something fails, we will end up in onError()&#39;s callback.</p><h4>Summary</h4><p>We started out discussing what asynchronous operations are, why they are useful in UI application, and how they typically are modeled with completion callbacks. We then introduced the Result&lt;T&gt; type to better model asynchronous results. After updating our APIs to use Result&lt;T&gt;, we recognized that most completion handlers look the same but for the type T returned, hence we defined the Future&lt;T&gt; type to encapsulate asynchronous operations.</p><p>We discovered that futures carry a state of being completed or not. This state resulted in the implementation being a bit more tricky then perhaps first anticipated. Finally, we introduced the map() and flatMap() transforms and showed how we could chain futures together and mainly focus on the &quot;happy flow&quot;.</p><p>If you want to learn more about futures and try them out yourself, download the open sourced framework <a href="https://github.com/iZettle/Flow">Flow</a>. Here, you can also see how a production implementation might look like. There is also a <a href="https://gist.github.com/mansbernhardt/a410b3de02e618cb5c6a76cbb069be56">playground</a> available, where you can see the code introduced in this article all come together.</p><p>In an upcoming article, we will see how we can make futures even more powerful and convenient to work with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=607aea9abdee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Design — Expanding on Signals]]></title>
            <link>https://medium.com/@mans.bernhardt/expanding-on-signals-ad25daee4d64?source=rss-19780e21de4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad25daee4d64</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Måns Bernhardt]]></dc:creator>
            <pubDate>Fri, 27 Apr 2018 11:33:42 GMT</pubDate>
            <atom:updated>2018-05-07T19:21:47.651Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with UI frameworks, it is very common with APIs that want to notify the user of changes of different kinds. In Apple frameworks, these are typically expressed through the use of notifications, target/action, delegates or registration of callback closures.</p><p>In the article <a href="https://medium.com/izettle-engineering/deriving-signal-2adb8687e9bf">“Deriving Signals”</a> those different APIs were unified by the introduction of the Signal type. This article will further explore the utility of signals and how they can become even more convenient to work with.</p><p>We start off by extending Signal with more useful transforms. Then UIControl is extended to signal UI events such as text field changes. We conclude by exploring how to combine signals and handle the notion of a current state.</p><h4>Signal</h4><p>In the previous <a href="https://medium.com/izettle-engineering/deriving-signal-2adb8687e9bf">article</a> Signal was introduced as:</p><pre>final class Signal&lt;Value&gt; {<br>  let onValue: (_ callback: @escaping (Value) -&gt; Void) -&gt; Disposable<br>}</pre><p>Signal abstracts the API for observing changes over time. To listen to these changes, a callback is passed to onValue. This callback will then be called for each change. When you are no longer interested in observing those changes, dispose() is called on the returned Disposable:</p><pre>// Start observe<br>let disposable = signal.onValue { value in ... }<br>...<br>// Stop observe<br>disposable.dispose()</pre><p>Perhaps, more importantly, is that a Signal hides the details on how and from where events are generated. Signals can also be passed around and be shared among several users, and by applying transforms, they can be modified into new signals. The article <a href="https://medium.com/izettle-engineering/deriving-signal-2adb8687e9bf">&quot;Deriving Signals&quot;</a> concluded by introducing the map() transform:</p><pre>let email: Signal&lt;String&gt;<br>let shouldEnableButton = email.map { $0.isValidEmail }</pre><h4>More transforms</h4><p>Similar to map we can add more transforms such as filter:</p><pre>extension Signal {<br>  func filter(_ predicate: @escaping (Value) -&gt; Bool) -&gt; Signal&lt;Value&gt; {<br>    return Signal { callback in<br>      self.onValue { value in<br>        guard predicate(value) else { return }<br>        callback(value)<br>      }<br>    }<br>  }<br>}</pre><p>Another useful transformation distinct() will filter out repeated values. If a new value is equal to the preceding value it will not be forwarded:</p><pre>extension Signal where Value: Equatable {<br>  func distinct() -&gt; Signal&lt;Value&gt; {<br>    return Signal { callback in<br>      var prev: Value? = nil<br>      return self.onValue { value in<br>        if prev.map { $0 != value } ?? true {<br>          callback(value)<br>        }<br>        prev = val<br>      }<br>    }<br>  }<br>}</pre><p>There are many more useful transformations such as debounce(), throttle() and latestTwo(). See <a href="https://github.com/iZettle/Flow">Flow</a> for more examples.</p><h4>UI events</h4><p>When working with UI, probably the most common usage of event handling is when working with UI controls such as UIKit’s UIButton and UITextField. The API for working with UIControl events is by setting up targets and actions. A problem with using target/action<a href="#fn1-3251">1</a> is that the declaration of the action is separated from the code where it is set up. This becomes even more problematic if the action needs access to some additional context data. This data needs to be stored in the target for the action to be able to access it:</p><pre>class LoginController: UIViewController {<br>  let button: UIButton // Need access to the button in `emailChanged`<br><br>  init() {<br>    button = UIButton(...)<br>    let emailField = UITextField(...)<br>    // Add to view hierarchy<br>    <br>    button.addTarget(self, action: #selector(login), for: .touchUpInside)<br>    emailField.addTarget(self, action: #selector(emailChanged), for: .editingChanged)<br>  }<br>  <br>  func emailChanged() {<br>    button.isEnabled = emailField.text?.isValidEmail ?? false<br>  }<br>}</pre><p>When using signals we can instead capture this context data in the callback closure itself. This brings related code together and avoids potentially stale or out of sync context data.</p><p>Let us extend UIControl to provide a signal for control events:</p><pre>extension UIControl {<br>  func signal(for controlEvents: UIControlEvents) -&gt; Signal&lt;()&gt; { ... }<br>}</pre><p>Our view controller can now instead be written as:</p><pre>class LoginController: UIViewController {<br>  init() {<br>    let button = UIButton(...)<br>    let emailField = UITextField(...)<br>    // Add to view hierarchy<br>    <br>    bag += emailField.signal(for: .editingChanged).onValue {<br>      button.isEnabled = emailField.text?.isValidEmail ?? false<br>    }<br><br>    bag += button.signal(for: .touchUpInside).onValue(login)<br>  }<br>}</pre><h4>SignalProvider</h4><p>For most UIControls there is a signal that makes more sense than others. For UIButton it is signaling button presses, and for UITextField it is signaling changes to its text. It would be useful to express that certain types provide a default signal. Let us introduce a protocol for that:</p><pre>protocol SignalProvider {<br>  associatedtype Value<br>  var providedSignal: Signal&lt;Value&gt; { get }<br>}</pre><p>We can now retroactively extend UIButton:</p><pre>extension UIButton: SignalProvider {<br>  var providedSignal: Signal&lt;()&gt; {<br>    return signal(for: .touchUpInside)<br>  }<br>}</pre><p>And for UITextField we will provide the current value of its text:</p><pre>extension UITextField: SignalProvider {<br>  var providedSignal: Signal&lt;String&gt; {<br>    return signal(for: .editingChanged).map { self.text ?? &quot;&quot; }<br>  }<br>}</pre><p>It would be convenient if we did not have to explicitly call providedSignal on our conforming types. However, we do not want to implement all our transformations twice, once for Signal and once for SignalProvider. Fortunately, it is easy to conform Signal to SignalProvider by just returning itself:</p><pre>extension Signal: SignalProvider {<br>  var providedSignal: Signal&lt;Value&gt; {<br>    return self<br>  }<br>}</pre><p>We can now move onValue() and our other transformations to work on SignalProvider instead. Our example will now read more succinctly:</p><pre>bag += emailField.onValue { value in<br>  button.isEnabled = value.isValidEmail<br>}<br><br>bag += button.onValue(login)</pre><h4>Working with multiple signals</h4><p>Once you start using signals in many places you soon see a need to combine several signals into one. For example, if we have both an email and a password field and want to enable the button if both of them are valid we currently have to write:</p><pre>bag += emailField.onValue { value in<br>  button.isEnabled = value.isValidEmail &amp;&amp; passwordField.text?.isValidPassword<br>}<br><br>bag += passwordField.onValue { value in<br>  button.isEnabled = value.isValidPassword &amp;&amp; emailField.text?.isValidEmail<br>}</pre><p>This will be hard to maintain and will not scale if we get even more signals participating in the validation. What we would like is to combine these two signals into one signal that updates if any of the two signals are updated:</p><pre>bag += combineLatest(emailField, passwordField).onValue { email, password in<br>  button.isEnabled = email.isValidEmail &amp;&amp; password.isValidPassword<br>}</pre><p>An implementation of combineLatest might look like:</p><pre>func combineLatest&lt;A, B&gt;(_ signalA: A, _ signalB: B) -&gt; Signal&lt;(A.Value, B.Value)&gt;<br>  where A: SignalProvider, B: SignalProvider {<br>  return Signal { callback in<br>    var a: A.Value?<br>    var b: B.Value?<br>    <br>    let bag = DisposeBag()<br>    <br>    bag += signalA.onValue { value in<br>      a = value<br>      if let b = b {<br>        callback((value, b))<br>      }<br>    }<br><br>    bag += signalB.onEventType { value in<br>      b = value<br>      if let a = a {<br>        callback((a, value))<br>      }<br>    }<br><br>    return bag<br>  }<br>}</pre><p>Some other useful signal combiners are merge() and flatMapLatest(). See <a href="https://github.com/iZettle/Flow">Flow</a> for more information.</p><h4>Accessing initial state</h4><p>By adding combineLatest we got rid of the duplicated enable button logic. However, we also need to set up the initial state of isEnabled. In the current example, we could of course just set the button to disabled at creation. But what if the text fields would sometimes be pre-filled. Then disabled is not necessarily the preferred initial state. Yet again, this leads to code repetition:</p><pre>button.isEnabled = emailField.text?.isValidEmail &amp;&amp; passwordField.text?.isValidPassword<br><br>bag += combineLatest(emailField, passwordField).onValue { email, password in<br>  button.isEnabled = email.isValidEmail &amp;&amp; password.isValidPassword<br>}</pre><p>It would be convenient if a text field would signal its current value at once when setting up a callback. Then the initial state could be set inside onValue() instead. But not all signals have a notion of a current value such as UIButton or notifications. How would we know which signals will signal an initial value and which will not? We could, of course, document this at the declaration site. But it would be better if the type itself could express this.</p><p>Let us introduce a new type called ReadSignal that extends Signal with a read-only value property returning its current value. We also add the transform atOnce() that will signal this value as soon as someone starts listening:</p><pre>extension ReadSignal {<br>  func atOnce() -&gt; Signal&lt;Value&gt; {<br>    return Signal { callback in<br>      callback(self.value)<br>      return self.onValue(callback)<br>    }<br>  }<br>}</pre><p>We update UITextField to instead return a ReadSignal&lt;String&gt; and add atOnce() to our example:</p><pre>bag += combineLatest(emailField, passwordField).atOnce().onValue {<br>  button.isEnabled = $0.isValidEmail &amp;&amp; $1.isValidPassword<br>}</pre><p>Now the logic for enabling the button is in only one place inside onValue().</p><p>After adding ReadSignal, it also makes sense to add ReadWriteSignal where value is mutable and where updating the value will be signaled to listeners.</p><h4>Moving between signal types</h4><p>The introduction of different kinds of signals asks for ways to convert between them. For example, we might use a ReadWriteSignal internally to be able to work with its mutable value. But externally we only want to expose a non-mutable signal:</p><pre>let internalState = ReadWriteSignal(false)<br>var state: ReadSignal&lt;Bool&gt; {<br>  return internalState.readOnly()<br>}</pre><p>Similarly, we would like to be able to upgrade a plain Signal to a ReadSignal or ReadWriteSignal. UITextField&#39;s signal could then be implemented as:</p><pre>extension UITextField: SignalProvider {<br>  var providedSignal: ReadSignal&lt;String&gt; {<br>    return signal(for: .editingChanged)<br>      .map { self.text ?? &quot;&quot; }<br>      .readable(capturing: self.text ?? &quot;&quot;)<br>  }<br>}</pre><h4>Summary</h4><p>In this article, we explored how the basic Signal type can be extended in different dimensions to make it even more convenient to work with. Firstly, we added more transforms such as filter() and distinct(). After that, we built a simple login view and investigated how to work with UIControl events. Lastly, we saw that, by combining signals and asking for initial values, we could more easily express our intention and avoid code repetition.</p><p>In an upcoming article, we will explore how we could implement parts of what was being discussed in this article, such as ReadSignal.</p><p>To learn more about what was covered in this article, you can download our open sourced framework <a href="https://github.com/iZettle/Flow">Flow</a>.</p><ol><li>This is true with many of Apple’s other observation APIs as well <a href="#fnr1-3251">↩︎</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad25daee4d64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Design — Deriving Signal]]></title>
            <link>https://medium.com/@mans.bernhardt/deriving-signal-2adb8687e9bf?source=rss-19780e21de4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2adb8687e9bf</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[functional]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[reactive]]></category>
            <dc:creator><![CDATA[Måns Bernhardt]]></dc:creator>
            <pubDate>Fri, 20 Apr 2018 07:31:38 GMT</pubDate>
            <atom:updated>2018-05-03T06:25:15.405Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore three abstractions that are useful building blocks in asynchronous event handling. As a use case, we will build an API for registering callbacks to get notified of events. Working with callbacks might sound trivial at first. After all, it is just the passing of a closure to be called back on event updates. But as it turns out, we will run into several challenges to come up with an API design that is both robust and flexible.</p><p>It all starts out with trying to find a solution how to deregister our callbacks, a lifetime management problem which leads us to the Disposable protocol. After that, we address the repetitive work of callbacks book-keeping, leading us to the reusable Callbacker type. Finally, we investigate how to make our callbacks even more composable and stand-alone by bringing it all together into a basic implementation of a Signal type. This Signal type is a core concept found in many reactive frameworks, such as <a href="https://github.com/iZettle/Flow">Flow</a></p><h4>Callback registration</h4><p>A recurring problem in API design is to be able to notify clients of events. If the language supports closures, a natural design is to let the client register a callback that will be called when something happens. It typically starts out like:</p><pre>func addObserver(onEvent: @escaping (Event) -&gt; Void)</pre><p>And at the call-site we will have:</p><pre>addObserver(onEvent: { event in<br>   ...<br>})</pre><p>One major omission in this API is that there is no way to deregister your interest in event callbacks. It is unlikely you would always want to receive events for the lifetime of the application. Removing an observer would also free up the resources captured by the callback closure. A first attempt to add support might look like:</p><pre>func removeObserver()</pre><p>It should be obvious that this design will not scale beyond one observer. What should removeObserver do if we have registered more than one callback? What we need is a way to identify one callback from another. One approach would be to add some kind of key:</p><pre>func addObserver(forKey: String, onEvent: @escaping (Event) -&gt; Void)<br>func removeObserver(forKey: String)</pre><p>This is better. But to make the user of the API responsible for creating the keys opens up for several problems. As the keys have to be unique and we might use the API from different places, we have opened up for involuntarily reusing of the same key for different callbacks. This could result in callbacks being replaced by new registrations or existing callbacks being removed when deregistering others. So it is better to move the complexity of key generation to the API:</p><pre>func addObserver(onEvent: @escaping (Event) -&gt; Void) -&gt; String<br>func removeObserver(forKey: String)</pre><p>Using String as our key type comes with one disadvantage though. New strings can be constructed freely. This allows removeObserver to be accidentally called with an arbitrarily key. An improvement would be to add a custom key type with a private initializer. This would restrict the creation of keys to the implementation of the API:</p><pre>struct ObserverKey { private init() { ... } }<br>func addObserver(onEvent: @escaping (Event) -&gt; Void) -&gt; ObserverKey<br>func removeObserver(forKey: ObserverKey)</pre><p>We could still call removeObserver more than once for the same key, but that could potentially be preconditioned to cause a trap (at least in debug builds). This API design is very similar to what Foundation is using for notifications:</p><pre>func addObserver(forName: /*...*/, using block: @escaping (Notification) -&gt; Void) -&gt; NSObjectProtocol<br>func removeObserver(_ observer: Any)</pre><p>As can be seen, this API has a similar problem with its keys as some of our earlier attempts. It is even worse, as the user could pass a key of any value and type to removeObserver. This is a problem we nicely avoided when introducing our custom key type.</p><p>Another advantage of introducing custom key types is that we could have different types of keys for different but similar APIs. This would stop us from accidentally mixing up keys from different APIs. A disadvantage is that it requires us to define a new custom key type every time we add a similar API. It could also be an administrative burden for the consumer of these APIs to have to keep track of the different kind of keys.</p><p>It would be great if the API could abstract away what underlying key is being used and help us calling removeObserver correctly. One, at first perhaps not obvious way to solve this, is to let addObserver return something that can be called when we want to deregister. The most straightforward would be to return a function:</p><pre>func onEvent(callback: @escaping (Event) -&gt; Void) -&gt; () -&gt; Void</pre><p>That can be implemented using our existing observer APIs as:</p><pre>func onEvent(callback: @escaping (Event) -&gt; Void) -&gt; () -&gt; Void {<br>  let key = addObserver(onEvent: callback)<br>  return { removeObserver(forKey: key) }<br>}</pre><p>And voilà, in one sweep we got rid of the key and the removeObserver function all at once. Another great benefit of this change is that all deregister functions are now of the same type and we do not necessarily have to keep track of separate lists for different observer APIs. The method name can be simplified to onEvent, and by introducing a type alias, intention and readability can be further improved:</p><pre>typealias Disposable = () -&gt; Void<br>func onEvent(callback: @escaping (Event) -&gt; Void) -&gt; Disposable</pre><p>Applying this to Foundation’s notification would look something like:</p><pre>extension NotificationCenter {<br>  func onNotifications(named: /* ... */, callback: @escaping (Notification) -&gt; Void) -&gt; Disposable {<br>    let observer = addObserver(forName: /* ... */, using: callback)<br>    return { self.removeObserver(observer) }<br>  }<br>}</pre><h4>Disposable</h4><p>Even though Disposable describes everything we need, there are some limits of using functions directly such as they cannot be extended. Hence it makes a lot of sense to replace our function type alias with a protocol:</p><pre>protocol Disposable {<br>  func dispose()<br>}</pre><p>And the most basic implementation of Disposable would be the Disposer type:</p><pre>final class Disposer: Disposable {<br>  private var disposer: (() -&gt; Void)?<br><br>  init(_ disposer: @escaping () -&gt; Void) {<br>    self.disposer = disposer<br>  }<br><br>  func dispose() {<br>    disposer?()<br>    disposer = nil // Stop from being called more than once<br>  }<br><br>  deinit { dispose() }<br>}</pre><p>And now when all our different registration APIs are all returning the same Disposable type, we can add a convenience type for collecting them:</p><pre>final class DisposeBag: Disposable {<br>  fileprivate var disposables: [Disposable] = []<br><br>  func dispose() {<br>    disposables.forEach { $0.dispose() }<br>    disposables = []<br>  }<br><br>  deinit { dispose() }<br>}</pre><p>And by adding an operation +=:</p><pre>func +=(bag: DisposeBag, disposable: Disposable) {<br>  bag.disposables.append(disposable)<br>}</pre><p>We can now collect disposables and return a bag as another Disposable:</p><pre>func setupObservers() -&gt; Disposable {<br>  let bag = DisposeBag()<br>  bag += onSomething { .. }<br>  bag += onSomethingElse { .. }<br>  return bag<br>}</pre><h4>Implementing callbacks</h4><p>The introduction of Disposable made our API more robust. But how would an implementation of the observe method look like, supporting multiple listeners? Looking at e.g. NotificationManager, one could imagine that they internally would use a dictionary of some sort to keep track of the callbacks. If we apply this to our example, we would get something like:</p><pre>private typealias Key = ...<br>private var callbacks: [Key: (Event) -&gt; Void] = [:]<br>private func generateKey() -&gt; Key { ... }<br><br>func onEvent(callback: @escaping (Event) -&gt; Void) -&gt; Disposable {<br>  let key = generateKey()<br>  callbacks[key] = callback<br>  return Disposer {<br>    callbacks[key] = nil<br>  }<br>}<br><br>private func notify(event: Event) {<br>  callbacks.forEach { $1(event) }<br>}</pre><p>At a closer look, not much of this code seems unique for this specific API. If we have to repeat this code for several observer APIs we risk introducing subtle differences and bugs. This is especially true if taking thread safety and efficient key generation into consideration. It makes sense to introduce a Callbacker helper:</p><pre>final class Callbacker&lt;Value&gt; {<br>  private var callbacks: [Key : (Value) -&gt; Void] = [:]<br><br>  func addCallback(_ callback: @escaping (Value) -&gt; Void) -&gt; Disposable {<br>    let key = generateKey()<br>    callbacks[key] = callback<br>    return Disposer {<br>      self.callbacks[key] = nil<br>    }<br>  }<br><br>  public func callAll(with value: Value) {<br>    callbacks.forEach { $1(value) }<br>  }<br>}</pre><p>Using Callbacker would reduce our onEvent implementation to:</p><pre>private let callbacker = Callbacker&lt;Event&gt;()<br><br>func onEvent(callback: @escaping (Event) -&gt; Void) -&gt; Disposable {<br>  return callbacker.addCallback(callback)<br>}<br><br>private func notify(event: Event) {<br>  callbacker.callAll(with: event)<br>}</pre><p>Even though the onEvent API and its implementation have improved a lot from what we started out with, there are still problems with it. For one, it is hard to pass the onEvent functionality around. It is likely onEvent would be a member of some type and perhaps we could pass an instance of that type around instead. But that would introduce unnecessary dependencies on this type. It would be great if the code that is interested in observing changes does not need to have knowledge about who provides the API and how it is implemented.</p><p>One attempt to improve this would be to pass around functions:</p><pre>typealias Signal&lt;T&gt; = (_ callback: @escaping (T) -&gt; Void) -&gt; Disposable<br><br>let onEvent: Signal&lt;Event&gt; = { callback in<br>  return callbacker.addCallback(callback)<br>}<br><br>bag += onEvent { event in ... }</pre><p>But perhaps the consumer does not even need to know about the details of the original event but rather a transformation of it. This could be a boolean value expressing the enabled state of a button, or a string value to be displayed in a label. To allow this we need to add wrappers such as:</p><pre>let shouldEnableButton: Signal&lt;Bool&gt; = { callback in<br>  onEvent { event in<br>    callback(event.shouldEnableButton)<br>  }<br>}</pre><p>As those transforms might become common, we could improve this further by adding a map function:</p><pre>func map&lt;T, O&gt;(_ observer: Signal&lt;T&gt;, transform: @escaping (T) -&gt; O) -&gt; Signal&lt;O&gt; {<br>  return { callback in<br>    observer { value in<br>      callback(transform(value))<br>    }<br>  }<br>}</pre><p>The shouldEnableButton can now be rewritten to:</p><pre>let shouldEnableButton = map(onEvent) { $0.shouldEnableButton }</pre><p>But using free functions such as map gives us flashbacks to days before Swift 2 and protocol extensions. The more Swifty way to express this would be:</p><pre>let shouldEnableButton = onEvent.map { $0.shouldEnableButton }</pre><p>Yet again we have run into the limit of working directly with functions or type aliases of thereof. The solution for Disposable was to move the function into a type or protocol. We will do the same here by replacing the Signal&lt;T&gt; type alias with a Signal&lt;T&gt; type holding the closure in an onValue property:</p><pre>final class Signal&lt;Value&gt; {<br>  let onValue: (_ callback: @escaping (Value) -&gt; Void) -&gt; Disposable<br>}</pre><p>Now we can pass the onEvent function around as a Signal instead:</p><pre>let event: Signal&lt;Event&gt; = Signal { callback in<br>  return callbacker.addCallback(callback)<br>}</pre><p>And as event is no longer a function we now call it indirectly via Signal&#39;s onValue:</p><pre>bag += event.onValue { event in<br>  ...<br>}</pre><p>We can now move the map function to an extension of Signal:</p><pre>extension Signal {<br>  func map&lt;T&gt;(transform: @escaping (Value) -&gt; T) -&gt; Signal&lt;T&gt; {<br>    return Signal&lt;T&gt; { callback in<br>      self.onValue { event in<br>        callback(transform(event))<br>      }<br>    }<br>  }<br>}</pre><p>And hence our shouldEnableButton can now be written in our preferred way:</p><pre>let shouldEnableButton = event.map { $0.shouldEnableButton }</pre><p>Of course, map is just one of many transformations you could use on signals, but that is for another article to talk about. Until then you could always have a sneak peek at our open source framework <a href="https://github.com/iZettle/Flow">Flow</a>.</p><h4>Summary</h4><p>We started out trying to design an API to register callbacks to receive event updates. By identifying different issues with our different API attempts, we discovered several powerful abstractions. The last of those, Signal, is the basis of many popular reactive frameworks.</p><p>To see how the concepts introduced in this article all come together, there is a <a href="https://gist.github.com/mansbernhardt/724e9a11e6f58a0ff1f279b0afb62d95">playground</a> for you to play with. You can also learn more about Disposable, Callbacker and Signal by downloading our open sourced framework <a href="https://github.com/iZettle/Flow">Flow</a>.</p><p>In the follow-up article <a href="https://medium.com/izettle-engineering/expanding-on-signals-ad25daee4d64">Expanding on Signals</a> we will further explore the utility of signals and how we can make them even more convenient to work with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2adb8687e9bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Flow — Asynchronous programming made easy]]></title>
            <link>https://medium.com/@mans.bernhardt/introducing-flow-42de51988aea?source=rss-19780e21de4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/42de51988aea</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[functional]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[reactive]]></category>
            <dc:creator><![CDATA[Måns Bernhardt]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 13:54:50 GMT</pubDate>
            <atom:updated>2018-05-07T19:22:50.110Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we are proud to announce the open sourcing of <a href="https://github.com/izettle/Flow">Flow</a>, a Swift framework for building and maintaining complex asynchronous flows. Flow is modern, lightweight and composable, allowing you to write code that is more robust and easier to reason about. It has been field-tested and has matured over the course of many years while being extensively used in iZettle’s point of sale app to solve real problems.</p><p>If you ever wondered what this thing about reactive programming is, now is the time to give it a try. We hope that it will give you the boost in productivity and joy of developing software that it did for us.</p><h4>So what is Flow about?</h4><p>Modern applications often contain complex asynchronous flows and life cycles. Flow aims to simplify building these by solving three main problems:</p><h4>Lifetime management — Managing long-living resources</h4><p>In Flow, lifetime management refers to the handling of for how long a resource is kept alive. This becomes especially important when working with closures, as they, in turn, capture and keep resources alive. Instead of weakly capturing those resources, Flow advocates the use of explicit disposal of resources. At first, this might seem like adding a lot of extra work, but once you adopt it in your application, your code will be much easier to reason about.</p><p>In Flow, the Disposable protocol is the standard way of handling clean-up after something is done. The protocol only declares one method dispose() to be called to perform clean-up:</p><pre>protocol Disposable {<br>  func dispose()<br>}</pre><p>By returning a Disposable when starting long living processes, you have a standard way of handling clean-up:</p><pre>extension UIView {<br>  func showSpinnerOverlay() -&gt; Disposable { <br>    let spinner = ...<br>    addSubview(spinner)<br>    return Disposer {<br>      spinner.removeFromSuperview()<br>    }<br>  }<br>}<br><br>let disposable = view.showSpinnerOverlay()<br><br>disposable.dispose() // Hide spinner</pre><h4>Event handling — Observing events over time</h4><p>APIs that want to notify the user of changes are common. Apple provides several of those and they come in many forms, such as notifications, delegates, target/action and KVO. In Flow, event-based APIs are represented by signals. Since a signal hides the underlying logic and provides a uniform API, not only can you use them interchangeably, but you can also easily pass them around, combine them, and transform them into new ones.</p><p>By calling onValue() on a signal you will start listening on new changes until you dispose the returned disposable:</p><pre>let bag = DisposeBag() // Bag of disposables<br><br>// UIButton provides a Signal&lt;()&gt;<br>let loginButton = UIButton(...)<br><br>bag += loginButton.onValue { <br>  // Log in user if tapped<br>}<br><br>// UITextField provides a ReadSignal&lt;String&gt;<br>let emailField = UITextField(...)<br>let passwordField = UITextField(...)<br><br>// Combine and transform signals<br>let enableLogin = combineLatest(emailField, passwordField)<br>  .map { email, password in<br>    email.isValidEmail &amp;&amp; password.isValidPassword<br>  } // -&gt; ReadSignal&lt;Bool&gt;<br><br>// Use bindings and key-paths to update your UI on changes<br>bag += enableLogin.bindTo(loginButton, \.isEnabled)</pre><h4>Asynchronous operations — Handle results that might not yet be available</h4><p>When building applications interacting with a user, a goal is to keep the application responsive at all times. It is thus important to not perform long-running operations that will block the UI. This is one reason why many APIs used in UI intensive applications are asynchronous.</p><p>Working with asynchronous code can easily become messy as soon as you need to nest a few operations which depend on each other’s results. So similar to signals, Flow abstracts the idea of an asynchronous operation and encapsulates it into a Future&lt;T&gt; type representing a result that might not yet be available:</p><pre>extension URLSession {<br>  func data(for request: URLRequest) -&gt; Future&lt;Data&gt; {<br>    return Future { completion in<br>      let task = self.dataTask(with: request) { data, _, error in<br>        if let error = error { <br>          completion(.failure(error)) <br>        } else {<br>          completion(.success(data!))<br>        }<br>      }<br>      task.resume()<br>      return Disposer { task.cancel() }<br>    }<br>  }<br>}</pre><p>Futures are highly composable and comes with many useful transformations:</p><pre>func login(email: String, password: String) -&gt; Future&lt;User&gt; {<br>  let request = URLRequest(...)<br>  return URLSession.shared.data(for: request).map { data in<br>    User(data: data)<br>  }<br>}<br><br>login(...).onValue { user in<br>  // Handle successful login<br>}.onError { error in<br>  // Handle failed login<br>}</pre><h4>Bringing it all together</h4><p>By bringing these three concepts together we can build complex UI flows that are still easy to reason about:</p><pre>class LoginController: UIViewController {<br>  let emailField: UITextField<br>  let passwordField: UITextField<br>  let loginButton: UIButton <br>  let cancelButton: UIBarButtonItem <br>  <br>  var enableLogin: ReadSignal&lt;Bool&gt; { // Introduced above }<br>  func login() -&gt; Future&lt;User&gt; { // Introduced above }<br>  func showSpinnerOverlay() -&gt; Disposable { // Introduced above }<br>  <br>  // Returns future that completes with true if user chose to retry<br>  func showRetryAlert(for error: Error) -&gt; Future&lt;Bool&gt; { <br>    return Future { completion in<br>      let retry = UIAlertAction(title: &quot;Retry&quot;) { completion(.success(true)) }<br>      let cancel = UIAlertAction(title: &quot;Cancel&quot;) { completion(.failure(error)) }<br>      let alert = UIAlertController(...)<br>      // Present alert ...<br>      return Disposer { // Dismiss alert }<br>    }<br>  }<br>  <br>  // Will setup UI observers and return a future completing after a successful login <br>  func runLogin() -&gt; Future&lt;User&gt; {<br>    return Future { completion in // Completion to call with the result  <br>      let bag = DisposeBag() // Resources to keep alive while executing <br>         <br>      // Make sure to signal at once to set up initial enabled state<br>      bag += self.enableLogin.atOnce().bindTo(self.loginButton, \.isEnabled)  <br><br>      // If button is tapped, initiate potentially long running login request<br>      bag += self.loginButton.onValue {<br>        self.login()<br>          .performWhile { <br>            // Show spinner during login request<br>            self.showSpinnerOverlay() <br>          }.onErrorRepeat { error in<br>              // If login fails with an error show an alert...<br>              // ...and retry the login request if the user chose to<br>            self.showRetryAlert(for: error)<br>          }.onValue { user in<br>            // If login is successful, complete runLogin() with the user<br>            completion(.success(user))<br>          }<br>      }<br>      <br>      // If cancel is tapped, complete runLogin() with an error<br>      bag += self.cancelButton.onValue { <br>        completion(.failure(LoginError.dismissed))<br>      }<br>      <br>      return bag // Return a disposable to dispose once the future completes<br>    }<br>  }<br>}</pre><h4>Looking back — on being pragmatic</h4><p>Flow has a very pragmatic design philosophy. It has been evolved over the years to solve the problems we have encountered while growing the iZettle app. It started many years ago, way before Swift, where we tried to make the complexity of our card payment flow easier to maintain and understand. Performing a card payment is a complex coordination of different asynchronous and concurrent operations. It involves hardware of different kinds, networking, timeouts, and user interaction. There are many things that can go wrong and we need to be able to gently tear down any ongoing processes while also propagating errors correctly. This resulted in the design of the Future type that later was modernized and brought over to Swift and Flow.</p><h4>Power of abstractions</h4><p>Once you have the right abstraction and an ergonomic API for working with asynchronous operations, you start to find uses for it everywhere. One great example is the presentation of view controllers. But perhaps more common when working with UI is to observe events over time. Events manifest in many different forms, such as button presses, notifications, and KVO updates. Here again, we used our experience from our Objective-C, block-based APIs, to develop a more general Swift solution using the Signal type.</p><p>When working with UI there is also a need to clean things up after e.g. a presentation. This is especially true when working with a lot of closure based APIs. Where previously we were trying to solve this by using weak references, this was a never-ending chase of fixing memory leaks. The solution turned out to be a very simple idea, but yet so powerful, solved by introducing the Disposable protocol.</p><h4>Increased productivity</h4><p>From introducing better support for lifetime management, signals and futures, our code base got a renaissance. An explosion of new possibilities and ideas grew out of these basic concepts, resulting in many powerful frameworks that have drastically changed how we build software at iZettle. Today we feel much more confident in our code, as it is easier to read, understand and reason about. It is easier than ever to decompose hard problems into smaller and more reusable components. Overall the joy of writing code and the safety of trusting your frameworks has been a huge boost in productivity.</p><h4>Learn more</h4><p>Flow can be found at <a href="https://github.com/izettle/Flow">GitHub</a> where you can try it out yourself and learn more about how to use it. We will also post a series of articles focusing on API design, where we will, step by step, derive the core types of Flow.</p><p>Our hope is that this article has inspired you to think about asynchronous programming in new ways. If you liked what you have seen so far, we encourage you to explore Flow further. If you find it useful, we welcome feedback and why not suggest or even contribute with your own improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42de51988aea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Design — Deriving Lift]]></title>
            <link>https://medium.com/@mans.bernhardt/deriving-lift-d83f8b6d0b38?source=rss-19780e21de4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d83f8b6d0b38</guid>
            <category><![CDATA[functional]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[library-design]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Måns Bernhardt]]></dc:creator>
            <pubDate>Fri, 08 Dec 2017 13:52:07 GMT</pubDate>
            <atom:updated>2018-04-20T08:10:25.347Z</atom:updated>
            <content:encoded><![CDATA[<p>There have been many attempts to build Swift libraries for both parsing and generating JSON. The reason is probably that there is no obvious Swift solution and JSON parsing is something most developers have to frequently confront. Swift 4 introduced Codable with the promise to solve this once and for all, and for many scenarios, it is just magic. But as soon as your models start to diverge from the simple one-to-one mapping between model and JSON, you have to implement everything yourself using a quite verbose API. Swift also currently lacks APIs for building and parsing JSON on the fly, not going through model objects, which is common when building and parsing network requests. So it seems there is still a need for third-party JSON libraries, explaining why many developers search GitHub or the web for better solutions to the problem.</p><p>But a few of us also takes on the challenge to create our own library. As you probably have guessed by now, that is exactly what we did. Soon after the introduction of Swift, we started to build our own version of a Swift JSON library at iZettle. Over the years it has matured significantly to support the different models and micro-services used by our iZettle app. With the recent open-sourcing of <a href="http://github.com/izettle/lift">Lift</a>, we thought it would be interesting to see how Lift became what it is today.</p><p>It is often useful to sketch out new APIs in a playground. Though great for initial prototyping, it is usually not until you apply your ideas and implementation to real production code that you will find many of the problems that have to be addressed. Of course, everyone’s needs are different, and in-house solutions tend to favor your specific challenges. But it is a good idea to plan for an eventual open-sourcing of your library from the get-go as it forces you to think in more general terms. But of course, you will never know for sure if your assumptions were right until you release your library into the wild.</p><h4>So what makes a good JSON library?</h4><p>To help out with the design work, we first tried to identify a list of requirements of what makes a good JSON library. Primarily we looked at our internal requirements, but we also looked at some of the existing JSON libraries to see how they approached the problem. In this blog we will, step by step, go through how we came up with the current design of the Lift library.</p><h4>Intuitive and lightweight syntax</h4><p>Ideally we would like to generate and parse JSON with a syntax like this:</p><pre>var json = [&quot;number&quot;: 5]<br>json[&quot;number&quot;] = 4711<br>let val = json[&quot;number&quot;] // val is inferred to &#39;Int?&#39;</pre><p>This is valid Swift code, but as JSON can hold a mix of heterogenous types such as arrays, dictionaries, numbers and strings, we run into problems when we start to mix types:</p><pre>var json: [String: Any] = [&quot;number&quot;: 5, &quot;string&quot;: &quot;hello&quot;]<br>json[&quot;string&quot;] = &quot;hello world&quot;<br>let val = json[&quot;string&quot;] // val is inferred to &#39;Any?&#39;</pre><h4>Static typing</h4><p>Being used to Swift’s strong typing, working with the Any type is just not good enough as this forces us to use casting to get back to our wanted types:</p><pre>let val = json[&quot;string&quot;] as? String // val is inferred to &#39;String?&#39;</pre><p>But often the compiler already knows what type to use. This is typically the case when deserializing into model types:</p><pre>struct Person { <br>  var name: String?<br>  var age: Int?<br>    <br>  init(json: [String: Any]) {<br>    name = json[&quot;name&quot;] as? String<br>    age = json[&quot;age&quot;] as? Int<br>  }<br>}</pre><p>Here we can see that we have to repeat the types String? and Int?</p><p>To solve this, the first revision of our JSON library, wrapped the JSON dictionary in a struct and added subscripts overloads for different types:</p><pre>struct Jar {<br>  var dict: [String: Any]<br>    <br>  subscript(key: String) -&gt; String? { <br>    return dict[key].flatMap { $0 as? String }<br>  }<br>    <br>  subscript(key: String) -&gt; Int? { <br>    return dict[key].flatMap { $0 as? Int }<br>  }<br>}</pre><p>The type signature of the different subscripts differs only on the return type. In comparison to many other languages, Swift allows overloading of methods not only based on their arguments but also their return types. This together with Swift’s powerful type inference, the compiler will now pick the correct subscript version based on the receiving type. This removes the need to repeat the type information through casting:</p><pre>init(jar: Jar) {<br>  name = jar[&quot;name&quot;]<br>  age = jar[&quot;age&quot;]<br>}</pre><p>Now we are back to the ideal syntax. But we are restricted to work only with optionals.</p><h4>Handling of non-optionals</h4><p>Very seldom do we have models that consist of only optionals. We really do not want our JSON library to enforce optionality. One way forward is to force unwrap the result:</p><pre>struct Person { <br>  var name: String // No longer optional<br>  var age: Int?<br>    <br>  init(jar: Jar) {<br>    name = jar[&quot;name&quot;]! // force unwrap will halt the app if failing<br>    age = jar[&quot;age&quot;]<br>  }<br>}</pre><p>But if the JSON does not contain the key “name” or if the value of “name” is not a String, the app will halt. This might be ok if you can guarantee the format of your JSON. But that is seldom the case.</p><p>So now you start to see the guard/if let dance:</p><pre>init?(jar: Jar) { // init is now optional<br>  guard let name = jar[&quot;name&quot;] else { return nil }<br>  self.name = name<br>  age = jar[&quot;age&quot;]<br>}</pre><p>This requires returning an optional Person. Unfortunately, we will not know what caused the error if nil is returned. Was the value absent, or of the wrong type? What we really would like is some proper error handling.</p><h4>Error handling</h4><p>Swift has a great model for error handling, so why not use it? An improvement over using optional initializers is to let the initializer throw instead:</p><pre>init(jar: Jar) throws { // init is now throwing<br>  guard let name = jar[&quot;name&quot;] else { <br>    throw Error(&quot;The key &#39;name&#39; is missing or it&#39;s value is not a String&quot;) <br>  }<br>  self.name = name<br>  age = jar[&quot;age&quot;]<br>}</pre><p>A more convenient way could be to extend Optional with an unwrap helper method that throws if the value is missing:</p><pre>extension Optional {<br>  func unwrap(description: String) throws -&gt; Wrapped {<br>    switch self {<br>      case let val?: return val<br>      case nil: throw UnwrapError(description)<br>    }<br>  }<br>}</pre><p>This allows rewriting the string extraction as:</p><pre>init(jar: Jar) throws {<br>  name = try jar[&quot;name&quot;].unwrap(...) <br>  age = jar[&quot;age&quot;]<br>}</pre><p>This improves the error handling but the error lacks details of what exactly went wrong. Also, some errors are silently ignored:</p><pre>init(jar: Jar) throws {<br>  name = try jar[&quot;name&quot;].unwrap(...)  // Was the key &quot;name&quot; missing or the value not a String?<br>  age = jar[&quot;age&quot;] // If the value of &quot;age&quot; is not an Int, this should cause an error as well.<br>}</pre><p>If Swift had support for generic(<a href="#fn1-19577">1</a>) and throwing subscripts we might try something like:</p><pre>subscript&lt;T&gt;(key: String) throws -&gt; T? {<br>  return try dict[key].map { val in<br>    try (val as? T).unwrap(...)<br>  }<br>}<br><br>subscript&lt;T&gt;(key: String) throws -&gt; T {<br>  let val = try dict[key].unwrap(...)<br>  return try (val as? T).unwrap(...)<br>}</pre><p>Unfortunately we have to wait for a future version of Swift for that, and instead, work with what we have today. But as it happens, operators can both throw and be generic:</p><pre>postfix func ^&lt;T&gt;(value: Any?) throws -&gt; T? {<br>  return try value.map {<br>    try ($0 as? T).unwrap(...)<br>  }<br>}<br><br>postfix func ^&lt;T&gt;(value: Any?) throws -&gt; T {<br>  let val = try value.unwrap(...)<br>  return try (val? T).unwrap(...)<br>}</pre><p>In Lift this is called the “lift operator” as it is used to lift values out of Jar containers(<a href="#fn2-19577">2</a>).</p><p>We have now derived the syntax used by the Lift library:</p><pre>init(jar: Jar) throws {<br>  name = try jar[&quot;name&quot;]^<br>  age = try jar[&quot;age&quot;]^<br>}</pre><h4>Extensible</h4><p>Unfortunately, the above implementation of the lift operator will only allow us to work with the limited set of known JSON types. If we like to work other types than JSON’s string, number, bool, null, array, and dictionaries, we are out of luck. What we need is a way to go from JSON values to other types as well. This is a perfect place to introduce a new protocol:</p><pre>protocol JarConvertible {<br>  init(jar: Jar) throws<br>}</pre><p>Similarly, we need to be able to generate JSON from these other types as well:</p><pre>protocol JarRepresentable {<br>  var jar: Jar { get }<br>}</pre><p>And for many types we want to implement both protocols:</p><pre>typealias JarElement = JarRepresentable &amp; JarConvertible</pre><p>Applying this to Int could look like:</p><pre>extension Int: JarElement {<br>  init(jar: Jar) throws {<br>    self = try (jar.asAny() as? Int).unwrap(&quot;Object &#39;\(value)&#39; is not convertible to Int&quot;)<br>  }<br>    <br>  var jar: Jar { return Jar(unchecked: self) }<br>}</pre><h4>Custom type handling</h4><p>This is all and well for common types already known to Lift. But the use of a protocol will also open up Lift for our custom types (types not known to Lift). This works for both simple types such as:</p><pre>struct Money {<br>  var fractionized: Int<br>}</pre><p>Where we now can reuse the already added support for Int:</p><pre>extension Money: JarElement {<br>  init(jar: Jar) throws {<br>    fractionized = try jar^<br>  }<br>    <br>  var jar: Jar { return Jar(fractionized) }<br>}<br><br>let jar: Jar = [&quot;amount&quot;: Money(fractionized: 2000)]<br>let amount: Money = try jar[&quot;amount&quot;]^</pre><p>As well as for more complex and record like types:</p><pre>struct Payment {<br>  var amount: Money<br>  var date: Date<br>}<br><br>extension Payment: JarElement {<br>  init(jar: Jar) throws {<br>    amount = try jar[&quot;amount&quot;]^<br>    date = try jar[&quot;date&quot;]^<br>  }<br>    <br>  var jar: Jar { <br>    return [&quot;amount&quot;: amount, &quot;date&quot;: date] <br>  }<br>}<br><br>let jar: Jar = [&quot;payment&quot;: Payment(...)]<br>let payment: Payment = try jar[&quot;payment&quot;]^</pre><p>We have now come to a point where the API is mature enough to work both with built-in types as well as our custom types. Due to limits of the current version of Swift, we did not reach the ideal syntax that we aimed for, but we came fairly close and gained a lot of other benefits along the way.</p><h4>Summary</h4><p>We started with an ideal syntax to work with JSON like data. Being a good Swift citizen we soon added requirements such as static typing, error handling and support to extend our custom types. This led us towards the syntax and protocols being used by the Lift library today.</p><p>Of course, there is a lot more to a fully featured JSON library than what was covered in this article. If you want to read more about Lift and try it out yourself you can find it at <a href="https://github.com/iZettle/Lift">GitHub</a>. And as Lift is open source you are more than welcome to look at its implementation, and why not contribute to it as well?</p><ol><li>Swift 4.0 added support for generic subscripts, but they still can not throw.</li><li>In Lift the lift operator will work on Jar containers instead of Any values and the Jar subscripts will wrap returned values in new Jar containers.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d83f8b6d0b38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>