我一直在玩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)
}
如何我應該做這個擴展沒有得到這個惱人的警告/錯誤?
你試過了} catch let error as NSError {而不是dict [NSUnderlyingErrorKey] =錯誤是NSError? –