gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:41:32 26 4
gpt4 key购买 nike

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

最佳答案

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 会自动导入,您已经在第一行执行了这些操作。

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com