SwiftUI previews stopped working: build error with @main

I've been working for the past day or so to add a very minor feature to one of our UIKit based apps using SwiftUI, as an experiment. Suddenly, this morning, previews stopped working, citing a build error that only occurs when building for preview:

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

I was editing the view when this started happening, but no fiddling I've done with it since has fixed the issue.

I have tried:
  • Reverting all changes in Git

  • Cleaning the build folder (repeatedly)

  • Touching both the file with the SwiftUI view, and the AppDelegate that's annotated with @main

  • Closing the project, and Xcode

The project builds and runs just fine: this error only occurs with previews.

I had been working in Xcode 12.5 beta 2 when the problem started, but it persists when I open the project in Xcode 12.3.

Is there some extra build cache that I can go purge?
Sorry to hear you are having problems getting previews working. Best next step will be to file a feedback with diagnostics.
We will need the diagnostics Xcode Previews generates in order to make sure we understand the error the previews system is encountering.
  1. When you get an error in Xcode Previews, an error banner appears in the canvas

  2. Click the "Diagnostics" button in that banner

  3. In the sheet that appears, click "Generate Report" in the bottom left of the sheet

  4. Attach (or make from the folder) the resulting zip file to the bug (will be named something like previews-diagnostics-0123456789.zip)

OK. Filed FB9017523.

I was able to solve this error by moving the App.swift file (containing the @main statement) to trash, then re-creating the file and its contents.

SwiftUI previews stopped working: build error with @main
 
 
Q