简体   繁体   中英

How to check multiple Switch case value in Objective-C?

In Swift it is possible to check a tuple like,

switch(type1, type2) {
    case (1, 1):
        functionNormal()
    case (1, 2):
        functionUncommon()
    case (1, 3):
        functionRare()
    ...
}

Is it possible to check tuple like multiple values in Objective-C Switch case? Any way around?

There could be various approaches, depending on exactly what your type1 and type2 data might be.

However, here is a basic example:

NSInteger i = 1;
NSInteger j = 2;

switch (i) {
    case 1:
        switch (j) {
            case 1:
                [self functionNormal];
                break;

            case 2:
                [self functionUncommon];
                break;

            case 3:
                [self functionRare];
                break;

            default:
                NSLog(@"first value: 1 ... missing case for second value: for %ld", (long)j);
                break;
        }
        break;

    case 2:
        switch (j) {
            case 1:
                [self secondFunctionNormal];
                break;

            case 2:
                [self secondFunctionUncommon];
                break;

            case 3:
                [self secondFunctionRare];
                break;

            default:
                NSLog(@"first value: 2 ... missing case for second value: %ld", (long)j);
                break;
        }
        break;

    default:
        NSLog(@"missing first case for first value: %ld", (long)i);
        break;
}

This is rather inefficient, of course, but maybe it can get you on your way.


Edit

Again, it will depend on your data, but another approach more closely resembling your Swift example:

NSInteger i = 1;
NSInteger j = 2;

NSInteger ij = i * 1000 + j;

switch (ij) {
    case 1001:
        [self functionNormal];
        break;

    case 1002:
        [self functionUncommon];
        break;

    case 1003:
        [self functionRare];
        break;

    case 2001:
        [self secondFunctionNormal];
        break;

    case 2002:
        [self secondFunctionUncommon];
        break;

    case 2003:
        [self secondFunctionRare];
        break;

    default:
        NSLog(@"case was something else: %ld", (long)ij);
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM