Adding Either type to the Standard Library

I think @Dmitriy_Ignatyev lays out pretty compelling reasons for Either's addition:

I feel like a need to clarify that Either won't try to replace all 2-case enums and neither will OneOf replace all enums, just as Tuples haven't replaced structs. Tuples still have labels and they are more concise, still though structs are usually preferred. Either just as Tuples, fits naturally in places where the creation of a new type just doesn't make sense. For example, such a type is present in the Standard Library, in the "automatic protocol satisfaction" proposal, in function builders it would make sense if it was used instead of two separate - and confusing - buildEither methods. Additionally, in places where the creation of a new type is currently not allowed:

struct FooGeneric {
    func fooGeneric<Baz>(baz: Baz) {
        enum State { case bar(Bar), case foo(Foo) } // ❌ 

        ...
    }
}

of course we can do:

struct FooGeneric {
    enum State { case bar(Bar), case foo(Foo) }

    func fooGeneric<Baz>(baz: Baz) {
        ...
    }
}

but in the above cases if we use State just in fooGeneric it would make much more sense for an Either type to take State's place. Not to mention the boilerplate that would be required should we want Equatable conformance.

I recognise that Either is not the ideal type, we'd all like to have. Nonetheless, I feel that it is needed for the cases outlined above - or at least it would make them more pleasant to deal with. Finally, let's not forget that having an OneOf as I mentioned before, is not an option currently, so adding Either for now seems like a good option and discussing how to best implement is the goal of this discussion. If you have any other ideas that are realistic for the above examples and is more elegant than Either feel free to share them.

1 Like