Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

SwiftUI Problem with main attribute only in Previews

I am running a SwiftUI app (Xcode 12.3) using the App approach:

@main
struct ThingsApp: App {
...
}

This works as expected both on simulators and my device. But it does not work in previews: There, I get the error of 'main' attribute cannot be used in a module that contains top-level code.

There must be something about my app that's causing it, since if I set up a project from scratch in Xcode, this approach works. But I don't quite know how to figure out what exactly would cause this. Fuller trace below:

'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

question from:https://stackoverflow.com/questions/65871820/swiftui-problem-with-main-attribute-only-in-previews

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

if you are using environment your code should look like this

    @main
struct YourApp: App {
    @StateObject private var someData = SomeData()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(someData)
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...