Swift 4 中的 Smart KeyPaths 无法正常工作
Smart KeyPaths in Swift 4 not working properly
我正在尝试为 SKSpriteNode
创建自定义操作块,我有以下代码:
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',但事实并非如此,因为如果我像它建议的那样删除它,我会得到此错误:
Cannot convert value of type 'ReferenceWritableKeyPath' to expected argument type 'String'
我得到的第二个错误是:
Ambiguous reference to member 'subscript'
我不太确定为什么会收到所有这些错误,我也不确定这些错误的确切含义。如果有人可以向我解释它们并提出解决方案,那就太好了。提前致谢。
keyPath
无效,因为 node
的类型为 SKNode
而不是 SKSpriteNode
。您可以使用条件转换来确定该节点是 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
}
})
我正在尝试为 SKSpriteNode
创建自定义操作块,我有以下代码:
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',但事实并非如此,因为如果我像它建议的那样删除它,我会得到此错误:
Cannot convert value of type 'ReferenceWritableKeyPath' to expected argument type 'String'
我得到的第二个错误是:
Ambiguous reference to member 'subscript'
我不太确定为什么会收到所有这些错误,我也不确定这些错误的确切含义。如果有人可以向我解释它们并提出解决方案,那就太好了。提前致谢。
keyPath
无效,因为 node
的类型为 SKNode
而不是 SKSpriteNode
。您可以使用条件转换来确定该节点是 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
}
})