Khazan
Khazan

Reputation: 53

learning swift: expressions are not allowed at the top level

I'm learning Swift. I met a problem cannot be solved.

import UIKit

func helloword(str:String) {
    print(str)
}

helloword("say")

I use helloword("say") but Xcode tell me the error:

expressions are not allowed at the top level

Upvotes: 1

Views: 4826

Answers (1)

ranjit.x.singh
ranjit.x.singh

Reputation: 307

You can't simply call this method anywhere in the file. It must be called in a control flow. I mean call it inside a function.

For example, call your function from your viewDidLoad method like so :

override func viewDidLoad() {
self.helloword("say")  // here self is the View Controller itself
}

Upvotes: 1

Related Questions