JREnum
JREnum copied to clipboard
Enums with prefixes, additional to string conversion method
I was looking for a nice web service string enums workaround, and the best way so far was dealing with an enum and an array/dictionary. For example, there's an abstract service makeUpName
, it has parameter age
, which is supposed to be one of strings: "Young", "Old", "Ancient". The old way is something like described here: http://stackoverflow.com/questions/1242914/converting-between-c-enum-and-xml or here: http://stackoverflow.com/questions/6331762/enum-values-to-nsstring-ios.
The idea is to declare enum using JREnum, where all the enum elements have prefix equal to enum name, like:
JREnum(makeUpNameAge,
makeUpNameAgeYoung,
makeUpNameAgeOld,
makeUpNameAgeAncient);
And then, provide a function (makeUpNameAgeToStringCutPrefix() in my implementation), which could get enum element string representation without prefix, for example:
makeUpNameAgeYoung
=> Young
makeUpNameAgeOld
=> Old
etc. Wonder if some underscore additions could be implemented as well (prefix_enumName).
This approach is less verbose and reasonable if string constants don't change often. Autocomplete completes prefixes when enum elements are defined (didn't manage to create enum elements with prefix automatically, so one will have to type them by hand). Downside is that spaces are not supported and if string constants are often changed, the whole project has to be refactored (which is easy via XCode's rename feature).
I'm going to experiment with this for a while, what do you think?