Enums in Objective-C

Our code example demonstrates the use of enumerated types in a program. Here’s how it works in Objective-C.

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, ServerState) {
    StateIdle,
    StateConnected,
    StateError,
    StateRetrying
};

NSString *ServerStateString(ServerState state) {
    switch (state) {
        case StateIdle:
            return @"idle";
        case StateConnected:
            return @"connected";
        case StateError:
            return @"error";
        case StateRetrying:
            return @"retrying";
        default:
            [NSException raise:NSGenericException format:@"Unexpected ServerState."];
            return @"";
    }
}

ServerState transition(ServerState state) {
    switch (state) {
        case StateIdle:
            return StateConnected;
        case StateConnected:
        case StateRetrying:
            // Implement conditions to determine next state here
            return StateIdle;
        case StateError:
            return StateError;
        default:
            [NSException raise:NSGenericException format:@"Unknown state: %ld", (long)state];
    }
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        ServerState state = StateIdle;
        NSLog(@"%@", ServerStateString(state));

        state = transition(state);
        NSLog(@"%@", ServerStateString(state));

        state = transition(state);
        NSLog(@"%@", ServerStateString(state));
    }
    return 0;
}

To run the program:

  1. Save the code in a file named enums.m.
  2. Compile the program using clang or gcc.
$ clang -fobjc-arc -framework Foundation enums.m -o enums
$ ./enums
idle
connected
idle

The NS_ENUM macro defines the ServerState enum type with underlying NSInteger values. We also define a helper function ServerStateString to convert enum values to readable strings.

The transition function replicates state transitions for a server. It takes the current state and returns a new state based on predefined rules. If the state is unknown, it raises an exception.

Now that we’ve seen how to implement and use enums in Objective-C, we can look at more advanced topics in the language.