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

Kevin Wooten kdubb at me.com
Wed Dec 9 22:21:11 CST 2015


I know that this currently works...

enum MyEnum { case MyA }
let val = String(MyEnum.MyA) // yields “MyA"

Which I assume is what you are referring to.  Although, even after sifting through Swift.String, I am not sure how this support is provided. I assume some magic method is produced by the compiler for enums.

In the generics of today, auto generated functions like these do not seem to be available to generic implementations.  So what I was trying to achieve by adding the string convertible protocol was to ensure the availability of code like this…

parseFromSource<E: Enumerable>(source: Source) -> E? {
	let str = source.readString()
	for e in E.allValues {
		if (e.description == str) {
			return e;
		}
	}
	return nil;
}

From what I know of the generics implementation if we tried to replace the “e.description == str” with “String(e) == str” it would fail; since that initializer is not formalized anywhere in the Enumerable protocol.

Another option entirely would be to just always produce an initializer similar to the raw value string enum initializer that will match raw values. Essentially a magic method similar to the one I wrote above but for all enums.  Although the code above is much more flexible even beyond my simple parsing example.

> On Dec 9, 2015, at 12:06 PM, Joe Groff <jgroff at apple.com> wrote:
> 
> 
>> On Dec 9, 2015, at 4:37 AM, Kevin Wooten via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> I don’t think this is overcomplicating things at all.  I see many useful cases for this.
>> 
>> I would suggest a simple change to Enumerable…
>> 
>> protocol Enumerable : CustomStringConvertible, CustomDebugStringConvertible {
>>>> }
>> 
>> The number of times the enumeration value name is needed at runtime is just too great.
> 
> Everything is string-convertible; no need to force Enumerable implementations to provide custom printing implementations.
> 
> -Joe



More information about the swift-evolution mailing list