'UIApplicationMain' 属性不能在包含顶级代码的模块中使用

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

突然间,我的 AppDelegate 中出现了这个错误:

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

在它说的行中:@UIApplicationMain

现在无法构建项目。我正在使用 Swift 和 Xcode 6.2。我尝试删除派生数据文件夹,甚至使用最新的 Xcode 6.3 beta,这是我第一次创建项目的地方。

我不知道这是怎么回事,我到处搜索都没有运气。 谢谢

好吧,我终于自己解决了。似乎在我添加的名为 main.swift 的库中隐藏了另一个文件,它与我的 AppDelegate 冲突。我删除了它,问题就消失了。

同样的事情发生在我身上,一个库包含 main.swift ... 删除那个,问题就解决了。

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.

您项目中的某些文件正在使用顶级表达式,即任何函数或块之外的语句。这只允许在一个名为“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.

如果您的项目使用@UIApplicationMain,您的项目不能有顶级表达式。 (根据我使用 XCode 8.2.1 的经验,它似乎甚至不能有一个名为“main.swift”的文件,尽管我找不到这样说明的参考。)

这解释了为什么从项目中删除恶意 main.swift 文件会使错误消失。