Optional, throws, Result, and async/await
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 asthrows
.” 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
implementsflatMap
. Specifically,flatMap
on aResult
will, in the case of.success
, apply the given transform to the associated value and return the newly producedResult
. 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 awayResult
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: LocalizedError, RecoverableError, CustomNSError.
Previously: