Xcode with an Error

Hello everyone!

I am kind a new here and trying to learn Swift.

I am getting this error "Expressions are not allowed at the top level"

I´ve tried both with an function and without function!

func text(){ let number = 120 print(number.isMultiple(of: 3)) } text() Without function

let number = 120
print(number.isMultiple(of: 3))

I really appreaciate if you can help me out!

My playground app is crashing every time I open it so I´ve got no other choice but to use Xcode

Kind regarding Your noob friend!

Accepted Reply

Welcome to the forum.

When you post code, you should post more code and be clear in describing the issue (what works, what does not work). That will help explain.

This works in playground (I renamed text to avoid potential conflicts).

let number = 120
print(number.isMultiple(of: 3))

func printText(){
    let number = 120
    print("is multiple", number.isMultiple(of: 3))
}
printText()

That's for pure playground.

But in an app (including playground app), you cannot call a function directly at the top level (that's what the error says).

You have to call the function from within a class, for instance from the action of a button.

If you show complete code, it will be possible to tell you exactly where.

Replies

Welcome to the forum.

When you post code, you should post more code and be clear in describing the issue (what works, what does not work). That will help explain.

This works in playground (I renamed text to avoid potential conflicts).

let number = 120
print(number.isMultiple(of: 3))

func printText(){
    let number = 120
    print("is multiple", number.isMultiple(of: 3))
}
printText()

That's for pure playground.

But in an app (including playground app), you cannot call a function directly at the top level (that's what the error says).

You have to call the function from within a class, for instance from the action of a button.

If you show complete code, it will be possible to tell you exactly where.