Generating random values in Swift between two inte

2019-03-14 13:03发布

问题:

I'm trying to generate random values between two integers. I've tried this, which starts from 0,

let randomNumber = arc4random_uniform(10)
println(randomNumber)

But I need a value between 10 and 50.

回答1:

try this

let randomNumber = arc4random_uniform(40) + 10
println(randomNumber)

in general form

let lower : UInt32 = 10
let upper : UInt32 = 50
let randomNumber = arc4random_uniform(upper - lower) + lower
println(randomNumber)


回答2:

An answer for Swift 4.2 using the new random() method, which makes it easy!

let randomInt = Int.random(in: 10...50)


回答3:

If you want a reusable function with simple parameters:

func generateRandomNumber(min: Int, max: Int) -> Int {
    let randomNum = Int(arc4random_uniform(UInt32(max) - UInt32(min)) + UInt32(min))
    return randomNum
}


回答4:

more simple way of random number generator

func random(min: Int, max: Int) -> Int {
    return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}


标签: swift random