[swift-evolution] List of all Enum values (for simple enums)

Brent Royal-Gordon brent at architechies.com
Wed Dec 9 06:05:45 CST 2015


>     extension Attribute {
>         static var allValues: [Attribute] {
>             return [.Title, .Date]  // imagine this x100, and not autogenerated :(
>         }
>     }
> 
> It would be nice if the compiler generated this for us.

You know, I was thinking about this the other day when the topic of numeric minimum/maximums came up.

In some sense these are related ideas. These types have in common that they have a particular finite, easily-calculated set of possible values, and it’s convenient to be able to look at that set in various ways. This has the feel of a protocol:

	protocol Enumerable {
		typealias Enumeration: SequenceType where Generator.Element == Self
		var allValues: Enumeration
	}

For a simple enum, `Enumeration` would be something like an `Array` or `Set`, and `allValues` would primarily be iterated over; for an integer type, `Enumeration` would be a range and `allValues` would primarily have its `first` and `last` elements examined. (Well, there’s a problem with using a range. A `Range<T: IntegerType>` can never include `T.max`, because then its `endIndex` would have to be `T.max + 1`, which is by definition not representable in `T`. But you could imagine a range-like type without this limitation.) However, in each case there are some fairly useless operations exposed by `allValues`, and I’m not sure if I like that.

One interesting thing I noticed: enums with associated values could also be made `Enumerable`, as long as all associated values are `Enumerable` and the enum is not recursive. For instance:

	enum Foo {
		case Alice, Bob
	}
	enum Bar {
		case Charlie (Foo), Eve (Foo, Foo)
	}
	Bar.allValues   // => [ .Charlie(.Alice), .Charlie(.Bob), .Eve(.Alice, .Alice), .Eve(.Alice, .Bob), .Eve(.Bob, .Alice), .Eve(.Bob, .Bob) ]

This is even in principle true of associated values of type `Int`, although obviously the set of possible values for `Int` would be so large that it would have to be generated lazily (not to mention that I can’t see much practical use for it). This would also imply that `Optional<T: Enumerable>` would be `Enumerable`, with an `allValues` consisting basically of `[.None] + Wrapped.all.map(.Some)`.

Anyway, I’m not sure if what I’m describing here is a good idea. It might be overcomplicating things, and some parts of it would probably be difficult to implement. But I thought it was an interesting observation.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list