[swift-evolution] Adding Result to the Standard Library

David Waite david at alkaline-solutions.com
Tue Nov 14 18:01:52 CST 2017


For some generic function

func doSomething() -> Result<String>

You could write (potentially pseudocode);

func doSomething() throws -> String {
   return try doSomething().value()
}

with Result defined as:

enum Result<T> { 
 case success(T)
 case error(Error) 
 func value() throws -> T {
     switch self {
        case success(let t):
            return t
        case error(let e):
            throw e
      }
  }
}

IMHO, the real value for a Result type (or Future/Promise type) in the core library would be the compiler support for the type. Why would you want to define two versions of the doSomething function just to deal with code that wants a Result and code which doesn't?

That, and people implementing Result themselves internally in 15 lines making it a question of supporting *everyone’s* Result types, not just a system type.

-DW
 
> On Nov 14, 2017, at 4:40 PM, Guillaume Lessard via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I’m late to this particular party, but having just caught up with the thread I’m surprised that no one substantially addressed the stylistic duality that a `public enum Result` would bring.
> 
> In short, I’d rather Result be a struct than an enum.
> 
> I too implemented a Result, for obvious reasons. I was, however, unsatisfied that it added another interface for error handling, namely switching over the enum — it’s not really better, not really worse, but now there are more error handling patterns to look for in your code.
> 
> My solution was to simply switch to a `struct Result`, where the enum is private. The only way to get the value out is via a throwing method. See <https://gist.github.com/glessard/48f4c1305ac20b1b99c1bbdc2fb6290c> for a no-frills implementation.
> 
> This has all the advantages of the Result enum — it’s easily used in asynchronous situations and can implement the desired functional/monadic niceties, but without exposing an unnecessary alternate interface to Swift’s native error handling.
> 
> Cheers,
> Guillaume Lessard
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list