IMustCode
IMustCode

Reputation: 109

error when initializing enum value

Below is the enum I created in the header file of my Ball class:

typedef enum   {
redBall = 0,
blueBall = 1,
greenBall = 2

}ballTypes;

and in the interface:

ballTypes ballType;

in the init method of Ball.mm I initialized ballType as follows:

ballType = 0;

I get the following error:

Assigning to 'ballTypes' from incompatible type 'int'

How can I solve this?

Upvotes: 3

Views: 2067

Answers (2)

jszumski
jszumski

Reputation: 7416

Enums should be defined with the NS_ENUM macro:

typedef NS_ENUM(NSInteger, BallType) {
    BallTypeNone  = 0,
    BallTypeRed   = 1,
    BallTypeBlue  = 2,
    BallTypeGreen = 3
};

BallType ballType;

ballType = BallTypeNone;

Typically the name starts with a capital letter and each value is the name with a meaningful description appended to it.

Upvotes: 3

trojanfoe
trojanfoe

Reputation: 122381

BallTypes is a type and int (literal 0) is a type and they cannot be mixed without casting.

Create an invalid ball type and use that:

typedef enum   {
    noBall,
    redBall,
    blueBall,
    greenBall
} ballTypes;

...

ballType = noBall;

Note: Conventionally enums are capitialized...

Upvotes: 1

Related Questions