[swift-evolution] [Proposal] Powerful enumerations built upon protocols, structures and classes
Al Skipp
al_skipp at fastmail.fm
Tue Dec 15 07:59:37 CST 2015
> Sum types look very interesting and are very similar to enumerations.
> If there is enough interest in sum types then this proposal could probably cover them too since it already provides a good foundation for implementing them.
> It could also be proposed separately or on top of this proposal.
> In any case this proposal does not prevent sum types from being added to Swift.
Swift already has Sum types, they are enums. Pretty much all the other constructs are Product types (structs, classes, tuples…). I’ve not managed to read your detailed proposal in full, but it strikes me that it would involve quite fundamental changes. Not sure what all the consequences would be and what the value is in blurring the distinction between Sum types and Product types?
My personal view is that the distinction between enums and protocols is important. Your proposal would enable the easy creation of extensible enums which I find problematic. When using extensible enums you’d be obliged to include a ‘default’ case in every switch statement. You point out that you’d be able to restrict the cases by using ‘final’ or some other means, but in practice I think the extensible form would be popular for its perceived flexibility.
Currently if I create an enum I am obliged to deal with all cases in a switch (assuming I don’t use a default case, which I try to avoid). Now imagine I subsequently realise I need to add a case to the enum. OK, I do so, now all my code breaks, arghh! But this is a good thing! The compiler guides me to every piece of code I need to change – magic! If on the other hand, enums were easily extensible, I’d add my new case and my code would still compile, brilliant! However, my code is fundamentally broken and I have to manually fix it without any guidance from the compiler.
That’s why I think the distinction between enums and protocols is important - enums are useful because they’re not extensible.
When a type is required that can be extended with new cases, then a protocol is the right tool for the job, rather than an enum.
My worry is this proposal would reduce compile time guarantees in Swift and make me more responsible for finding my own bugs (the horror!).
Al
More information about the swift-evolution
mailing list