这是我在 Swift 中不明白的一件事

This is one thing I do not understand in Swift

考虑这些行:

我用这个创建了一个基于 NSButton 的 class:

typealias onClickHandler = (NSTextfieldSuper)->Void
var onClick: onClickHandler?

当用户点击该按钮的一个实例时,我这样做:

if (self.onClick != nil) {
   onClick?(self)
}

我稍后使用那个按钮,从另一个 class,用这个:

let button = SuperButton()
button.onClick = { (textField: NSTextfieldSuper)->Void in 
}

我不确定这是否是正确的语法。我想处理从创建按钮的父级 class 上的第一个闭包发送的按钮。

这是我能够在没有 Xcode 抱怨的情况下输入的唯一表格。如果这是正确的,那么 ->Void 的目的是什么?这可能会返回什么?

我只想处理发送的那个按钮。

顺便说一句,作为奖励,我必须用这个初始化几个按钮,所有 运行 功能相同。做一些像

这样的事情会很好
func doSomething () {
}

然后

let button = SuperButton()
button.onClick = doSomething

有什么想法吗?

This was the only form I was able to type this without Xcode complaining. If this is correct, what is the purpose of this ->Void there? What could this possibly returning?

它与您的 typealias 相同,在 Swift 中,函数类型的形式为:

(parameter definitions) -> return type

和 return 没有 return 类型的 Void 的函数(类似于 C)。闭包表达式的 full 形式是:

{ (parameter definitions) ->return typeinbody}

在没有任何推论的情况下,此表达式提供了闭包的完整类型,而您示例中的 -> Void Return 类型指定您的闭包 return 什么都没有。在您的作业中,将在编译时检查此完整类型以符合 onClick.

的类型

现在 Swift 会推断出很多东西,并且有各种可用于闭包表达式的简写形式,您会发现 Swift 接受:

button.onClick = { textField in }

此处也推断出闭包的参数和 return 类型。

By the way, as a bonus, [...] any ideas?

只需使类型匹配:

func doSomething(textField : NSTextfieldSuper) { }
button.onClick = doSomething

不同于 (Objective-)C 函数和闭包(C 中的块)是可以互换的(因为它们在许多其他语言中,C 在这里是奇怪的家伙)

HTH