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

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


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.


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.


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