switch with enum

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Nov 25 11:59:58 PST 2015


On Wednesday, 25 November 2015 at 03:51:48 UTC, tcak wrote:
> I have seen a code a while ago, but even by looking at 
> documentation, I couldn't have found anything about it.
>
> Let's say I have defined an enum;
>
> enum Status: ubyte{
>  Busy = 1,
>  Active = 2
> }
>
> and received a ubyte value from user.
>
> ubyte userValue;
>
> I want to switch over userValue, but that should depend on 
> Status.
>
> switch( userValue ){
> ...
> }
>
> What I mean is that compiler should enforce values of enum 
> "Status" to be declared in switch as it would be done with 
> "final switch", but as you can guess, user might enter a value 
> that is not defined by Status. Thus, I should be able to enter 
> the case "default" as well.
>
> I remember it something like switch( userValue ) with( Status 
> ){...}, but not sure about it. Maybe it was D1 code. Is there 
> anything like this currently?

One way you could do it:

import std.conv: to;

try
{
     switch (userValue.to!Status)
     {
         ...
     }
}
catch (ConvException c)
{
     //Default case
}


More information about the Digitalmars-d-learn mailing list