Wednesday, May 8, 2019

Optional, throws, Result, and async/await

Joshua Emmons:

Ah ha! So we see that the Result type can serve as a concrete reification of Swift’s abstract idea of “that thing that’s returned when a function is marked as throws.” And as such, we can use it to deal with asynchronous operations that require concrete types for parameters passed to their completion handlers.

[…]

Thankfully, we can clean this up by taking advantage of the fact that, like Optional, Result implements flatMap. Specifically, flatMap on a Result will, in the case of .success, apply the given transform to the associated value and return the newly produced Result. In the case of a .failure, however, flatMap simply passes the .failure and its associated error along without modification.

[…]

In the near term, we just have to lump it. It’s better than the other alternatives native to the language, and chaining asynchronous calls isn’t as common as for synchronous calls.

But in the future, just as Swift used do/catch syntax to define away Result nesting problems in synchronous error handling, there are many proposals being considered to do the same for asynchronous errors (and asynchronous processing, generally).

See also: Localized​Error, Recoverable​Error, Custom​NSError.

Previously:

Comments RSS · Twitter

Leave a Comment