如何使用Swift 1.2来确定NS_ENUM的未记录值 [英] How to determine if undocumented value for NS_ENUM with Swift 1.2

查看:193
本文介绍了如何使用Swift 1.2来确定NS_ENUM的未记录值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,定义了NS_Enum之后...

  typedef NS_ENUM(NSInteger,Type ){
TypeNone = 0,
TypeA = 1,
}



  var x = 2 
如果let type:Type = Type(rawValue:x){
// Swift 1.2执行此块。
}
else {
//上一个swift执行此块。
}

如何确定x是否在NS_ENUM上定义?

解决方案

我假设这是Swift 1.2的以下变化的结果,记录在
UIViewAnimationCurve 现在可以使用 init(rawValue:)初始化器从原始整数
值转换而不被重置到
nil 。使用 unsafeBitCast 作为此问题的解决方法的代码可以使用
来使用原始值初始化程序。例如:

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

现在可以写成:

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


问题(如果我理解正确) p>

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

仅定义了4个可能的枚举值,但实际上也可以采用其他
(未记录)值。这就需要一些讨厌的解决方法,例如





为了解决这个问题,Swift 1.2现在允许创建
枚举变量与任意的原始值(底层的
整数类型),如果枚举从 NS_ENUM
定义导入。



因此,如果
a原始值是 NS_ENUM 以编程方式检查c $ c>定义。


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.

这篇关于如何使用Swift 1.2来确定NS_ENUM的未记录值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆