Tag Archives: enum

How to create your own Data Type using typedef

With typedef you can specify custom variable types. Instead of having a variable such as int, you could create your own – such as yourInt:

Now you have your own variable type called youInt which behaves just like an int.

The power of typedef becomes clearer when combined with enumerations we were discussing previously. You can create your own data type of enum, creating and addressing your values more easily. Let’s stick with the drink size example from earlier:

Xcode will code complete all available values, making your life a bit easier when coding.

Many of Apple’s pre-defined super long complex types are created this way. Think of all those NSDateFormatter values you can use, such as NSDateFormatterStyleLongStyle.

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.

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