理解 iOS Swift 中的随机数 2

Understanding random numbers in iOS Swift 2

如何让一个 运行dom 号码在程序中随着时间的推移不断变化(即每次我想使用它时都成为 运行ge 中的一个新号码)?

我被难住了。我已经阅读了 20 多篇关于如何用这种语言生成 运行dom 数字的不同帖子和文章(我是新手),但我似乎无法让它工作。

我基本上是在尝试从 1.0-3.0 获得 运行dom double。我可以很容易地做到这一点,但一旦它选择了那个数字,它就不会改变。这是我使用的代码:

var randomNumber:Double = (Double(arc4random() % 3) + 1);

然后我将其用作该行的值:

SKAction.waitForDuration(randomNumber)

每次我 运行 我都想再次更改号码,但是一旦程序启动它就会继续使用相同的号码(每次我重置程序时都不一样)

我知道如何生成号码,但我似乎无法找到有关更新号码的任何信息!

我试过添加

randomNumber = (Double(arc4random() % 3) + 1);

在代码中多次 运行,但它仍然给我相同的结果。

我非常熟悉 c++,所以如果你想解释一些东西,你可以参考它的风格,我很可能会理解。

试试这个代码:

func randomNumberBetween1_0And3_0() -> Double {
    return 1 + Double(arc4random_uniform(2000)) / 1000.0
}

for index in 1...10 {
    print(randomNumberBetween1_0And3_0())
}

示例输出为: 2.087 1.367 1.867 1.32 2.402 1.803 1.325 1.703 2.069 2.335

您需要的是一个只读计算 属性,每次您尝试访问它时都会 return 一个新的随机数:

var randomNumber: Double {
    return Double(arc4random_uniform(3).successor())
}

print(randomNumber)  // 2.0
print(randomNumber)  // 2.0
print(randomNumber)  // 1.0
print(randomNumber)  // 3.0
print(randomNumber)  // 3.0

使用:

SKAction.waitForDuration(sec: NSTimeInterval, withRange: NSTimeInterval) 

其中 sec 是您要使用的时间范围的中间值,因为范围在 +- 方向。

所以在你的情况下你想要:

SKAction.waitForDuration(2, withRange: 2),  this will get you a range of 1 to 3 (-1 to 1 range)

如果出于某种原因你需要一个不断创建新的随机等待的方法,你总是可以这样做:

extension SKAction
{
    func waitForRandomDuration() -> SKAction
    {
        var randomNumber:Double = (Double(arc4random() % 3) + 1);
        return SKAction.waitForDuration(randomNumber);

    }
}

然后确保每次需要完成时将其作为新动作添加到精灵上,如果将其存储到变量中,则随机性不会改变。