How to create an Enumeration (enum)

An Enumeration (enum) allows you to create a collection of custom values. These can be more meaningful than simply using numbers.

Imagine you want to track drink sizes, such as small, medium and large. You can remember to just use the numbers 1, 2 and 3 for each size – but Enumeration makes it easier to declare those.

// create an enumeration
        enum drinkSize {
            smallDrink = 1,
            mediumDrink = 50,
            largeDrink = 100
        };
        
        // declare a variable from my enumeration set
        enum drinkSize myDrink = largeDrink;
        
        // compare against my own values
        if (myDrink == largeDrink) {
            NSLog(@"That's my drink!");
        }
        
        // an enum behaves like an integer
        NSLog(@"My Drink Size is %i", myDrink);

Notice the last line: when written in a string like a log message, Objective-C will track your enumeration’s numeric values instead. In my case, the log message would display “My Drink Size is 100”.





Leave a Reply