简体   繁体   English

Xcode随机变量不起作用

[英]Xcode random variable doesn't work

I'm using Xcode 7.3.1 and Swift, and i'm trying to set a random number between 1 and 50 like that: variableName = random()%50 我正在使用Xcode 7.3.1和Swift,并且我试图像这样设置1到50之间的随机数: variableName = random()%50

Then i have to move an ImageView in the Y axe of that random value: imageviewName.center.y = imageviewName.center.y - variableName 然后我必须在该随机值的Y轴中移动ImageView: imageviewName.center.y = imageviewName.center.y - variableName

But it gives me the following error: "cannot convert value of type 'int' to expected argument type 'CGFloat'. 但这给了我以下错误:“无法将类型'int'的值转换为预期的参数类型'CGFloat'。

So I declared the variable like that: var RandomSquirrel2 = CGFloat() but it still doesn't wok. 因此,我像这样声明了变量: var RandomSquirrel2 = CGFloat()但它仍然不起作用。

How can I generate a random number in Swift? 如何在Swift中生成随机数?

您需要将Int转换为CGFloat

 imageviewName.center.y = imageviewName.center.y - CGFloat(variableName)

You need to cast variableName to CGFloat. 您需要将variableName强制转换为CGFloat。 because random() returns an Int and not A CGFloat. 因为random()返回的是Int而不是CGFloat。

 imageviewName.center.y = imageviewName.center.y - CGFloat(variableName)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM