Is it possible in Objective-C to see if a int
value is in a particular enum
? For instance, in this enum:
enum {
ValidationLoginFailed = 2000,
ValidationSessionTokenExpired = 2001,
ValidationSessionTokenInvalid = 2002,
ValidationEmailNotFound = 2003
};
typedef int ValidationStatusCodes;
is it possible to see if an arbitrary integer value is in the ValidationStatusCodes
enum
?
[ValidationStatusCodes contains:intResponseCode]
or at least
[self intIsInRangeofEnum:ValidationStatusCodes forValue:intResponseCode]
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
typedef enum declaration in Objective-C A enum declares a set of ordered values - the typedef just adds a handy name to this. The 1st element is 0 etc. typedef enum { Monday=1, Tuesday, Wednesday } WORKDAYS; WORKDAYS today = Monday;//value 1.
There's no simpler way than just doing
(ValidationLoginFailed == intResponseCode ||
ValidationSessionTokenExpired == intResponseCode ||
ValidationSessionTokenInvalid == intResponseCode ||
ValidationEmailNotFound == intResponseCode)
In general, C is not very helpful for doing dynamic things or reflecting on types, and enums are a C feature.
Not with an enum
. An enum
is not an objective-C object, so you can't send it messages as you're doing.
Maybe use an NSDictionary?
This question is a little dated, but the standard I have seen in software design is to use a bitmask where each of these values is a discrete state with a bit-shift. In some cases, your enum values can be combinations of other values.
enum {
ValidationLoginFailed = 0, //0
ValidationSessionTokenExpired = 1 << 0, //1
ValidationSessionTokenInvalid = 1 << 1, //2
ValidationEmailNotFound = 1 << 2 //4
};
typedef int ValidationStatusCodes;
For your use-case you would &
your result with all of the items in the set:
int allStates = (ValidationLoginFailed | ValidationSessionTokenExpired |
ValidationSessionTokenInvalid | ValidationEmailNotFound); //7
if(val & allStates){
//some logic here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With