Smart KeyPaths in Swift 4 not working properly

2019-08-09 02:01发布

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.

标签: swift key swift4
1条回答
淡お忘
2楼-- · 2019-08-09 02:37

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
    }
})
查看更多
登录 后发表回答