嗨,我是新来的编码,我想知道为什么这不是工作。首先,我试图创建一个按钮,你点击它,就会打开一个将运行的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

在这种特定的情况下,实际上可以删除“cc>行”,因为在导入第一行的COCOA时,会自动导入基础。

关于swift - 这是什么意思 ?声明仅在文件范围内有效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29290550/

10-12 01:17