iterate over enum name:value pairs

Jay Norwood jayn at prismnet.com
Sat Dec 7 21:11:23 PST 2013


Thanks.  This is exactly what I was looking for.

I tried this iteration below, based on the example shown in the 
std.traits documentation, and the int values are not what I 
expected, but your example works fine.

http://dlang.org/phobos/std_traits.html#.EnumMembers


import std.traits;

void main()
{
     enum Suit { spades, hearts=4, diamonds=10, clubs }

     foreach (i, member; EnumMembers!Suit)
     {
	writefln("%s: %d", member, i);
     }

}


D:\dprojects\ConsoleApp1\ConsoleApp1>dmd -run main.d
spades: 0
hearts: 1
diamonds: 2
clubs: 3

but the same example, substituting writefln("%s: %d", member, 
member) prints

D:\dprojects\ConsoleApp1\ConsoleApp1>dmd -run main.d
spades: 0
hearts: 4
diamonds: 10
clubs: 11


More information about the Digitalmars-d-learn mailing list