我想使用以下表达式
-(void)SwitchCondn{
int expression;
int match1=0;
int match2=1;
switch (expression)
{
case match1:
//statements
break;
case match2:
//statements
break;
default:
// statements
break;
}
但我得到了
当我研究时,我找到了
In order to work in Objective-C, you should define your constant either like this:
#define TXT_NAME 1
Or even better, like this:
enum {TXT_NAME = 1};
我一直在使用这种方法。现在我的变量值将在运行时改变,所以我需要以其他方式定义,我不想使用if else所以是否有任何方式的声明变量其他方式
我接受过
的研究Objective C switch statements and named integer constants
答案 0 :(得分:10)
错误expression is not an integer constant expression
意味着它所说的内容:在case
中,值必须是常量,而不是变量。
您可以将switch
上方的声明更改为常量:
const int match1=0;
const int match2=1;
或者您可以使用枚举。或#define
。但是你不能在那里使用非常数变量。
答案 1 :(得分:6)
如果您想要标记案例,则需要ENUM类型
typedef NS_ENUM(int, MyEnum) {
match1 = 0,
match2 = 1
};
- (void)switchCondn:(MyEnum)expression {
switch (expression)
{
case match1:
//statements
break;
case match2:
//statements
break;
default:
// statements
break;
}
}