Reputation: 7616
I had a working and compiling Swift game before I updated to the new XCode and suddenly a lot of errors has appeared. Here is two I haven't been able to fix.
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)
I guess I don't really get this ! and ? business. Wrapping, unwrapping, optional types. What is this in Java or C# terms?
Upvotes: 1
Views: 353
Reputation: 9178
This will work, assuming node.scene
is never nil
, and node.parent
is never nil
:
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)
If it is possible for those to be nil
, use this code instead:
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)
}
}
This will test to ensure that none of the values are nil
, and will do nothing if they are (instead of crashing, as the first example would).
For an explanation of how optionals work, read Apple's article.
Upvotes: 2