I map NSString objects to NSNumber objects in NSDictionary to set the enum types from JSON strings as follows:
typedef enum { XXEnumTypeA, XXEnumTypeB, XXEnumTypeC, } XXEnumType; ... @property (nonatomic, assign) XXEnumType enumType; ... self.mapNSStringToEnumType = @{ @"enumTypeA" : @(XXEnumTypeA), @"enumTypeB" : @(XXEnumTypeB), @"enumTypeC" : @(XXEnumTypeC), }; ... self.enumType = [self.mapNSStringToEnumType[stringFromJSON] integerValue];
Now I want to go the other way to convert the enum value to a string. I don’t want to store another dictionary with reverse mapping, and the solution I use includes a linear search through the matching dictionary to find the value and then return the key.
In practice, my linear method is good, and neither performance nor memory is a problem, but I'm curious from a scientific point of view if there is another more efficient way that I don’t know about, or perhaps another type of structure that contains a mapping in both directions (so that all values are unique)?
source share