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

Joe Groff jgroff at apple.com
Thu Dec 10 15:06:31 CST 2015


> On Dec 9, 2015, at 8:21 PM, Kevin Wooten <kdubb at me.com> wrote:
> 
> 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.

String(e) is defined for all types; there's an unconstrained String.init<T>(_: T) method. It's implemented using runtime reflection. You should use the String(x) initializer, or the equivalent interpolation "\(x)", instead of using .description directly.

-Joe


More information about the swift-evolution mailing list