简体   繁体   中英

enum Not Type Checked by Compiler?

With these enums...

typedef enum {
    ThisThingA = 0,
    ThisThingB = 1
} ThisThing;

typedef enum {
    ThatThingX = 8,
    ThatThingY = 9
} ThatThing;

and these properties...

@property (nonatomic) ThisThing thisThing;
@property (nonatomic) ThatThing thatThing;

I can do this...

self.thisThing = thatThingX;

and I don't get a warning from the compiler, which I would expect. Why is there no warning from the compiler? Why can I assign something that is of type ThatThing to something that is of type ThisThing?

EDIT as per the answer from Martin R: But if I do this...

[self setThisThing:thatThingX];

I get the warning: Implicit conversion from enumeration type 'ThatThing' to different enumeration type 'ThisThing'

(Xcode 4.6.3 and iOS 6.0)

The compiler option "Implicit Enum Conversions (-Wenum-conversion)" is by default on, and you actually get a warning if you assign to a variable of different enum type:

ThisThing x = ThatThingX;

or if you use the setter method to set the property:

[self setThisThing:ThatThingX];

In both cases you get the warning

implicit conversion from enumeration type 'ThatThing' to different enumeration type 'ThisThing' [-Wenum-conversion]

Only when you use the "dot" syntax to set the value

self.thisThing = ThatThingX;

then you don't get a warning, so this could be a bug in the compiler.

enum is C construct that is an integer type. It is type checked. Your usage is the same default integer type so there is nothing wrong in the eyes of the compiler or at all. Your usage is int.

If you typedef int as Bob and again as Josephine, that is a convenience for code clarity. Bob and Josephine are still the same type int.

If you declare two enums but one uses NSUInteger and the other uses NSInteger you could get a warning depending on your settings for implicit conversion.

This is really a C question.

Actually enum options are treated as NSInteger. So thatThingX has the value of 0 by default. When you assign self.thisThing = thatThingX; self.thisThing got the value of 0. So it will become ThisThingA . That's why there are no warnings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM