Coder-256
Coder-256

Reputation: 5618

NS_ENUM in Swift

NOTE: This is not a dupe of this question.

I am trying to use a library named GBCli in Swift. It was written in Objective-C. I am having trouble with a particular enum:

/** Various command line argument value requirements. */
typedef NS_ENUM(NSUInteger, GBValueFlags) {
    GBValueRequired, ///< Command line argument requires a value.
    GBValueOptional, ///< Command line argument can optionally have a value, but is not required.
    GBValueNone ///< Command line argument is on/off switch.
};

I am trying to use the method:

- (void)registerOption:(NSString *)longOption shortcut:(char)shortOption requirement:(GBValueRequirements)requirement;

In the documentation, a suggested use is:

[parser registerOption:@"verbose" shortcut:'v' requirement:GBValueRequired];

I tried translating this as:

parser.registerOption("verbose", shortcut: 118 /* Array("v".utf8)[0] */, requirement: .Required);

Note: It seems that GBValueRequirements is the argument type used by the library, but that GBValueFlag is the actual type that they intend you to pass into said methods. Evidence: typedef NSUInteger GBValueRequirements;, the enum mentioned above, and the fact that many functions take a GBValueRequirements. Also note that each case in GBValueFlags is exclusive, so they are not meant to be OR'ed together.

However, that gives an error of Type 'UInt' has no member 'Required', which doesn't make sense seeing that the the enum was defined to be of type NSUInteger (which should translate to UInt). I am able to access GBValueFlags, but I am unable to see whatever swift translated it to. Strangely, this works:

let requiredTest : GBValueFlags = .Required;

But this doesn't:

parser.registerOption("verbose", shortcut: 118 /* Array("v".utf8)[0] */, requirement: requiredTest);

Because it throws:

Cannot convert value of type 'GBValueFlags' to expected argument type 'UInt'

at compile time. How should I pass the equivalent of .Required to the method?

Defining my own enum won't work because the internal code of GBCli checks the argument against its own enum.

Upvotes: 1

Views: 1178

Answers (1)

Jon Brooks
Jon Brooks

Reputation: 2492

You can do it like this (though it's not pretty):

parser.registerOption("verbose", shortcut: 118 /* Array("v".utf8)[0] */, requirement: GBValueFlags.Required.rawValue)

Upvotes: 2

Related Questions