【问题标题】:AppDelegate.Swift compile error after updating to Swift 5更新到 Swift 5 后 AppDelegate.Swift 编译错误
【发布时间】:2022-01-26 00:19:45
【问题描述】:

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

以前一切正常,我什至通过每个错误来更新新语法,但我被困在 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。 我需要在这里放什么?

感谢您提供的任何帮助!

【问题讨论】:

  • 与其担心“默认值”,只需解开modelURL 可选(例如guard let modelURL = ... else { fatalError("database not found") } 或只是let modelURL = Bundle.mainBundle.url(forResource: "ProjectName", withExtension: "momd")!。那么您根本不需要nil 合并运算符。
  • 这不是更新到 Swift 5 的问题。第一个代码块在早期的 Swift 版本中无法编译。

标签: swift xcode swift5 appdelegate


【解决方案1】:

如果模型丢失,应用程序根本无法运行,您可以强制解开 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多