Swift result types. Are they useless?
Tags: swift, discuss, programming, asynchronous
Published: 2018-10-28 03:38:16

---
title: Swift result types. Are they useless?
published: true
description: A debate about the value of Swift Result Types
tags: swift, discuss, programming, asynchronous
cover_image: https://thepracticaldev.s3.amazonaws.com/i/0dtho3s0txi31ah44yw0.jpg
---

Fresh-faced, amateur, and impressionable: Swift is not my main jam. When setting out to write [Amatino Swift](https://github.com/amatino-code/amatino-swift), I was hungry for best-practice and good patterns. Amatino Swift involves lots of asynchronous HTTP requests to the [Amatino API](https://amatino.io).

Asynchronous programming requires bifurcation at the point of response receipt. That is, an asynchronous operation may yield a success state or a failure state. Result types are a pattern widely espoused as a pattern for handling such bifurcation.

I'd like to open a debate over whether result types should be used in Swift. After some thought, it appears to me that they are useless. I propose that we would be better off encouraging newbies to utilise existing Swift features, rather than learning about and building result type patterns.

For the purposes of this discussion, let's assume that our code includes two functions, each of which handle a bifurcated state:

```swift
func handleSuccess(data: Data) {
    // Do stuff with data
}

func handleFailure(error: Error) {
    // Do stuff with error
} 
```

Inside these functions, we might implement code which is independent of our bifurcation pattern. For example, we could `case-switch` on Error type in order to present a meaningful message to a user.

Now to the bifurcation itself. A naive and simple pattern might be:

```swift
// This is bad code. Do not copy it!
func asynchronousCallback(error: Error?, data: Data?) -> Void {
    if (error != nil) {
        handleFailure(error!)
        return
    }
    handleSuccess(data!)
    return
}
```

There are myriad problems with this approach. We have no type safety over `data`. We do not control for cases where programmer error yields a state where both `data` and `error` are `nil`. It's ugly. More.

Result types propose to improve upon this pattern by defining a type such as:

```swift
enum Result<Value> {
    case success(Value)
    case failure(Error)
}
```

Which may be used like so:

```swift
func asynchronousCallback(result: Result<Data>) {
    switch result {
    case .success(let data):
        handleSuccess(data)
    case .failure(let error):
        handleError(error)
    }
    return
}
```

This pattern introduces type safety to both `error` and `data`. I suggest that it does so at too great a cost when compared to using inbuilt Swift features. Every asynchronous bifurcation now requires a `switch-case` statement, and the use of a result type.

Compare the result type pattern with one that uses the Swift `guard` statement:

```swift
func asynchronousCallback(error: Error?, data: Data?) {
    guard let data = data else { handleError(error ?? TrainWreck()) }; return
    handleSuccess(data)
    return
}
```

In this case, we have type safety over `error` and `data`. We have handled a case in which a programmer failed to provide an `Error` using the nil-coalescing operator `??`. We have done it all in two lines of less than 80 char. A suitable error type might be defined elsewhere as:

```swift
struct TrainWreck: Error { let description = "No error provided" }
```

Bifurcation via a `guard` statement appears to me to have several advantages over result types:

* **Brevity**. Functions handling asynchronous callbacks need only implement a single line pattern before proceeding with a type safe result.
* **Lower cognitive load**. A developer utilising a library written with the `guard` pattern does not need to learn how the library's result type behaves.
* **Clarity**. A `guard` statement appears to me to be more readable than a `case-switch`. This is subjective, of course.

What do you think? I am not a Swift expert. Am I missing something obvious? Why would you choose to use a result type over a `guard` statement?

*Cover image - A bee harvests pollen from lavender on [Thornleigh Farm](https://thornleighfarm.com)*