Ethan Marcus - 6 months ago 31

iOS Question

I'm making a game and I've been trying to produce random movement. This is my code.

`let actualDuration = NSTimeInterval(random(min(): CGFloat(3.0), max: CGFloat(4.0)))`

The min and max aren't working please help.

Answer

Unlike the .NET Framework or the JDK, there isn't a function that takes `min`

and `max`

parameters to generate a random number. :(

If you want to generate a random number between 3 and 4, you should use the `arc4random_uniform`

function to generate a number between 0 and 999 first and then divide that number by 1000 and plus 3:

```
let randomNumber = Double(arc4random_uniform(1000))
let actualDuration = CGFloat(randomNumber / 1000 + 3)
```

Let me explain how this works.

`randomNumber`

is between 0 and 999 right? Now when you divide it by 1000, it becomes a number less than 1. i.e. 0 ~ 0.999. And you add this number to 3, the result becomes a random number between 3 and 4, which is what you wanted.

If you want a more precise double, you can generate a number between 0 and 9999 and divide it by 10000. You know what I mean!