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

标签 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()
    }

最佳答案

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

相关文章:

Android.mk 包含其他项目

java - 如何将项目 Y 添加到项目 X 并将项目 X 添加到项目 Z 并修复问题构建路径

ios - 测验 : How to integrate an alternative/a similar answer as declared correct in a UITextField

wpf - WPF 中的 Google 样式按钮

javascript - jQuery对话框按钮如何设置点击事件?

Android:如何让Borderless button的文字大小和TextView一样

SQL Server 2008 运行大型查询 - 内存不足

ios - 如何过滤 dic-filter 数组并附加到单独的 dic 数组

swift - 如何在 swift 3 中从数组中查找特定位置对象

ios - 解析/PFQueryTableView : Append extra text to an object in parse