Hello Swift Evolution,
What are your thoughts on adding an Either
type:
enum Either<First, Second> {
case first(First), second(Second)
}
Many wonder why would we need such a type. Well, having an Either
type built into Swift comes in handy in some situations, where the developer just needs such a behaviour, but they have to create their own one. Being a part of the Standard Library would alleviate this needless "boilerplate".
Examples:
1. Function Builders
Instead of the current approach:
static func buildEither(first: Component) ->
Content { ... }
static func buildEither(second: Component) ->
Content { ... }
which is quite confusing, we would have:
static func buildEither(either: Either<ComponentA, ComponentB>) ->
Content { ... }
This example, perfectly highlights the need for such a simple type.
2. Everyday cases
Sometimes, it's just useful to have an Either type. For example:
struct Image {
...
var alpha: Either<AlphaComponent, NoAlpha>
}
In this hypothetical example, the AlphaComponent
type specifies how the alpha component is encoded in the image data, whereas NoAlpha
specifies how to decode the image data when there is no alpha channel.
There are countless other cases where Either
would be useful to just have around. What are your thoughts?
3. Standard Library
Albeit not widely, it is used in the Standard Library as an internal type:
internal enum _Either<Left, Right> {
case left(Left), right(Right)
}
which shows that even in the space cases where it appears, boilerplate is currently unavoidable. Furthermore, the problem is highlighted when considering that in library settings, the declaration is not as simple as the one shown above. Instead, conditional conformances are common, as is illustrated in the Standard Library. That means that boilerplate is not just an additional cost of three lines, in the contrary it can take up 10 times as much.
Why not just use an enum?
Well, writing a custom enum is just boilerplate. With Either
, though, being a standardised type, useful extension could be provided. For instance, in the image example above, Either
provides conditional conformances for Hashable
- and Equatable
, allowing Image itself to conform to Hashable
. Also, many argue that custom enums provide more descriptive names. While that's true in some cases, it is most often a subtle gain. What makes people uneasy at the sight of Either
is in many case, unfamiliarity with it as pointed out by @ExFalsoQuodlibet.