xcode Swift 编译器错误:“Double”不可转换为 CGFloat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25028039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift Compiler error: 'Double' is not convertible to CGFloat
提问by Beast_Code
I just began learning Swift. I created a game project and a template came up. I have not done anything to the code whatsoever. I tried to run the project but a compiler error popped up.
我刚开始学习 Swift。我创建了一个游戏项目并出现了一个模板。我没有对代码做任何事情。我试图运行该项目,但弹出编译器错误。
I'm going off a tutorial so it could be something wrong with my environment or the book is already outdated.
我要离开教程,所以我的环境可能有问题,或者这本书已经过时了。
Swift Compiler error: 'Double' is not convertible to CGFloat
Swift 编译器错误:“Double”不可转换为 CGFloat
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!";
myLabel.fontSize = 65;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func mouseDown(theEvent: NSEvent) {
/* Called when a mouse click occurs */
let location = theEvent.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.position = location;
sprite.setScale(0.5)
let action = SKAction.rotateByAngle(M_PI, duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
The error occurs in let action = SKAction.rotateByAngle(M_PI, duration:1)
错误发生在 let action = SKAction.rotateByAngle(M_PI, duration:1)
Here is a screenshot of the project settings
这是项目设置的屏幕截图
回答by Santa Claus
You can convert it with CGFloat(M_PI)
.
你可以用CGFloat(M_PI)
.
For example the following code should work in your case (note the use of CGFloat
)
例如,以下代码应该适用于您的情况(注意使用CGFloat
)
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
回答by Drakalex
You can declare pi like this in your code : let π = CGFloat(M_PI)
and then use let action = SKAction.rotateByAngle(π, duration:1)
您可以在代码中像这样声明 pi:let π = CGFloat(M_PI)
然后使用let action = SKAction.rotateByAngle(π, duration:1)
If you are going to use π a lot, it's way more simple.
如果你要经常使用 π,那就更简单了。
You can type π with the shortcut alt+p
您可以使用快捷键 alt+p 键入 π
回答by Howard Lovatt
The old M_PI was a Double, but the function did expect a CGFloat. A cast would be the solution.
旧的 M_PI 是一个 Double,但该函数确实需要一个 CGFloat。演员阵容将是解决方案。
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
With respect to Swift 5 it would be now:
关于 Swift 5,现在是:
let action = SKAction.rotate(byAngle: .pi, duration:1)
No need to cast anymore
无需再投