[swift-evolution] [proposal] Either in the Swift Standard Library
Haravikk
swift-evolution at haravikk.com
Tue Jan 26 04:15:46 CST 2016
> On 26 Jan 2016, at 09:52, Andrew Bennett via swift-evolution <swift-evolution at swift.org> wrote:
>
> It seems like the argument comes down to:
> * An either-like type should be named something meaningful for the context it is used
> * There are a lot of cases where an either-like type is useful, there may generalised functions that are often used on them
> * Is defining or re-defining an either type hard?
> * Is it too niche to be in the standard library
>
> Personally I think defining an either type is not hard:
>
> enum Result<T,E: ErrorType> {
> case Value(T), Error(E)
> }
>
> I think it may be too niche to be in the standard library, from the "meaningful context" perspective.
>
> Perhaps what we want is not an either type, but an easy to conform to protocol that allows some reuse with Either-style types. Possibly with some compiler magic to make it easy for enums to conform to it...
>
> I've thrown an example protocol together here:
> https://github.com/therealbnut/Either <https://github.com/therealbnut/Either>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
Personally I agree that this is pretty niche these days; if I want to return either a result or an error, then I now have the option of throwing an exception, and this in my experience was the most common case where something like this was needed.
If the aim is to allow a function to return one of several possible types, then the question is… why only two? If we were looking at allowing several possible return types then what I’d really rather see is some kind of compiler magic that supports that, so I could do stuff like:
func myFunc() -> Int, Double, String { … }
This could then create an implicit enum that I could then check via cases like:
case .Double(value): doSomething(value)
case .Int(value): doSomethingElse(value)
case .String(value): doSomethingStringy(value)
There could also be some kind of naming syntax, to enable returning one of two possible values of the same type, but with different meanings, otherwise the case would be implicitly named for the type of data that it holds.
Otherwise… I think use of Either is too specialised, and too easily done yourself with a name that’s more specific to your use-case.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160126/6c5f2778/attachment.html>
More information about the swift-evolution
mailing list