Ky -
Ky -

Reputation: 32143

Can I add methods to an Objective-C enum?

In Java, I have an enum like:

public enum Toppings {
  PEPPERONI,
  EXTRA_CHEESE,
  SECRET_SAUCE;

  @Override
  public String toString() {
    switch(this) {
      case EXTRA_CHEESE: return "Extra Cheese";
      case SECRET_SAUCE: return "Secret Sauce™";
    }
    String name = name();
    return name.charAt(0) + name.substring(1, name.length()).replace('_', ' ').toLowerCase();
  }
}

I want to re-made this in Objective-C. So far, I've done this:

NS_ENUM(NSInteger, Toppings) {
  PEPPERONI,
  EXTRA_CHEESE,
  SECRET_SAUCE
};

And then I was stumped. How would I make the toString() method? I know it's rather complex and uses some Java-specific behaviors, but I'm sure there's a way.

The only thing that comes to mind is to have a separate helper class with this functionality, but that seems a bit much, doesn't it?

Upvotes: 7

Views: 8084

Answers (4)

Abhishek Bhardwaj
Abhishek Bhardwaj

Reputation: 98

No, there is no way to declare a method in an enum using Objective-C. However, you can use an enum as a parameter to any method. This might be a solution for you:

typedef NS_ENUM(int, PatientActivity)
{
    Exercise = 101,
    Smoke,
    Alcohol
};

 - (void)getPatientDetail:(NSString *)PatID withActivity:(enum PatientActivity) activity;

Upvotes: 0

Candost
Candost

Reputation: 1029

NSString * const ToppingsList[] = {
    [PEPPERONI] = @"Pepperoni",
    [EXTRA_CHEESE] = @"Extra Cheese",
    [SECRET_SAUCE] = @"Secret Sauce",
};
NSLog("Topping: %@", ToppingList[PEPPERONI]);

After declaring your enum, you can add this to use type string. It seems like toString() method

EDIT: Meanwhile @andyvn22 is right. There is no way to add methods to enums in Objective-C. I just gave a solution for using enums with string.

Upvotes: 5

andyvn22
andyvn22

Reputation: 14824

Unfortunately, there is no way to add methods to an Objective-C enum. (Sidenote: you can add methods to a Swift enum.)

Traditionally, a standalone function would be used for this purpose, with a body similar to your Java method:

NSString* NSStringFromToppings(Toppings toppings)
{
    switch (toppings)
    {
        case PEPPERONI: return @"Pepperoni";
        case EXTRA_CHEESE: return @"Extra Cheese";
        case SECRET_SAUCE: return @"Secret Sauce";
    }
}

(Sidenote: you should name your enum Topping instead of Toppings--you can see how the code above would be clearer with a singular type name. You should also add a two- or three-letter prefix to all your type names (and this function) to avoid naming collisions.)

Upvotes: 21

Daniel Saidi
Daniel Saidi

Reputation: 6187

Yeah, it's not as straightforward as in, say, Java or .NET. However, I think that option 2 of yar1vn's answer looks ok:

Convert objective-c typedef to its string equivalent

You could also add enum serialization as an NSString extension, making it possible to ask NSString to give you a string based on your enum.

Upvotes: 1

Related Questions