TExcelTAD
Home › Objective-C › Enums & Option Sets

Enums & Option Sets

An enumeration gives names to a fixed set of integer values. Objective-C uses C enums, declared through two Foundation macros that specify the underlying type and make the enum import nicely into Swift:

Macro For Values
NS_ENUM exactly one choice 0, 1, 2, …
NS_OPTIONS any combination of flags 1, 2, 4, 8, … (bits)

NS_ENUM

objc · try it yourself
#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, OrderStatus) {
    OrderStatusPending,        // 0
    OrderStatusPaid,           // 1
    OrderStatusShipped,        // 2
    OrderStatusDelivered,      // 3
    OrderStatusCancelled = 99, // explicit value
};

NSString *StatusName(OrderStatus status) {
    switch (status) {
        case OrderStatusPending:   return @"pending";
        case OrderStatusPaid:      return @"paid";
        case OrderStatusShipped:   return @"shipped";
        case OrderStatusDelivered: return @"delivered";
        case OrderStatusCancelled: return @"cancelled";
    }
    return @"unknown";
}

int main(void) {
    @autoreleasepool {
        OrderStatus s = OrderStatusPaid;
        NSLog(@"status %ld = %@", (long)s, StatusName(s));

        s = OrderStatusShipped;
        if (s >= OrderStatusShipped && s != OrderStatusCancelled) {
            NSLog(@"%@: the parcel is on its way", StatusName(s));
        }
        NSLog(@"cancelled is %ld", (long)OrderStatusCancelled);
    }
    return 0;
}
status 1 = paid
shipped: the parcel is on its way
cancelled is 99

The convention is to prefix every case with the type name (OrderStatusPaid), because C enum constants share one global namespace. Swift strips the prefix: OrderStatus.paid.

Tip: Don't add a default: to a switch over an NS_ENUM. Without it, clang warns when you add a new case and forget to handle it somewhere.

Enums in classes and collections

Enums are C values, so they need boxing to go into collections:

objc · try it yourself
#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, Suit) { SuitClubs, SuitDiamonds, SuitHearts, SuitSpades };

@interface Card : NSObject
@property (nonatomic) Suit suit;
@property (nonatomic) NSInteger rank;
@end
@implementation Card
- (NSString *)description {
    NSArray *symbols = @[@"C", @"D", @"H", @"S"];
    NSArray *faces = @[@"", @"A", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"J", @"Q", @"K"];
    return [NSString stringWithFormat:@"%@%@", faces[self.rank], symbols[self.suit]];
}
- (BOOL)isRed {
    return self.suit == SuitDiamonds || self.suit == SuitHearts;
}
@end

int main(void) {
    @autoreleasepool {
        NSMutableArray *hand = [NSMutableArray array];
        NSInteger ranks[] = {1, 12, 7};
        Suit suits[] = {SuitSpades, SuitHearts, SuitDiamonds};
        for (int i = 0; i < 3; i++) {
            Card *c = [Card new];
            c.rank = ranks[i];
            c.suit = suits[i];
            [hand addObject:c];
        }
        for (Card *c in hand) {
            NSLog(@"%@ %@", c, [c isRed] ? @"red" : @"black");
        }

        NSDictionary *counts = @{@(SuitHearts): @5, @(SuitSpades): @2};   // boxed keys
        NSLog(@"hearts played: %@", counts[@(SuitHearts)]);
    }
    return 0;
}
AS black
QH red
7D red
hearts played: 5

NS_OPTIONS: bit flags

When several options can be on at once, each case gets its own bit (1 << n), and values are combined with | (bitwise OR):

objc · try it yourself
#import <Foundation/Foundation.h>

typedef NS_OPTIONS(NSUInteger, Permission) {
    PermissionNone    = 0,
    PermissionRead    = 1 << 0,   // 1
    PermissionWrite   = 1 << 1,   // 2
    PermissionExecute = 1 << 2,   // 4
    PermissionShare   = 1 << 3,   // 8
};

NSString *Describe(Permission p) {
    if (p == PermissionNone) return @"none";
    NSMutableArray *parts = [NSMutableArray array];
    if (p & PermissionRead)    [parts addObject:@"read"];
    if (p & PermissionWrite)   [parts addObject:@"write"];
    if (p & PermissionExecute) [parts addObject:@"execute"];
    if (p & PermissionShare)   [parts addObject:@"share"];
    return [parts componentsJoinedByString:@"+"];
}

int main(void) {
    @autoreleasepool {
        Permission editor = PermissionRead | PermissionWrite;
        NSLog(@"editor = %lu (%@)", (unsigned long)editor, Describe(editor));

        editor |= PermissionShare;                 // add a flag
        NSLog(@"after adding share: %@", Describe(editor));

        editor &= ~PermissionWrite;                // remove a flag
        NSLog(@"after removing write: %@", Describe(editor));

        BOOL canRead = (editor & PermissionRead) != 0;
        NSLog(@"can read? %d", canRead);
        NSLog(@"guest: %@", Describe(PermissionNone));
    }
    return 0;
}
editor = 3 (read+write)
after adding share: read+write+share
after removing write: read+share
can read? 1
guest: none
Operation Code
combine a | b
add flags |= PermissionShare
remove flags &= ~PermissionWrite
test (flags & PermissionRead) != 0
test several (flags & (A | B)) == (A | B)

Swift imports an NS_OPTIONS type as an OptionSet: let p: Permission = [.read, .write].

String-backed "enums"

For values that must be strings (dictionary keys, notification names), Apple uses typed string constants:

objc
typedef NSString *ThemeName NS_TYPED_ENUM;
static ThemeName const ThemeNameLight = @"light";
static ThemeName const ThemeNameDark  = @"dark";

In Swift these become a struct with static members, ThemeName.light. NS_TYPED_ENUM comes from Apple's headers; GNUstep's Foundation doesn't define it, so this snippet is shown without running.

Test yourself

Which macro should you use for values that can be combined, like permissions?

  1. NS_ENUM
  2. NS_OPTIONS
  3. #define
  4. NS_STRING_ENUM

How do you test whether flags contains PermissionWrite?

  1. flags == PermissionWrite
  2. (flags & PermissionWrite) != 0
  3. flags | PermissionWrite
  4. flags > PermissionWrite

Why avoid default: in a switch over an NS_ENUM?

  1. It's a syntax error
  2. So the compiler warns about unhandled new cases
  3. It's slower
  4. Swift doesn't allow it