[swift-evolution] Replace throws with Result

Jose Manuel Sánchez Peñarroja josema at vitaminew.com
Wed May 3 09:12:53 CDT 2017

> At what cost ? Today, the error handling is barely zero-cost thanks to the swift calling convention. Having a generic return type will not only prevent calling convention optimization, but it will also add cost to all the return types as they will have to embed a discriminator.

I guess I’m thinking more in terms of usage and elegancy than performance. I don’t know which implications this might have.

> Is it really a benefit ? Working with functions that returns an optional (and can throw) will be far more complex as we will have to deal with 2 levels of unwrapping, one for the error, and a second one for the returned value.

I think it would make very little sense to return a Result<ErrorT, Optional<T>>. Just like it doesn’t make much sense to return a Optional<Optional<T>>. It could still happen at some point, but the optional could be upgraded to Result and then everything flattened.

> All error handling pattern have a intrinsic complexity. I don’t see how having to call mapError after each call will make thing easier.

In my opinion it’s easier to learn how optional works, and then use that knowledge for Result, instead of learning 2 different patterns for similar things. Optional can be used for computations where the error is obvious (like Array.first), and Result when more information is needed. Also, Result is not something very original. There are already some implementations of this for Swift, and it is widely used in Haskell (Either) and other languages for dealing with errors.

To be honest I never thought this would happen, as it involves a lot of breaking changes, but I expected to have a little discussion to see how feasible it would be in the long run.

More information about the swift-evolution mailing list