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.

Limitations: Does not work with enums whose members' values cannot be used in a switch statement. This includes enums with members that share values with other members, as well as enums of values that are non-string arrays or other complex types.

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.

Examples

enum E { a, b, c }

E a = Enum!E.fromString("a");
E c = Enum!E.fromString("c");

assert(a == E.a);
assert(c == E.c);

// Enum members must not share values
enum F { d = 1, duplicate = 1 }
//F d = Enum!F.fromString("d");  // compile-time error