Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Expressions are not allowed at the top level' if the module is not main.swift

Tags:

xcode

swift

Is there anything special with a main.swift file?

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

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.

like image 549
Anthony Kong Avatar asked Jul 08 '14 22:07

Anthony Kong


2 Answers

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

Update This is documented 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”.

like image 74
Manav Avatar answered Sep 20 '22 13:09

Manav


I wonder if it is really main.swift or perhaps you have two files. Here is a simple demo.

Folder: swift-testy
Files1: main.swift
Files2: ex1.swift

Contents are:

main.swift

import Foundation  println("Hello, World!")  let chaulky = Dog()  chaulky.bark() 

ex1.swift

import Foundation  class Dog {     func bark() {         println("woof") // This is a comment     } } 

Output when I click the run button

Hello, World! woof

like image 36
netskink Avatar answered Sep 19 '22 13:09

netskink