Created
November 5, 2016 03:12
-
-
Save wh1pch81n/f95d1674906d431698a6fc223709178e to your computer and use it in GitHub Desktop.
Using NS_STRING_ENUM can be verbose when used in objective c. Below is an example of how macros can be used to shorten it. These macros can be used and reused by cleverly defining and underlining macros.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//global macro helpers | |
#define DH_Str(I) #I | |
#define __DH_STRING_ENUM(PREFIX, SUFFIX, PREFIX2, SUFFIX2) \ | |
static PREFIX PREFIX##_##SUFFIX = @DH_Str(PREFIX2##SUFFIX2); | |
#define _DH_STRING_ENUM2(PREFIX, SUFFIX, VAL) \ | |
static PREFIX PREFIX##_##SUFFIX = VAL; | |
#define _DH_STRING_ENUM(T,I) \ | |
__DH_STRING_ENUM(T, I, T, I) | |
//------ file dependent | |
// the enum type shall be DHBlahKey | |
typedef NSString * DHBlahKey NS_STRING_ENUM; | |
#define DH_STRING_ENUM(I) \ | |
_DH_STRING_ENUM(DHBlahKey, I) | |
#define DH_STRING_ENUM2(I,J) \ | |
_DH_STRING_ENUM2(DHBlahKey, I, J) | |
// make swift objc enums | |
DH_STRING_ENUM(pop) | |
DH_STRING_ENUM2(crackel, @"To Snap") | |
// undef so same macro can be reused | |
#undef DH_STRING_ENUM | |
#undef DH_STRING_ENUM2 | |
///<<<-----new type | |
// the enum type shall be DHWowKey. Noticed how I only needed to modify these 3 lines | |
typedef NSString * DHWowKey NS_STRING_ENUM; | |
#define DH_STRING_ENUM(I) \ | |
_DH_STRING_ENUM(DHWowKey, I) | |
#define DH_STRING_ENUM2(I,J) \ | |
_DH_STRING_ENUM2(DHWowKey, I, J) | |
// make swift objc enums | |
DH_STRING_ENUM(pop) | |
DH_STRING_ENUM2(crackel, @"To Snap") | |
// undef so same macro can be reused | |
#undef DH_STRING_ENUM | |
#undef DH_STRING_ENUM2 | |
/* | |
//Obj-c Usage | |
NSLog(@"%@", DHBlahKey_pop); // "DHBlahKeypop" | |
NSLog(@"%@", DHBlahKey_crackel); // "To Snap" | |
NSLog(@"%@", DHWowKey_pop); // "DHWowKeypop" | |
NSLog(@"%@", DHWowKey_crackel); // "To Snap" | |
// Swift usage | |
print(DHBlahKey._pop.rawValue); // "DHBlahKeypop" | |
print(DHBlahKey._crackel.rawValue); // "To Snap" | |
print(DHWowKey._pop.rawValue); // "DHWowKeypop" | |
print(DHWowKey._crackel.rawValue); // "To Snap" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment