You can support all styles with enum as well. What don’t you do this:

public enum Result<T> {
    
    case value(T)
    case error(Error)
    
    public init(_ value: T) { self = .value(value) }
    public init(error: Error) { self = .error(error) }

    public func get() throws -> T {
        switch self {
        case let .value(value): return value
        case let .error(error): throw error }
    }
    
    public func map<U>(_ transform: (T) throws -> U) throws -> U { return try 
transform(get()) }
    
    public var value: T? {
        switch self {
        case let .value(value): return value
        case .error: return nil }
    }
    
    public var error: Error? {
        switch self {
        case .value: return nil
        case let .error(error): return error }
    }
}


> On Nov 14, 2017, at 3:40 PM, Guillaume Lessard via swift-evolution 
> <swift-evolution@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@swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to