我正在使用核心数据,在我的AppDelegate.swift
中,我在此行dict[NSUnderlyingErrorKey] = error as NSError
上收到以下错误:
'ErrorType'不能转换为'NSError';你的意思是用'as!'迫使低垂?
以下是相应的代码:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("On The Go.sqlite")
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 {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
以下是代码的屏幕截图:
我做了错误建议的内容,但存在同样的错误。
答案 0 :(得分:2)
如果更改catch以在NSError错误中包含模式匹配,该怎么办?
do {
} catch let e as NSError {
// handle NSError case
} catch {
}
由于您的块现在可以抛出,您将不得不改变您的功能:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = try? { () throws in
// your code
}
答案 1 :(得分:0)
尝试将catch
替换为catch let error as NSError
。