typestar

NS_ENUM in Objective-C

Enums with a fixed underlying type, switched exhaustively.

#import <Foundation/Foundation.h>

// NS_ENUM ties an enum to a fixed underlying type.
typedef NS_ENUM(NSInteger, VinylGrade) {
    VinylGradeMint,
    VinylGradeNearMint,
    VinylGradeVeryGood,
    VinylGradeGood,
};

static NSString *gradeLabel(VinylGrade grade) {
    switch (grade) {
        case VinylGradeMint:     return @"M";
        case VinylGradeNearMint: return @"NM";
        case VinylGradeVeryGood: return @"VG";
        case VinylGradeGood:     return @"G";
    }
    return @"?";
}

int main(void) {
    @autoreleasepool {
        NSLog(@"Grades: %@ then %@", gradeLabel(VinylGradeNearMint),
              gradeLabel(VinylGradeGood));
    }
    return 0;
}

How it works

  1. NS_ENUM(NSInteger, VinylGrade) ties the enum to its width.
  2. Cases follow the ClassPrefixCase naming convention.
  3. A switch over every case needs no default to satisfy -Wall.

Keywords and builtins used here

The run, in numbers

Lines
27
Characters to type
580
Tokens
106
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 98 seconds.

Type this snippet

Step 3 of 3 in C interop, step 24 of 27 in Language basics.

← Previous Next →