2014-10-06 61 views
2

我在尝试使用此如何比较NSPersistentStoreUbiquitousTransitionType枚举值

// Check type of transition 
if let type = n.userInfo?[NSPersistentStoreUbiquitousTransitionTypeKey] as? UInt { 

    FLOG(" transition type is \(type)") 

    if (type == NSPersistentStoreUbiquitousTransitionType.InitialImportCompleted) { 
      FLOG(" transition type is NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted") 
    } 

} 

比较从NSPersistentStoreCoordinatorStoresDidChangeNotification接收的值时,下面的错误,但我得到以下编译器错误

NSPersistentStoreUbiquitousTransitionType is not convertible to UInt 

当我以为我得到了斯威夫特的喋喋不休,我再次陷入困境!

回答

3

这是编译器实际上告诉你到底发生了什么问题的罕见情况! typeUInt,而NSPersistentStoreUbiquitousTransitionType.InitialImportCompleted是枚举的一种情况。对它们进行比较,你需要让他们在同一页上 - 它可能最安全得到枚举的原始值:

if (type == NSPersistentStoreUbiquitousTransitionType.InitialImportCompleted.toRawValue()) { 
    FLOG(" transition type is NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted") 
} 

注:在Xcode 6.1,枚举略有变化,所以你'使用.rawValue而不是.toRawValue()

要以另一种方式处理它,您需要将通知中的数据转换为枚举值。该文档说:“相应的值是作为NSNumber对象的NSPersistentStoreUbiquitousTransitionType枚举值之一。”所以,你的代码的第一部分是刚刚好,然后你需要使用枚举的fromRaw(number)静态方法:

if let type = n.userInfo?[NSPersistentStoreUbiquitousTransitionTypeKey] as? Uint { 
    // convert to enum and unwrap the optional return value 
    if let type = NSPersistentStoreUbiquitousTransitionType.fromRaw(type) { 
     // now you can compare directly with the case you want  
     if (type == .InitialImportCompleted) { 
      // ... 
     } 
    } 
} 

注:在Xcode 6.1,你会使用NSPersistentStoreUbiquitousTransitionType(rawValue: type),而不是fromRaw()方法。

+0

谢谢,所以我正确地将userInfo的值作为Uint获取,还是有更好的方式来处理不需要获取原始值的事情? – 2014-10-07 06:30:23

+0

更新了我的答案 – 2014-10-07 14:25:03