如何在代码中减少if else条件?

时间:2014-12-08 09:06:39

标签: ios objective-c ios8

我是iOS的新手,我想删除if else条件并使用适当的代码来实现以下代码.. 谁可以帮我这个?

我有很多条件

if (B == 99)
{
    B = 11;
    [Search_color addObject:Z];
}else if(B == 4)
{
    B = 1;
    [Search_color addObject:D];
}else if (B == 5)
{
    B = 2;
    [Search_color addObject:E];
}else if (A == 14)
{
    B = 11; A = 10;
    [Search_color addObject:N];
    [Search_color addObject:Z];

}
else if (B == 26)
{
    B = 11;
    [Search_color addObject:Z];
}

1 个答案:

答案 0 :(得分:2)

可以使用相同结果的开关:

switch (B) {
    case 99:
        B = 11;
        //[Search_color addObject:Z];
        break;
    case 4:
        B = 1;
        //[Search_color addObject:D];
        break;
    case 5:
        B = 2;
        //[Search_color addObject:E];
        break;
    case 26:
        if (A != 14) {
        B = 11;
        //[Search_color addObject:Z];
        break;
        }
    default:
        if (A == 14) {
            B = 11; A = 10;
            //[Search_color addObject:N];
            //[Search_color addObject:Z];
        }
        break;
}

代码使用开关功能

- (void)yourFunction
{
    NSInteger B, A;
    B = 99;
    switch (B) {
        case 99:
            B = 11;
            //[Search_color addObject:Z];
            break;
        case 4:
            B = 1;
            //[Search_color addObject:D];
            break;
        case 5:
            B = 2;
            //[Search_color addObject:E];
            break;
        case 26:
            if (A != 14) {
                B = 11;
                //[Search_color addObject:Z];
                break;
            }
        default:
            if (A == 14) {
                B = 11; A = 10;
                //[Search_color addObject:N];
                //[Search_color addObject:Z];
            }
            break;
    }

    NSLog(@"B = %ld", B);
}

输出:B = 11。