Cyril
Cyril

Reputation: 2818

Switch statement on Objective-C not working

I just learned how to use switch statements and I'm trying to implement it on my project but won't work.

int x;
    x = arc4random()%5;

    switch (x) {
        case '0':
            NSLog(@"0");

            break;
        case '1':
            NSLog(@"1");

            break;
        case '2':
            NSLog(@"2");
            break;
        case '3':
            NSLog(@"3");

            break;
        case '4':
            NSLog(@"4");

            break;

        default:

            break;
    }

This is my line of code and I looked at multiple examples and I don't see anything wrong with my code.

I assume that it has something to do with it being inside the viewDidLoad because that is the only thing thats different between the examples I looked at and my code.

Upvotes: 0

Views: 205

Answers (2)

karateman10998
karateman10998

Reputation: 322

Take out the apostrophes and it should work properly. Adding apostrophes like case '0': makes it test for string inputs. Writing it like case 0: will make it test for integer inputs.

Upvotes: 1

Eiko
Eiko

Reputation: 25632

You are testing against characters, not integer values.

You need to use case 0, case 1 etc. without the quotes.

Upvotes: 6

Related Questions