Smart KeyPaths in Swift 4 not working properly

2.4k views Asked by At

I am trying to create an custom action block for an SKSpriteNode, I have the following code:

let sprite = SKSpriteNode(color: SKColor.red, size: CGSize(width: 50, height: 50))
sprite.position = CGPoint(x: 320, y: 240)    
self.addChild(sprite)

let animation = SKAction.customAction(withDuration: 0, actionBlock: {
    (node, elapsedTime) in

    var initialValue : CGFloat?
    initialValue = node[keyPath: \SKSpriteNode.position.x] //Extraneous argument label 'keyPath:' in subscript

    node[keyPath: \SKSpriteNode.position.x] = 10 //Ambiguous reference to member 'subscript'
})

sprite.run(animation)

I am getting two errors, the first is that the compiler is thinking I have an Extraneous argument of 'keyPath', which is not the case, because if I were to remove it like it suggests, I get this error:

Cannot convert value of type 'ReferenceWritableKeyPath' to expected argument type 'String'

The second error I get is:

Ambiguous reference to member 'subscript'

I am not exactly sure why I am getting all of these errors, and I am not sure exactly what the errors mean. If somebody could explain them to me and propose a solution, that would be great. Thanks in advance.

1

There are 1 answers

0
vacawama On BEST ANSWER

The keyPath isn't working because node has type SKNode and not SKSpriteNode. You can use a conditional cast to establish that the node is an SKSpriteNode:

let animation = SKAction.customAction(withDuration: 0, actionBlock: {
    (node, elapsedTime) in

    var initialValue : CGFloat?
    if let spritenode = node as? SKSpriteNode {
        initialValue = spritenode[keyPath: \SKSpriteNode.position.x]

        spritenode[keyPath: \SKSpriteNode.position.x] = 10
    }
})