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″.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.