[swift-evolution] List all values of a simple enum and extension constraint to enum types

David Sweeris davesweeris at mac.com
Mon Mar 13 18:42:58 CDT 2017

> On Mar 10, 2017, at 10:15 AM, Trevör ANNE DENISE via swift-evolution <swift-evolution at swift.org> wrote:
> Hello everyone,
> As I was writing a program, I realised that I could make it safer by being able to list all possible cases of a Swift enum.
> This is similar to what has been described there:
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001233.html <https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001233.html>
> Is there any updates about it since 2015?
> Also, do you think this would be a good idea to make extensions constrainable by enum types, like that?
> extension Type where P1: enum {
> }
> You could then write something similar to this:
> protocol A {
> associatedtype P1
> associatedtype P2
> static var p1PossibleValues:[P1] { get }
> static var p2PossibleValues:[P2] { get }
> }
> extension A where P1: enum, P2: enum {
> 	static var p1PossibleValues:[P1] { return p1PossibleValues.allValues }
> 	static var p2PossibleValues:[P2] { return p2PossibleValues.allValues }
> }
> Would it make sense to do it this way?

Almost… You could have the compiler generate that for 2/3 of the types of enum, but it can’t do anything with enums that have associated values. I wrote a bit of software a while back that does as much as I could figure out how to do automatically, then makes in a compile-time error to not fill-in the blanks (which is still annoying, but at least you don’t find out about your mistake when your program crashes). Feel free to do whatever you want with it: https://github.com/TheOtherDave/EnumEnhancer

Hope that helps
- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170313/53cef82b/attachment.html>

More information about the swift-evolution mailing list