ArdenDev
ArdenDev

Reputation: 4191

Warn against BOOL to ENUM conversion in XCode

Previously I had a method that does some task which takes in a BOOL.

-(void)processUserBasedonStatus:(BOOL)newUser

I then defined an NS_ENUM to accept more states like this

typedef NS_ENUM(NSInteger, Status)
{
    StatusNewUser=0,
    StatusCurrentUser,
    StatusOldUser,
    StatusOther
};

And updated the method to use the new ENUM param

-(void)processUserBasedonStatus:(Status)userStatus

Everything works well, except that Xcode didn't complain about some places where I forgot to update the calling method, i.e.

[self processUserBasedonStatus:YES];
[self processUserBasedonStatus:NO];

In this case, YES & NO will only map to the top 2 values of the ENUM. I experimented with the list of warnings in Xcode but nothing allows the compiler to bring up this warning.

Is there a way to enable the compiler to warn us about this type of behavior?

Upvotes: 0

Views: 220

Answers (1)

CRD
CRD

Reputation: 53010

In (Objective-)C the types _Bool, char, int, long et al and their unsigned counterparts are all integer types. Types defined by enum are not distinct types per se but a collection of constants of their underlying integer type.

The Objective-C type BOOL is either a synonym (typedef or #define) for _Bool or one of the char types, depending on the version of the compiler.

Due to integer promotions and integer conversions many assignments between different integer types are automatic and silent. Even floating point types can get involved, e.g.:

bool b = true;
float f = b;

is perfectly legal and might well go uncommented by a compiler even as a warning.

Given all this the answer to your question:

Is there a way to enable the compiler to warn us about this type of behaviour?

is currently it seems “no” – the code is perfectly legal in (Objective-)C. It is however dubious and could indicate an error and there is nothing stopping the compiler issuing a warning as it does for some other legal but dubious constructs. You could submit a report to Apple at bugreport.apple.com (you need an Apple ID to do this) suggesting they add such a warning.

Upvotes: 1

Related Questions