isaac
isaac

Reputation: 4897

Evaluate if int matches a defined enum type

I have an enum typedef containing several type definitions, eg:

ActionTypeSomething = 1,
ActionTypeSomethingElse = 2

And so on.

So a method I've written evaluates a passed int and then returns a value (for example, a string) accordingly.

(NSString *)evaluatAndReturnProperResult:(int)typeID

NSString *repsonseString;

switch (typeID) 
    case actionTypeSomething: {
        responseString = @"an appropriate string for typeID"
    }
...

return responseString;

So my switch evaluates each supported type and returns the correct string.

Now for my question:

I only want to return strings for supported types (i.e., in theory any integer could be passed). If there's no match, I return nil.

Obviously I can do this using exactly the method I already have. But could I (in theory) improve performance by evaluating the passed int to see if it matches any of my defined enum types BEFORE I send it through switch (the switch isn't massive, but I'd still rather just return nil at the beginning of the method if I know there's not going to be a match).

I'm sure this is easy, could someone suggest how to evaluate if my passed integer matches any define enum ActionType before I enter the switch? In this case I'm probably prematurely optimizing, but it's more of a general question about how to do achieve it (not if I should).

Upvotes: 0

Views: 2035

Answers (3)

Igor Kulagin
Igor Kulagin

Reputation: 1771

You can define 2 more enum values:

typedef enum {
    ActionTypeMin = 1,
    ActionTypeSomething = 1,
    ActionTypeSomethingElse = 2,
    ActionTypeMax = 2
} ActionType;

Then check:

typeID >= ActionTypeMin && typeID <= ActionTypeMax

Upvotes: 2

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

You are using a TypeDef that's to limit ActionEnum to a set of values, so you shouldn't be using int in your program except for up or downstream communication. Some would say not even then and that you should recive a string and map it to the enum and vice versa.

In terms of getting your strings the usual optimsatiin is Have an array of strings from ActionType1 to ActionTypeN. Use the enum as the index to look it up from the array.

The array will also give you the doings to map the string to the enum.

A simple if statement of the enum cast as an integer against teh bound of the array will let you deal gracefully with a bad value, though to me that should throw a big blaring exception.

Upvotes: 1

jrturton
jrturton

Reputation: 119242

The argument for your method shouldn't be an int, it should ideally be the enum you have defined. This gives you some compile time checking.

If this is not possible then your default case in the switch will handle it just fine - that's what they are designed for.

Upvotes: 1

Related Questions