Xcode: "Expressions are not allowed at the top level"

I am just getting started with programming in Xcode with Swift. When I start a new project with some code, for example: print(“Hello world!”), I get the following error:
“Expressions are not allowed at the top level”
Do you know what might be wrong?
Thank you!

StackOverflow user Manav answered this question in a 2014 post on the subject, making reference to documentation on the Swift blog:

… 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”.

You should review the Swift blog post for additional information on Files and Initialization.

1 Like