digitalmars.D.learn - Can I check if a value is convertible to a valid value of an enum?
- French Football (17/17) Sep 24 2015 ...without having to loop over the enum?
- thedeemon (9/11) Sep 24 2015 Since `value` is known only at run time, some checks need to be
- Nicholas Wilson (7/24) Sep 24 2015 find + EnumMembers should do the trick
- Meta (7/12) Sep 25 2015 Should be
...without having to loop over the enum? enum SomeType : string { CHEESE = "cheese", POTATO = "potato" } string valid_value = "cheese"; string invalid_value = "pizza"; bool test( string value ){ if( value.isConvertableToSomeType ){ // this be the magic I seek //do something return true; } return false; } void main(){ writeln( test( valid_value ) ); //prints true writeln( test( invalid_value ) ); //prints false } Or would I need to foreach over the enum somehow?
Sep 24 2015
On Friday, 25 September 2015 at 03:12:20 UTC, French Football wrote:...without having to loop over the enum? writeln( test( valid_value ) ); //prints trueSince `value` is known only at run time, some checks need to be performed at run time anyway. One way of doing it without iterating over all variants is to create a static hash table bool[string] valid_strings; and populate it in static constructor, then in your function you can just write if (value in valid_strings) ...
Sep 24 2015
On Friday, 25 September 2015 at 03:12:20 UTC, French Football wrote:...without having to loop over the enum? enum SomeType : string { CHEESE = "cheese", POTATO = "potato" } string valid_value = "cheese"; string invalid_value = "pizza"; bool test( string value ){ if( value.isConvertableToSomeType ){ // this be the magic I seek //do something return true; } return false; } void main(){ writeln( test( valid_value ) ); //prints true writeln( test( invalid_value ) ); //prints false } Or would I need to foreach over the enum somehow?find + EnumMembers should do the trick if ( (EnumMembers!SomeType).canFind(value)) { // ... }
Sep 24 2015
On Friday, 25 September 2015 at 03:20:24 UTC, Nicholas Wilson wrote:find + EnumMembers should do the trick if ( (EnumMembers!SomeType).canFind(value)) { // ... }Should be if (only(EnumMembers!SomeType).canFind(value)) { //... }
Sep 25 2015