Understanding random numbers in iOS Swift 2

2019-07-07 20:59发布

问题:

How do I make a random number continue to change over time in the program (I.E. become a new one within the range everytime I want to use it)?

I'm stumped. I've read more than 20 different posts and articles on how to generate random numbers in this language (which I'm pretty new to) and I just can't seem to get it to work.

I'm basically trying to get a random double from 1.0-3.0. I can do this pretty easily, but once it has selected that number it doesn't change. This is my code that I use:

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

Then I use this as a value for the line:

SKAction.waitForDuration(randomNumber)

Every time I run this I want to change the number again, but once the program starts it continues that same number (It's different every time i reset the program)

I understand how to generate the number, but I can't seem to find anything on updating it!

I've tried adding

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

into the code in a spot where it will be ran many times, but it still gives me the same thing.

I'm very familiar with c++ so if you're trying to explain something you can reference its style and I will most likely understand.

回答1:

Use:

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

where sec is the middle of the range in time you want to use, since range goes in a +- direction.

So in your case you want:

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

If for some reason you need a method that will constantly create a new random wait, you can always do:

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

    }
}

And then make sure that you add this as a new action onto your sprite every time you need to get it done, if you store it into a variable, your randomness won't change.



回答2:

What you need it is a read only computed property that will return a new random every time you try to access it:

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


回答3:

Try this code:

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

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

Sample output is: 2.087 1.367 1.867 1.32 2.402 1.803 1.325 1.703 2.069 2.335