views:

48

answers:

4

I want to test for transition from one state to another. I have defined my states in an enum like this:

enum FingerStatus {
FINGERS_UP,
MOVING,
FINGERS_STILL
};

I have a "currentState" and a "newState" variable. I know that enums are just integers, and if they're 16-bit integers, which I think they are, it's possible to represent two enums as a single 32-bit integer.

I feel like I ought to be able to do something along the lines of

switch ({currentStatus, newFingerStatus}) {
    case {FINGERS_STILL, MOVING}:
        NSLog(@"fingers starting to move");
        break;
    case {MOVING, FINGERS_STILL}:
        NSLog(@"fingers stopped moving");
        break;
    default:
        break;
}

I realize the syntax is all wrong, but I think the basic idea is sound. Is there another nice, clean way to do this?

A: 

Since switches are just a fancy way to write gotos, you can't use them to do what you want to do. Use ifs instead:

if(currentStatus == FINGERS_STILL && newFingerStatus == MOVING)
{
    NSLog(@"fingers starting to move");
}
else if(currentStatus == MOVING && newFingerStatus == FINGERS_STILL)
{
    NSLog(@"fingers stopped moving");
}
Etienne de Martel
A: 

Ints can be more than 16bits, and usually 32bits on computers( not sure about iPhone), but your idea would still work.

You can use (intOne + ( intTwo << 4 )) to put the two ints together, for comparison and evaluation.

Alexander Rafferty
+1  A: 

If you can guarantee your enums are less than 16 bits, this will work:

switch ((currentStatus<<16) + newFingerStatus) {
    case (FINGERS_STILL<<16) + MOVING:
        NSLog(@"fingers starting to move");
        break;
    case (MOVING<<16) + FINGERS_STILL:
        NSLog(@"fingers stopped moving");
        break;
    default:
        break;
}
xscott
Thanks! Can I guarantee that they're less than 16 bits by just assigning values to them that can be held using 16 bits or less?
morgancodes
Yes, if you assign values to them, then they'll have those values. :-)
xscott
I should've been more precise and said, "if the values of your enums can be represented in less than 16 bits".
xscott
Cool. This works for me. I wound up making another enum representing the transitions so that my switch statement could be prettier. Thanks again for the help.
morgancodes
Happy to help. Cheers.
xscott
A: 

well for one it would probably wise to give the enums different unique values: 1,2,4 and not 0,1,2 then you can bitwise or them. Then you can do labels like:

case FINGERS_STILL|MOVING:
Anders K.