2014-10-06 63 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