目前,不要相信自动完成功能会插入您需要的代码 - 它会从“标头”中放入签名,但块签名与您在为块参数插入自己的闭包时所需的声明不同。
编写闭包的正式方法是复制大括号内的签名,添加本地参数名称并使用in
标记闭包体开始的关键字:
self.enumerateChildNodesWithName("enemy", usingBlock: {
(node: SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in
// do something with node or stop
})
但 Swift 的类型推断意味着你不必写那么多。相反,您可以只命名参数,因为它们的类型(以及闭包的返回类型)是已知的:
self.enumerateChildNodesWithName("enemy", usingBlock: {
node, stop in
// do something with node or stop
})
您还可以使用尾随闭包语法:
self.enumerateChildNodesWithName("enemy") {
node, stop in
// do something with node or stop
}
(您甚至可以删除本地参数名称并按位置引用参数 - 例如$0
for node
- 但这里不是这样做的好地方,因为它使您的代码可读性大大降低。最好预约一下$0
和朋友们的闭包,参数是什么非常明显,就像你使用的闭包map
and sort
.)
See Closures https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-XID_117 in Swift 编程语言以获得进一步的解释。
另外,因为stop
is an UnsafeMutablePointer
,使用它的语法与 ObjC 中的有点不同:setstop.memory = true
摆脱枚举。