[Re-Proposal] Type only Unions

I understand why we are discouraged from using typed throws. The proposal very clearly stated how harmful they can be. But they simply exist and there are certainly cases where "catch them all" is viable.

For starters, a custom enum Union2<T, U>: Error where T: Error, U: Error (and higher arities) will do.

But in generic contexts like

the E can already be Union2 which would result in propagating nested unions. And this is why I find a very lightweight union feature somewhat compelling. Simply because statically summarized ErrorA | ErrorB is swiftier than reducing some Union2<ErrorA, Union2<Union3<Never, ErrorB, ErrorA>, Never>>.

There certainly are cases where expecting a couple of errors within a module is neither a cardinal sin nor something that should make you feel guilty of being a Java developer. However, propagating in generic contexts takes a toll without unions.

I've noticed the mention of "closed" protocols (also discussed on the forum as "sealed"). While I don't think they would solve the problem of typed throws exhaustion, perhaps the unions could help to declare a closed/sealed protocol?
public protocol Beverage where Self ~= Water | Espresso | Beer
Take it with a grain of salt; I'm anything but a compiler engineer.

I remember times when typed throws were a heresy, and here we are. It just needs time until the core team finds a need for it; just like Task brought us the typed throws.

I don't think this is always viable, if you are for example providing a closure to a third party library (such as a dynamically linked standard library function, system api etc) that has some behaviors based on errors you throw this third party lib is not going to be able to deal with a custom enum you create within your closure.

Over the years of using Swift, I have changed my view on this subject from negative to neutral.

Just like tuples can be used as lightweight, anonymous structs, If some day there's a syntax for Swift to describe anonymous enums, I will surely welcome it with my arms.

1 Like