Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum from string

Given the following declarations below, is there a way to retrieve the enum value (e.g. jt_one) from a string value (e.g. 'one')?

type
 TJOBTYPEENUM =(jt_one, jt_two, jt_three);


CONST JOBTYPEStrings : ARRAY [jt_one..jt_three] OF STRING =
     ('one','two','three');

Or do i need to create my own function using a nested set of if statements?

NOTE: I am not looking for the string "jt_one"

like image 747
Blow ThemUp Avatar asked Oct 18 '12 17:10

Blow ThemUp


2 Answers

function EnumFromString(const str: string): TJOBTYPEENUM;
begin
  for Result := low(Result) to high(Result) do 
    if JOBTYPEStrings[Result]=str then
      exit;
  raise Exception.CreateFmt('Enum %s not found', [str]);
end;

In real code you'd want to use your own exception class. And if you want to allow case insensitive matching, compare strings using SameText.

like image 56
David Heffernan Avatar answered Sep 30 '22 15:09

David Heffernan


function GetJobType(const S: string): TJOBTYPEENUM;
var
  i: integer;
begin
  for i := ord(low(TJOBTYPEENUM)) to ord(high(TJOBTYPEENUM)) do
    if JOBTYPEStrings[TJOBTYPEENUM(i)] = S then
      Exit(TJOBTYPEENUM(i));
  raise Exception.CreateFmt('Invalid job type: %s', [S]);
end;

or, neater,

function GetJobType(const S: string): TJOBTYPEENUM;
var
  i: TJOBTYPEENUM;
begin
  for i := low(TJOBTYPEENUM) to high(TJOBTYPEENUM) do
    if JOBTYPEStrings[i] = S then
      Exit(i);
  raise Exception.CreateFmt('Invalid job type: %s', [S]);
end;
like image 21
Andreas Rejbrand Avatar answered Sep 30 '22 17:09

Andreas Rejbrand