枚举字符串比较

Nic*_*guy 5 c objective-c

我需要将enum作为一个整体与一个字符串进行比较,以便检查枚举的全部内容.

想要的东西:

NSString *colString = [[NSString aloc] initWithString:@"threeSilver"];


typedef enum {
oneGreen,
twoBlue, 
threeSilver
}numbersAndColours;

if (colString == numbersAndColours) {
//Do cool stuff
}
Run Code Online (Sandbox Code Playgroud)

但很明显我不能这样做,也许是一个结构......对不起,我是C的新手请帮忙吗?

顺便说一句:我知道NSString不是C,但认为这个问题比Obj-C更多.

谢谢

Geo*_*che 2

C、ObjC 和 C++ 不直接支持,您必须创建显式映射。

使用普通 C 的示例:

typedef struct { 
    numbersAndColours num;
    const char* const str;
} entry;

#define ENTRY(x) { x, #x }

numberAndColours toNum(const char* const s) {
    static entry map[] = {
        ENTRY(oneGreen),
        ENTRY(twoBlue),
        ENTRY(threeSilver)
    }; 
    static const unsigned size = sizeof(map) / sizeof(map[0]);

    for(unsigned i=0; i<size; ++i) {
         if(strcmp(map[i].str, s) == 0) 
             return map[i].num;
    }

    return -1; // or some other value thats not in the enumeration
}

#undef ENTRY

// usage:

assert(toNum("oneGreen") == oneGreen); 
assert(toNum("fooBar") == -1);
Run Code Online (Sandbox Code Playgroud)

Objective-C 基本方法:

#define ENTRY(x) [NSNumber numberWithInt:x], @#x

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
    ENTRY(oneGreen),
    ENTRY(twoBlue),
    ENTRY(threeSilver),
    nil];

#undef ENTRY

if([dict objectForKey:@"oneGreen"]) {
    // ... do stuff 
}
Run Code Online (Sandbox Code Playgroud)