Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 339
Ky. Avatar asked Sep 03 '15 21:09

Ky.


3 Answers

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.)

like image 80
andyvn22 Avatar answered Nov 09 '22 15:11

andyvn22


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.

like image 5
Candost Avatar answered Nov 09 '22 14:11

Candost


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.

like image 1
Daniel Saidi Avatar answered Nov 09 '22 13:11

Daniel Saidi