在我更新到新的 XCode 之前,我有一个正在运行和编译的 Swift 游戏,突然出现了很多错误。这是我无法修复的两个。
func centerOnNode(node: SKNode ) {
let cameraPositionInScene = node.scene?.convertPoint(node.position, fromNode: node.parent!)
var y = CGFloat(node.parent?.position.y - cameraPositionInScene?.y!)
// ERROR:
// Operand of postfix ‘!’ should have optional types; Type is CGFLoat
let x = CGFloat(node.parent.position.x - cameraPositionInScene.x)
// ERROR:
// SKNode? does not have a member position
// push the camera a bit up
y -= 75
node.parent.position = CGPointMake(x, y)
我想我真的不明白这个!和 ?商业。包装、展开、可选类型。用 Java 或 C# 术语来说这是什么?
最佳答案
假设 node.scene
是 never nil
,并且 node.parent
是 从不 无
:
let cameraPositionInScene = node.scene!.convertPoint(node.position, fromNode: node.parent!)
var y = CGFloat(node.parent!.position.y - cameraPositionInScene.y)
let x = CGFloat(node.parent!.position.x - cameraPositionInScene.x)
如果这些可能是nil
,请改用此代码:
if let cameraPositionInScene = node.scene?.convertPoint(node.position, fromNode: node.parent!) {
if let parent = node.parent {
var y = CGFloat(parent.position.y - cameraPositionInScene.y)
let x = CGFloat(parent.position.x - cameraPositionInScene.x)
// push the camera a bit up
y -= 75
parent.position = CGPointMake(x, y)
}
}
这将进行测试以确保没有任何值是 nil
,如果是则什么也不做(而不是像第一个示例那样崩溃)。
有关可选值如何工作的解释,请阅读 Apple's article .
关于ios - Swift:SKNode 应该有可选类型,可选成员没有成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236621/