Enum.fromString

Takes the member of an enum by string and returns that enum member.

It lowers to a big switch of the enum member strings. It is faster than std.conv.to and generates less template bloat. However, it does not work with enums where multiple members share the same values, as the big switch ends up getting duplicate cases.

Taken from: https://forum.dlang.org/post/bfnwstkafhfgihavtzsz@forum.dlang.org written by Stephan Koch (https://github.com/UplinkCoder). Used with permission.

template Enum(E)
@safe pure
E
fromString
(
const string enumstring
)
if (
is(E == enum)
)

Parameters

enumstring string

the string name of an enum member.

Return Value

Type: E

The enum member whose name matches the enumstring string (not whose *value* matches the string).

Throws

ConvException if no matching enum member with the passed name could be found.

Bugs

Does not work with enums that have members with duplicate values.

Examples

enum SomeEnum { one, two, three };

SomeEnum foo = Enum!SomeEnum.fromString("one");
SomeEnum bar = Enum!SomeEnum.fromString("three");

assert(foo == SomeEnum.one);
assert(bar == SomeEnum.three);

Meta