"Expressions are not allowed at the top level" (Only if the code is not in the main.swift file)

When I run the code, xCode shows me this error "Expressions are not allowed at the top level" While the code is correct and runs in the main.swift file only. And also runs in online compilers. please give me solution...

Answered by DTS Engineer in 795107022

In general, Swift treats main.swift differently from other Swift files. The top level of that file become the program’s main entry point, and it runs that code from top to bottom. So, if you have a main.swift with this code:

42

it compiles [1]. OTOH, the same code in a not-main.swift will report an Expressions are not allowed at the top level error.

This can be very confusing so I generally structure my main.swift like so:

func main() {
    … my real code here …
}

main()

That way all the code is within a function called main(), which is not subject to the different behaviour you see in top-level code.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] You get a warning about the value not being used, but that’s just a warning.

What code is causing the error? What version of Xcode are you using? What version of which OS are you building for?

Accepted Answer

In general, Swift treats main.swift differently from other Swift files. The top level of that file become the program’s main entry point, and it runs that code from top to bottom. So, if you have a main.swift with this code:

42

it compiles [1]. OTOH, the same code in a not-main.swift will report an Expressions are not allowed at the top level error.

This can be very confusing so I generally structure my main.swift like so:

func main() {
    … my real code here …
}

main()

That way all the code is within a function called main(), which is not subject to the different behaviour you see in top-level code.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] You get a warning about the value not being used, but that’s just a warning.

"Expressions are not allowed at the top level" (Only if the code is not in the main.swift file)
 
 
Q