Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

How to avoid if else or switch case whe dealing with enums?

I have a member variable that tells units for a value I have measured like centimeters,kilometers,seconds,hours etc.

Now these are enums, When I display a corresponding string, I have created a method that returns corresponding string for these enums.

Unlike Java, enums here cant have other properties associated with them.

So I have to explicitly do a if-else-if chain or a switch case to return the correct string.

I am new to Objective C. any good practice that I should be following in such scenarios ?

Upvotes: 0

Views: 356

Answers (3)

DRVic
DRVic

Reputation: 2491

Martin James's comment is the right answer. And use a definition of the enum like:

enum units { cm = 0, m, km };

that way you can be sure that your enum translates to the correct index values.

Upvotes: 0

Mike Weller
Mike Weller

Reputation: 45598

I guess if your enum values started at 0 and increased you could use some sort of array access:

const char *distanceUnitToString2(enum DistanceUnit unit)
{
    const char *values[] = {
            "cm",
            "m",
            "km"
    };

    // do some sanity checking here
    // ...

    return values[unit];
}

But this feels a little flaky to me. What if you have negative values, or you are using bitmask-style enum values like 1 << 8? You are going to end up using a very large array.

You also could use a switch and improve it a little with a macro. Something like this:

const char *distanceUnitToString(enum DistanceUnit unit)
{
#define CASE(UNIT, STRING) case (UNIT): return (STRING)
    switch (unit) {
            CASE(kCentimeters, "cm");
            CASE(kMeters, "m");
            CASE(kKiloMeters, "km");

        default:
            // should not get here
            assert(0);
            break;
    }
#undef CASE
}

But you don't really save that much vs. not using the macro.

Upvotes: 0

Oofpez
Oofpez

Reputation: 514

afaik Objective-C enums are just old-school C enums... so maybe you can use an integer value for them?

Upvotes: 1

Related Questions