Switch in Objective-C

Switch statements express conditionals across many branches.

Here’s a basic switch.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int i = 2;
        NSLog(@"Write %d as ", i);
        switch (i) {
            case 1:
                NSLog(@"one");
                break;
            case 2:
                NSLog(@"two");
                break;
            case 3:
                NSLog(@"three");
                break;
            default:
                NSLog(@"unknown");
                break;
        }

        // Using switch with multiple expressions and default case.
        NSDate *now = [NSDate date];
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSInteger weekday = [calendar component:NSCalendarUnitWeekday fromDate:now];
        
        switch (weekday) {
            case 7: // Saturday
            case 1: // Sunday
                NSLog(@"It's the weekend");;
                break;
            default:
                NSLog(@"It's a weekday");
                break;
        }

        // Switch without an expression and non-constant case values.
        NSDateComponents *components = [calendar components:NSCalendarUnitHour fromDate:now];
        NSInteger hour = [components hour];
        
        switch (hour) {
            case 0 ... 11:
                NSLog(@"It's before noon");
                break;
            default:
                NSLog(@"It's after noon");
                break;
        }

        // Type switch example using Objective-C type checking.
        id elements[] = { @(YES), @(1), @"hey" };
        
        for (int i = 0; i < 3; i++) {
            id element = elements[i];

            if ([element isKindOfClass:[NSNumber class]]) {
                NSNumber *number = (NSNumber *)element;
                if (strcmp([number objCType], @encode(BOOL)) == 0) {
                    NSLog(@"I'm a BOOL");
                } else {
                    NSLog(@"I'm an int");
                }
            } else if ([element isKindOfClass:[NSString class]]) {
                NSLog(@"Don't know type %@", NSStringFromClass([element class]));
            } else {
                NSLog(@"Unknown type");
            }
        }
    }
    return 0;
}

To run the program, save the code in a file named main.m and then compile and execute it using clang and ./.

$ clang -fobjc-arc -framework Foundation main.m -o main
$ ./main

Output:

Write 2 as 
two
It's a weekday
It's after noon
I'm a BOOL
I'm an int
Don't know type __NSCFConstantString

Now that we can run and build basic Objective-C programs, let’s learn more about the language.