Swift arc4random_uniform unWorking

233 Views Asked by At

I made a variable using arc4random this way:

var a = Int(arc4random_uniform(25))

I want a to be between 0 and 24.

Sometimes it works fine, but sometimes it gives a HUGE value with about 20 characters!

What causes this and how can I fix it?

2

There are 2 best solutions below

0
On

Swift can be a little unpredictable about how it infers variable types.

Try explicitly type casting both the variable a and the constant (25). I tested this code and it worked fine:

    var a:Int = 0

    for var i:Int = 0; i < 1000; i++
    {
        a = Int(arc4random_uniform(UInt32(25)))
        println("a = \(a)")
    }
0
On

Try this code for your random number value:

var a : Int = arc4random_unifrom(25)

Hope this will help you if you are still having problems.