Reputation: 3181
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?
Upvotes: 2
Views: 658
Reputation: 7028
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
...
}
Upvotes: 0
Reputation: 539685
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 theinit(rawValue:)
initializer without being reset tonil
. Code that usedunsafeBitCast
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.
Upvotes: 4