rv1*_*123 17 enumeration objective-c-blocks swift
我正在使用Swift在SpriteKit中制作游戏.
在Objective-C中,我可以使用以下方法:
(void)enumerateChildNodesWithName:(NSString *)name usingBlock:(void (^)(SKNode *node, BOOL *stop))block
Run Code Online (Sandbox Code Playgroud)
对此执行操作*node,但我无法在Swift中使用此功能.基本上,我不知道如何在Swift中引用该节点.
这是我正在使用的代码,但我遇到了"usingBlock:"部分的问题.我已经尝试了许多小时,但没有成功.请帮忙!
func spawnEnemy() -> () {
let enemy = SKSpriteNode(imageNamed: "enemy")
enemy.name = "enemy"
enemy.position = CGPointMake(100, 100)
self.addChild(enemy)
}
func checkCollisions() -> () {
self.enumerateChildNodesWithName("enemy", usingBlock: ((SKNode!, CMutablePointer<ObjCBool>) -> Void)?)
}
Run Code Online (Sandbox Code Playgroud)
ric*_*ter 45
现在,不要相信自动完成插入您需要的代码 - 它从"标题"中删除签名,但是块签名与为块参数插入自己的闭包时所需的声明不同.
编写闭包的正式方法是复制大括号内的签名,添加本地参数名称并使用in关键字标记闭包体的开头:
self.enumerateChildNodesWithName("enemy", usingBlock: {
(node: SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in
// do something with node or stop
})
Run Code Online (Sandbox Code Playgroud)
但Swift的类型推断意味着你不必写那么多.相反,您可以只为参数命名,因为它们的类型(以及闭包的返回类型)是已知的:
self.enumerateChildNodesWithName("enemy", usingBlock: {
node, stop in
// do something with node or stop
})
Run Code Online (Sandbox Code Playgroud)
您还可以使用尾随闭包语法:
self.enumerateChildNodesWithName("enemy") {
node, stop in
// do something with node or stop
}
Run Code Online (Sandbox Code Playgroud)
(你甚至可以删除本地参数名称和指的是由位置参数-例如$0用于node-但这里是不是一个伟大的地方这样做,因为它使你的代码远不可读这是最好的保留.$0和朋友关闭它的令人眼花缭乱明显的参数是什么,比如你使用的闭包map和sort.)
有关进一步说明,请参阅Swift编程语言中的闭包.
另外,因为stop是a UnsafeMutablePointer,使用它的语法与ObjC中的有点不同:设置stop.memory = true为突破枚举.