Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

xcode - Flappy Bird Coding Error in Swift

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...