Search code examples
cocoa-touchuiscrollviewswitch-statementuiscrollviewdelegate

Objective C switch statements and named integer constants


I have a controller which serves as a delegate to two scrollviews which are placed in view managed by aforementioned view controller.

To distinguish between two scroll views I'm trying to use switch statement (instead of simple pointer comparison with if statement). I have tagged both scroll views as 0 and 1 like this

NSUInteger const kFirstScrollView = 0;
NSUInteger const kSecondScrollView = 1;

When I try to use these constants in a switch statement, the compiler says that case statements are not constants.

switch (scrollView.tag) {
    case kFirstScrollView: {
      // do stuff
    }
    case kSecondScrollView: {
      // do stuff
    }
}

What am I doing wrong?


Solution

  • This can be solved through the use of an anonymous (though not necessarily so) enum type:

    enum {
        kFirstScrollView = 0,
        kSecondScrollView = 1
    };
    
    switch (scrollView.tag) {
        case kFirstScrollView: {
          // do stuff
        }
        case kSecondScrollView: {
          // do stuff
        }
    }
    

    This will compile without errors.