嗨,我是编码新手,我想知道为什么这不起作用。首先,我尝试创建一个按钮,单击该按钮将打开一个将运行的 applescript。
但我不断收到此错误。
声明仅在文件范围内有效
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func RunNowButton(sender: NSButton) {
import Foundation
let task = NSTask()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["~/Desktop/testscript.scpt"]
task.launch()
}
最佳答案
导入命令只能在“文件范围”使用,如错误所示。文件范围意味着代码不嵌套在任何其他代码中。在 Swift 中,这基本上意味着代码不能嵌套在任何大括号 ({}) 内。
让我们看一个简单的例子:
// Function declared at file scope:
func someFunction() {
// Any code here is inside the scope of "someFunction"
// import would not be allowed
}
// Class at file scope:
class MyClass {
// Any code here is inside the scope of "MyClass"
// import would not be allowed
}
// import at file scope (is valid)
import Foundation
在这种特定情况下,您实际上可以删除 import Foundation
行,因为当您导入 Cocoa 时,Foundation 会自动导入,而您已经在第一行执行了该操作。
关于swift - 这是什么意思 ?声明仅在文件范围内有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29290550/