Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've encountered a coding error for my flappy bird project, in Xcode 6.1.

The code is to allow rotation of the bird, and it reads:

bird.zRotation = self.acotarMinMax(-1, max: 0.3, valor: bird.physicsBody?.velocity.dy * (bird.physicsBody?.velocity.dy < 0 ? 0.003 : 0.001))

the error occurs under dy, it reads:

value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?

How can I correct the error, or is there another way to generate rotation?

I am a total beginner of Swift, so I'm having a hard time figuring out if this is a syntax problem or something to do with the updated version.

I obtained the code from a online tutorial, and it worked in the video.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
298 views
Welcome To Ask or Share your Answers For Others

1 Answer

Read up on the Swift Optional class: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

So it seems that dy is an Optional value, which means that it either has a value or it does not, but you don't know until you look into it (like Schroedinger's Cat). So if you need this value and you know it will not be nil, you unwrap it by writing bird.physicsBody?.velocity.dy! which will look into the "box" and take the value out but crash if there is nothing inside. If you write dy? it will look into the box but ignore it if the box is empty.

More on Optional Chaining (which is what you do) here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...