Swift 中 SKAction.runBlock() 的问题

Problems with SKAction.runBlock() in Swift

这是我正在开发的一个简单的 SpriteKit 游戏的一些代码:

let square = SKShapeNode()
let square2 = SKShapeNode()

override func didMoveToView(view:SKView) {
    var moveSquare: SKAction
    moveSquare = SKAction.moveTo(CGPoint(x: someNumber, y:otherNumber), duration: NSTimeInterval(3))

    square.runAction(SKAction.sequence([moveSquare1, SKAction.runBlock(checkIfSquareMatches(square)),SKAction.removeFromParent()]))
    square2.runAction(SKAction.sequence([SKAction.waitForDuration(1.0),SKAction.runBlock(self.addChild(self.square2)) ,moveSquare, SKAction.removeFromParent()]))
}

func checkIfSquareMatches(shape:SKShapeNode) {...}

所以我有两个错误,一个在 square.runAction 行,另一个在 square2.runAction 行。第一个说

"Cannot convert value of type '()' to expected argument type 'dispatch_block_t' (aka '@convention(block) () -> ()')"

第二个说的和上面一样,除了 "type '()'" 它说

"type 'Void' (aka '()')"

由于“(aka '()')”,我认为这是同一件事。

为什么会出现这些错误,我该如何解决?我在 Whosebug 上看到了一个稍微类似的 post 关于 运行 a function in a SKAction.runBlock() 的问题但是解决方案表明问题是你不能 return a value in runBlock,但我的函数没有 return 任何值;它只改变了一些变量的值,所以我没有看到问题。谢谢

当您将片段放在 runBlock 语句中时,它们需要在大括号 {} 内,除非它们是不带参数的简单 func 调用

改为

square.runAction(SKAction.sequence([moveSquare1, SKAction.runBlock( { self.checkIfSquareMatches(self.square) } ),SKAction.removeFromParent()]))
square2.runAction(SKAction.sequence([SKAction.waitForDuration(1.0),SKAction.runBlock( { self.addChild(self.square2 } )) ,moveSquare, SKAction.removeFromParent()]))

}

错误消失

请注意,您必须使用 self 引用变量。在 runBlock 调用中