AppDelegate.Swift 更新到 Swift 5 后编译错误

AppDelegate.Swift compile error after updating to Swift 5

我最近更新了一个项目,一两年没碰它,现在我遇到了一些问题。

之前一切正常,我什至通过每个错误来更新新语法,但我被困在 AppDelegate.Swift 中的一个函数,这阻止了我 运行 该程序。就是这个:

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = Bundle.mainBundle.url(forResource: "ProjectName", withExtension: "momd")
    return NSManagedObjectModel(contentsOfURL: modelURL ?? <#default value#>)!
}()

在我采纳 Xcode 的建议并更新语法后,它看起来像这样:

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = Bundle.main.url(forResource: "ProjectName", withExtension: "momd")
    return NSManagedObjectModel(contentsOf: modelURL ?? <#default value#>)!
}()

对于 默认值 应该设置什么,我真的很困惑,因为我以前从未编辑或接触过 AppDelegate。 我需要在这里放什么?

感谢您提供的任何帮助!

如果模型丢失,应用程序根本无法运行,您可以强制解包 URL

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = Bundle.main.url(forResource: "ProjectName", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelURL)!
}()

考虑自 iOS 10,macOS 10.12 有一个 more convenient way to initialize the Core Data stack with NSPersistentContainer