Switch with typedef enum type from string
I'm trying to get a value from a string that belongs to an enum typedef in Obj C but I don't seem capable of geting the value out of the NSString. I'me doing something like this:
typedef enum{
S,
M,
L
} Size;
-(void)function:(NSString *)var{
Size value=[var value];
swicth(value)开发者_JAVA技巧{
case S:...
case M:...
...
}
}
EDIT: The contents of the string would br something like @"S" @"M" @"L"
I don't see how can I accomplish this.
Assuming that you know that the strings are of length one, you can switch on the unichar
at position 0.
switch ([string characterAtIndex:0]) {
case 'S': ...
case 'L': ...
case 'M': ...
}
It's not clear what the string contains. Is it @"S"
, @"M"
or @"L"
? If so, you need to provide your own conversion to the values of the Size
enumeration. Or you could just use string comparison in your method:
if ([var isEqualToString: @"S"]) {
// ...
} else if ([var isEqualToString: @"M"]) {
//...
} ...
However, if the string contains the numeric value of one of the Size
entries (like @"0"
, @"1"
or @"2"
) you can use the -intValue
method to do the comparison you wrote in the question.
精彩评论