如何将NSNumber与快速枚举值进行比较?

Mik*_*ers 2 cocoa swift

我正在尝试对通过NSNotification接收的值和枚举值进行简单比较.我有一些有用的东西,但我无法相信这是做这件事的正确方法.基本上我最终得到的解决方案是将NSNumber转换为Int,并获取枚举值的rawValue,将其包装在NSNumber中,然后获取该值的integerValue.

我尝试的其他所有内容导致编译器错误,无法在Uint 8和Int或类似的东西之间进行转换.

    observer = NSNotificationCenter.defaultCenter().addObserverForName(AVAudioSessionRouteChangeNotification, object: nil, queue: mainQueue) { notification in

        println(AVAudioSessionRouteChangeReason.NewDeviceAvailable.toRaw())

        if let reason = notification.userInfo[AVAudioSessionRouteChangeReasonKey!] as? NSNumber  {
            if (reason.integerValue == NSNumber(unsignedLong:AVAudioSessionRouteChangeReason.NewDeviceAvailable.toRaw()).integerValue) {
                self.headphoneJackedIn = true;
            } else if (reason.integerValue == NSNumber(unsignedLong:AVAudioSessionRouteChangeReason.OldDeviceUnavailable.toRaw()).integerValue) {
                self.headphoneJackedIn = false;
            }
            self.updateHeadphoneJackLabel()
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 8

这应该工作:

if reason.integerValue == Int(AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

注:AVAudioSessionRouteChangeReason枚举使用UInt为原始值的类型,所以可以预期,这个工作没有一个明确的转换:

if reason.unsignedIntegerValue == AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue {

}
Run Code Online (Sandbox Code Playgroud)

然而,如Xcode的6测试4的,NSUInteger被映射到Swift的Int在OS X和iOS系统框架,这意味着这两个integerValueunsignedIntegerValue返回 Int,并且需要在任何情况下的显式转换.

或者,您可以从数字创建枚举值(如注释中@ColinE已经建议的那样),然后使用switch case:

if let r = AVAudioSessionRouteChangeReason(rawValue: UInt(reason.integerValue)) {
    switch r {
    case .NewDeviceAvailable:
        // ...
    case .OldDeviceUnavailable:
        // ...
    default:
        // ...
    }
} else {
    println ("Other reason")
}
Run Code Online (Sandbox Code Playgroud)

出于与上述相同的原因,UInt此处也需要显式转换.