2016-04-03 95 views
2

我一直在玩NSDecimalNumber,當我創建了一個擴展,突然間,我收到此錯誤:創建擴展導致「錯誤類型」是無法轉換爲「NSError」

'ErrorType' is not convertible to 'NSError'; did you mean to use 'as!' to force downcast?

但是,當我使用as!的建議,我得到了警告:

Forced cast from 'NSMutableDictionary!' to '[NSObject : AnyObject]' always succeeds; did you mean to use 'as'?

最終轉變爲as?是給我:

Conditional cast from 'ErrorType' to 'NSError' always succeeds

我創建的擴展名是:

extension String { 

    var decimalValue: NSDecimalNumber? { 
     let number = NSDecimalNumber(string: self) 

     return number == NSDecimalNumber.notANumber() ? nil : number 
    } 
} 

導致該錯誤代碼是:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { 
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.storeFile) 
    var failureReason = "There was an error creating or loading the application's saved data." 

    do { 
     try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) 
    } catch { 
     var dict = [String: AnyObject]() 
     dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" 
     dict[NSLocalizedFailureReasonErrorKey] = failureReason 
---> dict[NSUnderlyingErrorKey] = error as NSError <--- 

     let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 

     NSLog("Unresolved error \(error), \(error.userInfo)") 
     abort() 
    } 

    return coordinator 
}() 

當我改擴建這個錯誤將會消失:

var decimalValue: NSDecimalNumber? { 
    return NSDecimalNumber(string: self) 
} 

如何我應該做這個擴展沒有得到這個惱人的警告/錯誤?

+0

你試過了} catch let error as NSError {而不是dict [NSUnderlyingErrorKey] =錯誤是NSError? –

回答

0

我不知道爲什麼它只是因爲您將擴展名添加到String而引起警告,但我們可以照顧警告!

由於this SO post answer suggests,我們可以這樣做:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { 
    .... 
    do { 
     try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) 
    } catch let error as NSError { 
     .... 
     dict[NSUnderlyingErrorKey] = error 
     let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
     .... 
     NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") 
     abort() 
    } catch { 
     // dummy 
    } 

    return coordinator 
}() 

關鍵因素是catch錯誤就像catch let error as NSError

1

下面是答案其實該消息是很清楚的。 ErrorType是一個空協議,它已被NSError採用。因此,沒有必要「保護」或「如果讓」再次。你可以簡單地說

let underlyingError = error as NSError 

然後警告就會消失。

相關問題