我一直在玩NSDecimalNumber
,当我创建扩展程序时,突然间我收到了这个错误:
'ErrorType'不能转换为'NSError';你的意思是用'as!'迫使低垂?
但是当我按照建议使用as!
时,我收到了警告:
来自'NSMutableDictionary!'的强制演员阵容到'[NSObject:AnyObject]'总是成功;你的意思是使用'as'吗?
最终更改为as?
给了我:
从'ErrorType'到'NSError'的条件转换总是成功
我创建的扩展名是:
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 :(得分:1)
这是答案,实际上这个消息很清楚。 ErrorType是一个空协议,它已被NSError采用。因此,没有必要再“保护”或“如果让它”。你可以简单地说
let underlyingError = error as NSError
警告就会消失。
答案 1 :(得分: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 let error as NSError