Ryuk
Ryuk

Reputation: 95

Custom Enums - Unknown Type

Moving on with my game a bit I want to add difficulties etc.

Coming to Objective-C from C#, I was hoping I could have some enums like this

typedef enum GameTypes{
    Classic = 0,
    Unlimited,
    Timed,
    Expert,
} GameType;

typedef enum GameDifficultys
{
    Easy = 0,
    Medium,
    Hard,
} GameDifficulty;

and then have something like this:

GameType gameType = GameTypes.Classic;
GameDifficulty gameDifficulty = GameDifficultys.Easy;

However I get this following error:

Unknown type name "GameType"/"GameDifficulty"

Is this possible like it is in C#?

Thanks

Upvotes: 1

Views: 2059

Answers (2)

Wolfgang Schreurs
Wolfgang Schreurs

Reputation: 11834

You seem to have defined the enums wrong. In C the following seems to be the convention:

typedef enum {
    Classic = 0,
    Unlimited,
    Timed,
    Expert,
} GameTypes;

typedef enum
{
    Easy = 0,
    Medium,
    Hard,
} GameDifficulties;

Even so, I'd stick with Apple's naming conventions when using enums in Objective-C, which would result in something like:

typedef enum {
    GameTypeClassic = 0,
    GameTypeUnlimited,
    GameTypeTimed,
    GameTypeExpert,
} GameType;

typedef enum
{
    GameDifficultyEasy = 0,
    GameDifficultyMedium,
    GameDifficultyHard,
} GameDifficulty;

Now you'll be able to assign values like this:

GameType gameType = GameTypeClassic;
GameDifficulty gameDifficulty = GameDifficultyEasy;

Check how enums are defined in UITableView.h for comparison: https://github.com/enormego/UIKit/blob/master/UITableView.h

Upvotes: 2

Jody Hagins
Jody Hagins

Reputation: 28409

C# is one of the worst things to ever happen to C.

Your question has nothing to do with Objective-C, it's a plain C question.

typedef enum GameTypes{
    Classic = 0,
    Unlimited,
    Timed,
    Expert,
} GameType;

That code does several things (of which I will only describe the easy ones). First, it declares an enumeration type, which can be used as enum GameTypes. For example:

enum GameTypes gameType = Classic;

Second, it puts those 4 names into the global namespace, such that Classic, Unlimited, Timed, and Expert can be used, and must not be duplicated as symbols.

Third, it creates a type alias called GameType which can be used as an alias for enum GameTypes.

So, for your specific example, you should not differentiate enum GameTypes and GameType. Instead, you should probably do something like this:

typedef enum GameType {
    GameTypeClassic = 0,
    GameTypeUnlimited,
    GameTypeTimed,
    GameTypeExpert,
} GameType;

typedef enum GameDifficulty
{
    GameDifficultyEasy = 0,
    GameDifficultyMedium,
    GameDifficultyHard,
} GameDifficulty;

and then...

GameType gameType = GameTypeClassic;
GameDifficulty gameDifficulty = GameDifficultyEasy;

Also, you do not have to assign the first element as 0 because the first element of an enumeration will always get 0 unless it is explicitly overridden.

Upvotes: 2

Related Questions