Getting enum from value

Matthew Remmel via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 5 10:04:32 PDT 2017


On Saturday, 5 August 2017 at 15:42:53 UTC, Rene Zwanenburg wrote:
> On Saturday, 5 August 2017 at 15:33:57 UTC, Matthew Remmel 
> wrote:
>> Any ideas?
>
> You can use to! in std.conv:
>
>
> import std.stdio;
> import std.conv;
>
> enum Foo
> {
> 	A = "A",
> 	B = "B"
> }
>
> void main()
> {
> 	writeln("A".to!Foo);	
> }

This only works because the enum name and the value are the same. 
Its actually converting on the enum name, which happens to be the 
same as the value. This doesn't work if the values is different:

enum Foo {
     A = "AV",
     B = "BV"
}

int main() {
     writeln("AV".to!Foo); // Throws exceptions
     return 0;
}

It looks like Temtaime's solution works:

>enum Foo
>{
>	A = "AV",
>	B = "BV",
>	C = "CV",
>}

>Foo K = [ EnumMembers!Foo ].find!(a => a == `BV`)[0];

I can probably make a template or something out of this to make 
the syntax simpler.


More information about the Digitalmars-d-learn mailing list