这是什么意思 ?声明仅在文件范围内有效

时间:2015-03-26 23:12:51

标签: swift button import scope declaration

嗨,我是编码的新手,我想知道为什么这不起作用。首先,我尝试创建一个单击的按钮,然后打开将运行的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()
    }

2 个答案:

答案 0 :(得分:2)

import 命令只能在错误指示的“文件范围”中使用。文件范围意味着代码不嵌套在任何其他代码中。在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。

答案 1 :(得分:0)

您无法在方法内导入任何内容,因此请移动行

import Foundation

在文件顶部。