gpt4 book ai didi

swift - 创建扩展导致 'ErrorType' 无法转换为 'NSError'

转载 作者:可可西里 更新时间:2023-11-01 02:17:12 27 4
gpt4 key购买 nike

我一直在玩 NSDecimalNumber,当我创建一个扩展时,突然间我收到了这个错误:

'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)
}

我应该如何在不收到这个烦人的警告/错误的情况下进行此扩展?

最佳答案

这里是答案实际上信息非常清楚。 ErrorType 是一个空协议(protocol),它已被 NSError 采用。因此没有必要再次“守卫”或“如果让”它。你可以简单地说

let underlyingError = error as NSError

然后警告就会消失。

关于swift - 创建扩展导致 'ErrorType' 无法转换为 'NSError',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36391608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com