How to create your own Data Type using typedef

- by

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.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.