How to limit visibility of enum values in Objective C?

假如想象 提交于 2019-12-10 12:23:43

问题


In Objective C, when you define an enum, all of the enum values are visible everywhere and clog the global namespace.

I would like to make it Java-style and enforce that enums are only accessible thru the enum type name, e.g. with

typedef enum
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, NUM_OF
} Day;

I want to make sure that simply calling MONDAY produces compilation error or at least warning, and the only way to access the enum value were something like Day.MONDAY or Day::MONDAY or [Day MONDAY] or...

In Java I either use Enums or Interfaces, but is this doable in Objective-C?

If not, then I'd have to name all enums like this: DAY_MONDAY, DAY_TUESDAY... to make them easier to seach in auto-completion pop-up.


回答1:


It's just a workaround, but you can create a custom interface with a number of class methods (so that there's no need to create an instance), where each method represent a constant.

This way constants will be accessible only as you asked (ie. Day.MONDAY or [Day MONDAY]).



来源:https://stackoverflow.com/questions/7388997/how-to-limit-visibility-of-enum-values-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!