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"
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
.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With