如果模块不是 main.swift 则“顶层不允许表达式" [英] 'Expressions are not allowed at the top level' if the module is not main.swift

查看:42
本文介绍了如果模块不是 main.swift 则“顶层不允许表达式"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

main.swift 文件有什么特别之处吗?

Is there anything special with a main.swift file?

我在 XCode 中创建了一个基于命令行的项目.如果我把一个表达式 println("Hello, World!"); 放在一个新的 swift 文件中说 test.swift,我会得到错误信息:Expressions are not allowed at the top level

I have created a command line based project in XCode. If I put an expression println("Hello, World!"); in a new swift file says test.swift, I will get the error message: Expressions are not allowed at the top level

然而,这个表达式被放置在由 XCode 在新项目中创建的 main.swift 的顶层.XCode 没有标记此类异常.

However this expression is placed at top level in the main.swift that is created by XCode in the new project. No such exception is flagged by XCode.

推荐答案

显然是的,根据这个 answer.但是,没有关于这种行为的引用.

Apparently yes, as per this answer. However, there are no citations as to this behaviour.

更新这在 Swift 博客中有记录:

...之前我们说过,大多数应用的源文件中不允许使用顶级代码.例外是一个名为main.swift"的特殊文件,它的行为很像一个游乐场文件,但它是用你的应用程序的源代码构建的.main.swift"文件可以包含顶级代码,并且依赖于顺序的规则也适用.实际上,在main.swift"中运行的第一行代码被隐式定义为程序的主入口点.这允许最小的 Swift 程序是一行——只要该行在main.swift"中.

... 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. This allows the minimal Swift program to be a single line — as long as that line is in "main.swift".

这篇关于如果模块不是 main.swift 则“顶层不允许表达式"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆