在swich语句中使用变量作为大小写常量

时间:2015-12-18 19:45:19

标签: objective-c switch-statement

我正在尝试使用变量作为大小写匹配,但我得到“表达式不是Objective-C中的整数。

是否可以这种方式在开关中使用变量?

  int count = [array count];

    switch ([number to check]) {
        case 0:
            //first statement
            break;
        case 1 ... (count -1):
           //somewhere between 1 and the next to last statement
           //Basically the middle
            break;
        case count:
            //Last statement

        default:
            break;
    }

2 个答案:

答案 0 :(得分:2)

Objective-C(和C)switch仅支持每个case语句的单个基本常量值(或者由TwoStraws在答案中指出的范围)。使用if/else编写代码会好得多:

if ([number to check] == 0) {
} else if ([number to check] >= 1 && [number to check] < count) {
} else if ([number to check] == count) {
} else {
}

答案 1 :(得分:2)

Objective-C的switch语句确实支持您所见的值范围,但不支持我担心的变量匹配。

所以,下面的代码是有效的,因为我使用了精确整数:

int numberOfKittens = 12;
NSString *kittenDescription;

switch (numberOfKittens) {
    case 0 ... 5:
        kittenDescription = @"Need more kittens";
        break;

    case 6 ... 10:
        kittenDescription = @"That's a good number of kittens.";
        break;

    case 11 ... 20:
        kittenDescription = @"Are you sure you can handle that many kittens?";
        break;

    default:
        kittenDescription = @"You must really love kittens!";
}

...但是试图用变量代替其中任何变量都会失败。

如果这是您迫切需要的,请考虑使用Swift,因为它具有更具表现力的switch匹配系统。这是Swift中的相同代码,现在使用变量来匹配案例:

let upperLimit = 20
let numberOfKittens = 19
var kittenDescription = ""

switch (numberOfKittens) {
case 0 ... 5:
    kittenDescription = "Need more kittens"

case 6 ... 10:
    kittenDescription = "That's a good number of kittens."

case 11 ... upperLimit:
    kittenDescription = "Are you sure you can handle that many kittens?"

default:
    kittenDescription = "You must really love kittens!"
}