Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40255

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?

Upvotes: 1

Views: 272

Answers (1)

DonMag
DonMag

Reputation: 77690

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;
}

Upvotes: 2

Related Questions