Objective C switch statements and named integer constants
Asked Answered
G

2

10

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?

Girlish answered 20/12, 2010 at 8:37 Comment(1)
Make your constants static too; compiler issue I'm sure, but that seems to fix. For some reason compiler doesn't think that just const is really constant, but const static is. I'm sure there is some weird abstract reason in the docs somewhereShena
F
16

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.

Forcer answered 20/12, 2010 at 8:41 Comment(1)
This is a workable solution and is what I use, but I don't understand why the constants aren't working.Ashien
T
8

This is because case statement requires constant expression. Now in C and thus in Obj-C making a variable const does not create a true constant. Thus you are getting this error. But if you use C++ or Obj-C++ then this will work.

Some more hint is available here and here.

Torrid answered 20/12, 2010 at 8:50 Comment(2)
So, how can we create constants in Objective-C then? #define MY_CONSTANT 123 would be one way but Is that the only one?Valerie
define and enum. Thay both create true constant in C/Obj-C.Torrid

© 2022 - 2024 — McMap. All rights reserved.