2

我正在使用以下App方法运行 SwiftUI 应用程序(Xcode 12.3):

@main
struct ThingsApp: App {
...
}

这在模拟器和我的设备上都按预期工作。但它在预览中不起作用:在那里,我得到'main' attribute cannot be used in a module that contains top-level code.

一定是我的应用程序导致了它,因为如果我在 Xcode 中从头开始设置一个项目,这种方法是有效的。但我不太清楚如何弄清楚究竟是什么导致了这种情况。更完整的跟踪如下:

'main' attribute cannot be used in a module that contains top-level code

----------------------------------------

CompileDylibError: Failed to build ThingsApp.swift

Compiling failed: 'main' attribute cannot be used in
a module that contains top-level code

/Users/cg/Library/Developer/Xcode/DerivedData/
Things-bkpepcogttixysdvumdszlfwxfix/Build/
Intermediates.noindex/
Previews/Things/Intermediates.noindex/Things.build/
Debug-iphonesimulator/Things.build/Objects-normal/x86_64/
ThingsApp.2.preview-thunk.swift:8:1: error: 'main' 
attribute cannot be used in a module that contains top-level code
@main extension ThingsApp {
^
/Users/cg/Library/Developer/Xcode/DerivedData/
Things-bkpepcogttixysdvumdszlfwxfix/Build/
Intermediates.noindex/
Previews/Things/Intermediates.noindex/
Things.build/
Debug-iphonesimulator/Things.build/
Objects-normal/x86_64/
ThingsApp.2.preview-thunk.swift:1:1: note: top-level code defined in this source file
@_private(sourceFile: "ThingsApp.swift") import Things

4

2 回答 2

1

App对我来说,这是我在扩展中创建的顶级类类型:

@main
struct MyApp: App {
   var body: some Scene {}

   class AppDelegate: NSObject, UIApplicationDelegate {...}
}

一旦我将它移到外面并进行了干净的构建,预览就会再次起作用:

@main
struct MyApp: App {
   var body: some Scene {...}
}

private class AppDelegate: NSObject, UIApplicationDelegate {...}
于 2021-04-24T17:12:41.963 回答
0

如果您使用的是环境,您的代码应如下所示

    @main
struct YourApp: App {
    @StateObject private var someData = SomeData()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(someData)
        }
    }
}
于 2021-01-24T14:38:52.990 回答