Search code examples
enumstype-conversiond

Can I Convert a String to an Enum Value in D?


I have the following enum declared which using a string as its underlying value:

enum IssueType : string {
    STUDENT_LEAVING = "leaving",
    STUDENT_CONFLICT = "conflict",
    NEEDS_ARCHIVE = "archive",
    OTHER = "other"
}

I want to be able to do the following:

string s = "conflict";
IssueType type = std.conv.to!IssueType(s);

Currently, it is only possible to convert from a string to the enum by providing a case-sensitive match for one of the enum value names, like in this case the string "STUDENT_CONFLICT" would be accepted, while I want "conflict" to be accepted.


Solution

  • Simply cast the string to the enum type.

    IssueType type = cast(IssueType)s;