Giulia Lage
Giulia Lage

Reputation: 535

How to get enum value by name in Objective-C

typedef NS_ENUM(NSInteger, CameraMode) {
  DEFAULT,
  SMART,
  LIVENESS,
  DOCUMENT
};

I want to to something like

NSInt *mode = CameraMode.getValue("DEFAULT");

is it possible with Objective-C? I did something similar in Java like this:

CameraMode.valueOf("DEFAULT");

Upvotes: 1

Views: 1281

Answers (2)

Aleksandr Medvedev
Aleksandr Medvedev

Reputation: 8968

Objective-C doesn't support any extra functionality as part of enums, however nothing prevents you from writing your own helper functions:

typedef NS_ENUM(NSUInteger, TDWState) {
    TDWStateDefault,
    TDWStateSmart,
    TDWStateLiveness,
    TDWStateUndefined
};

TDWState TDWStateFromString(NSString *string) {
    static const NSDictionary *states = @{
        @"DEFAULT": @(TDWStateDefault),
        @"SMART": @(TDWStateSmart),
        @"LIVENESS": @(TDWStateLiveness),
    };
    
    NSNumber *state = [states objectForKey:string];
    
    if (state) {
        return state.unsignedIntValue;
    } else {
        return TDWStateUndefined;
    }
};

Which then can be used like this:

TDWState state = TDWStateFromString(@"DEFAULT");

Upvotes: 1

DarkDust
DarkDust

Reputation: 92335

There is no language-support for something like this. After all, typedef NS_ENUM(NSInteger, CameraMode) { … } is basically just C with some fancy macros.

You have to implement such string to enum mappings yourself, unfortunately.

Upvotes: 0

Related Questions