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:

// create a typedef of int
        typedef int yourInt;
        yourInt yourValue = 57;
        
        NSLog(@"Your value is %i", yourValue);

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:

// create a typedef of enum drinkSize
        typedef enum drinkSize {
            smallDrink = 1,
            mediumDrink = 50,
            largeDrink = 100
        } drinkSize;
        
        // declare a variable from my typedef enumeration set
        drinkSize myDrink = largeDrink;
        drinkSize juliasDrink = smallDrink;

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.





Leave a Reply