简体   繁体   中英

NS_ENUM gives compiler warning about forward references

Im using the spiffy new NS_ENUM to try and define an enum in my objective-c iOS project.

I'm declaring the NS_ENUM in the header of a class like so:

NS_ENUM(int, SomeEnumType){
    SomeEnumType1,
    SomeEnumType2,
    SomeEnumType3,
    SomeEnumType4
};

@interface Issue : NSObject
....

And im getting the compiler warning:

ISO C forbids forward references to 'enum' types

Now if i define the enum the (slightly) older traditional way like so:

typedef enum{
    SomeEnumType1,
    SomeEnumType2,
    SomeEnumType3,
    SomeEnumType4
}SomeEnumType;

@interface Issue : NSObject
....

in exactly the same place in the code the issue goes away. What am i doing wrong with NS_ENUM?

EDIT:

I corrected it by adding the typedef but its still giving a warning.

I have turned on the pedantic compiler warnings. Is this just a case where its being too pedantic or is there a correct way that im missing?

Try:

typedef NS_ENUM(int, SomeEnumType){
    SomeEnumType1,
    SomeEnumType2,
    SomeEnumType3,
    SomeEnumType4
};

NS_ENUM won't do the typedef for you to declare the SomeEnumType type, you have to do it yourself.

Update: The reason why the warning shows up is due to the implementation of NS_ENUM. Let's see what it tries to do:

#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type

The problem line (I believe) is this:

enum _name : _type _name;

This is performing a forward declaration within the macro itself. Hence, with pedantic warnings, it's flagging the use of this up.

The pedantic warning is simply stating if you wanted to transition this to pure C, it would not be portable as it does not follow the standardisation of no forward declarations of enums. Within the realm of Xcode, Clang and LLVM (and the fact NS_ENUM is provided by Apple), you should be pretty safe.

You missed off the typedef :

typedef NS_ENUM(int, SomeEnumType){
    SomeEnumType1,
    SomeEnumType2,
    SomeEnumType3,
    SomeEnumType4
};

You mentioned that you're using pedantic warnings. The compiler is correct: the fixed-type enums are part of the C++ standard , not ISO C.

As others have pointed out, the pedantic warning is correct. However, you don't have to use the NS_ENUM macro to take advantage of strictly typed enums. Just declare your enum like this and the warning will go away while you retain the strict typing:

typedef enum : int {
    SomeEnumType1,
    SomeEnumType2,
    SomeEnumType3,
    SomeEnumType4
} SomeEnumType;

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