[swift-evolution] ValueEnumerable protocol with derived implementation for enums

Vladimir.S svabox at gmail.com
Mon Apr 18 09:19:55 CDT 2016

On 16.04.2016 5:00, Jacob Bandes-Storch via swift-evolution wrote:
> I believe the community is in agreement about the following:
>     • The "allValues" behavior should be provided by conformance to some
> protocol, named ValueEnumerable or ValuesEnumerable or similar.
>     • The compiler should derive an allValues implementation for "simple"
> enums (those without associated values).

Please let me add my 2 cents. (Unfortunately can't support discussion on 
suggested level, sorry for some simplicity)

I believe first of all we need a easy to use method to iterate enum cases 
_without_ the need of manually specify each of case value in code for this.

I believe this is a huge problem we have now with enums. Ar at least Swift 
compiler should force us to specify each of case values in such array.

I mean that we can now implement this allValues by just introduce an array 
constant in enum{} declaration "manually". _But_ we need to change this 
array accordingly each time we add new or change order of 'cases'  in our 
enum. And right now this is the place where we most likely will have errors 
with forgotten values/wrong order.

Should we add extra complexity to Swift to implement the solution? I'm not 
Can't compiler "just" generate some kind of
static let allValues : [Self] = [firstCase, secondCase, ..]
for each enum(and only enum)? Should we introduce a dozen of 
protocols,extensions etc to implement such a solution just for enums?

enum ZZZ {
     case One, Two

     // this can be auto-generated
     static let allValues: [ZZZ] = [.One, .Two]

As for generic enums, the best I can implement right now, is calculated 

enum AAA<T,Z> {
     case One, Two   // somehow T,Z is used here, not important

     // I believe this could be also auto-generated
     static var allValues : [AAA<T,Z>]  { return [.One, .Two] }

As for the order of elements in allValues, IMO this order should be exactly 
as defined in enum. We can know the Raw value for specified enum case 
value, when we have it. But we can't say the defined position/index of enum 
case if we'll have allValues ordered by raw value.

enum ZZZ: Int {
     case One = 3, Two = 1

     // autogenerated:
     //static let allValues: [ZZZ] = [.One, .Two]

print(ZZZ.allValues) => [One, Two]
print(ZZZ.allValues[0].rawValue)  => 3

if allValues will return [Two, One], we can't find out how these cases was 
declared in our enum. I.e. in first case we have a solution(sort by 
rawValue), in second case - we have no solution.

More information about the swift-evolution mailing list