简体   繁体   中英

How to determine if undocumented value for NS_ENUM with Swift 1.2

For instance, following NS_Enum is defined...

typedef NS_ENUM(NSInteger, Type) {
  TypeNone = 0,
  TypeA = 1,
}
var x = 2
if let type: Type = Type(rawValue: x) {
  // Swift 1.2 executes this block.
}
else {
  // Previous swift executes this block.
}

How can I determine if x is defined on NS_ENUM or not?

I assume this is a consequence of the following change in Swift 1.2, documented in the Xcode 6.3 release notes :

Imported NS_ENUM types with undocumented values, such as UIViewAnimationCurve , can now be converted from their raw integer values using the init(rawValue:) initializer without being reset to nil . Code that used unsafeBitCast as a workaround for this issue can be written to use the raw value initializer. For example:

 let animationCurve = unsafeBitCast(userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue, UIViewAnimationCurve.self) 

can now be written instead as:

 let animationCurve = UIViewAnimationCurve(rawValue: userInfo[UIKeyboardAnimationCurveUserInfoKey].integerValue)! 

The problem (if I understand it correctly) was that

typedef NS_ENUM(NSInteger, UIViewAnimationCurve) { ... }

defined only 4 possible enumeration values, but could in fact take other (undocumented) values as well. This made some nasty workarounds necessary, see for example

To solve this problem, Swift 1.2 does now allow the creation of enumeration variables with arbitrary raw values (of the underlying integer type), if the enumeration is imported from an NS_ENUM definition.

As a consequence, it is not possible to check programmatically if a "raw value" is one of the defined values in the NS_ENUM definition.

Try this:

typedef NS_ENUM(NSInteger, Type) {
    TypeZero = 0,
    TypeOne = 1,
    TypeTwo = 2,
    TypeUnexpected = INT_MAX
};
switch Type(rawValue: 3) ?? .unexpected {
case .zero:
    // Handle type zero
    ...
case .one:
    // Handle type one
    ...
case .two:
    // Handle type two
    ...
default:
    // Handle unexpected types
    ...
}

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