Swift 4中的Smart KeyPaths无法正常工作 [英] Smart KeyPaths in Swift 4 not working properly
问题描述
我正在尝试为SKSpriteNode
创建自定义操作块,我有以下代码:
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)
我遇到两个错误,第一个是编译器以为我有一个'keyPath'的无关参数,事实并非如此,因为如果我按照建议的方式删除它,则会出现此错误:
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:
无法将类型"ReferenceWritableKeyPath"的值转换为预期的参数类型字符串"
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.
推荐答案
keyPath
不起作用,因为node
具有类型SKNode
而不是SKSpriteNode
.您可以使用条件转换来确定该节点是SKSpriteNode
:
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
}
})
这篇关于Swift 4中的Smart KeyPaths无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!