开发中,有时候将枚举类型作为Key会使代码简洁直观,提高可读性,符合“面向人件编程”思想,但枚举为基本数据类型,Key一般都要求字符串(对象),不能直接转换,这里提供一种方法,可以将枚举名称
转换为字符串:
#define stringWithLiteral(literal) @#literal
typedef NS_ENUM(NSInteger, EnumType) {
EnumType0,
EnumType1,
EnumType2
};
static NSString * const EnumTypeNames[] = {
stringWithLiteral(EnumType0),
stringWithLiteral(EnumType1),
stringWithLiteral(EnumType2)
};
测试方法:
- (void)test {
EnumType enumType = EnumType1;
NSString *enumName = EnumTypeNames[enumType];
NSLog(@"enumName: %@", enumName);
}