-->

'UIApplicationMain' attribute cannot be us

2019-05-05 07:50发布

问题:

All of a suden I got this error in my AppDelegate:

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

in the line where it says: @UIApplicationMain

Now the project cannot build. I am using Swift and Xcode 6.2. I have tried deleting the derived data folder and even using the latest Xcode 6.3 beta, which was where I first created the project.

I don't know what's going on and I have searched everywhere with no luck. Thank you

回答1:

Ok, I finally solved it myself. It seems there was another file buried within a library I added called main.swift which was conflicting with my AppDelegate. I deleted it and the issue went away.



回答2:

Apple documentation, Swift / “Files and Initialization”:

earlier we said top-level code isn’t allowed in most of your app’s source files. The exception is a special file named “main.swift”, which behaves much like a playground file, but is built with your app’s source code. The “main.swift” file can contain top-level code, and the order-dependent rules apply as well. In effect, the first line of code to run in “main.swift” is implicitly defined as the main entrypoint for the program.

Some file in your project is using top-level expressions, that is, statements outside of any function or block. This is only allowed in one file called “main.swift”.

In Xcode, Mac templates default to including a “main.swift” file, but for iOS apps the default for new iOS project templates is to add @UIApplicationMain to a regular Swift file. This causes the compiler to synthesize a main entry point for your iOS app, and eliminates the need for a “main.swift” file.

If your project uses @UIApplicationMain, your project can’t have top-level expressions. (It also seems, according to my experience with XCode 8.2.1, that it can’t even have a file named “main.swift”, though I can’t find a reference that states so.)

This explains why removing a rogue main.swift file from the project makes the error disappear.



回答3:

Same happen to me with a library that contains a main.swift ... Delete that one and problem solved.