Drakalex Drakalex - 1 year ago 135
Swift Question

Call a function which expects arguments with SKAction.runBlock()

I'm working with Swift and SpriteKit

I'd like to use SKAction.runBlock() to run a function that expect arguments :

class Tile : SKShapeNode

override func didMoveToView()
let tile = Tile()

func myFunc(tile: Tile)

When I try to create a function that doesn't expect any argument, everything works fine, but the code above returns this:

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

What am I not understanding ?

Answer Source

With writing this sort of expression:


You are passing the result of calling myFunc(tile).

(I believe you do not think this code: SKAction.runBlock(sin(0)), would pass some sort of closure to runBlock.)

And the returned value from myFunc(tile) is a void value, as myFunc is declared to return nothing. A void value can be represented also as (). The error message says () cannot be converted to a closure of type @convention(block) () -> ().

Thus, you need to create a closure of type @convention(block) () -> ().

    tile.runAction(SKAction.runBlock({()->() in myFunc(tile)}))

in short:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download