D
D
Daria2021-04-16 13:23:49
Swift
Daria, 2021-04-16 13:23:49

Why does Expressions are not allowed at the top level error when I run the code?

func mult(no1: Int, no2: Int) -> Int {
return no1*no2
}

print(mult(no1: 2, no2: 20))
print(mult(no1: 3, no2: 15))
print(mult( no1: 4, no2: 30))
PS I'm new

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NSA-bot, 2021-04-16
@NSA-bot

I could be wrong since you didn't write where you are executing your code. But most likely the error may be because this code, in its bare form (as it is written here, without a class), can be run in the Playground (or in a MacOS project too).
And you most likely inserted all this into an iOS project outside of any class.
That is, in an iOS project, all this code must be inside the class, and besides, the prints must also be in some method, and not just in the class body. For example, like this:

import UIKit

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    print(mult(no1: 2, no2: 20))
    print(mult(no1: 3, no2: 15))
    print(mult(no1: 4, no2: 30))
  }
  
  func mult(no1: Int, no2: Int) -> Int {
    return no1 * no2
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question