简体   繁体   中英

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.

您可以这样做(尽管它并不漂亮):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM