Generating random values in Swift between two inte

2019-03-14 13:29发布

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.

标签: swift random
4条回答
手持菜刀,她持情操
2楼-- · 2019-03-14 13:48

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)
查看更多
贼婆χ
3楼-- · 2019-03-14 13:54

more simple way of random number generator

func random(min: Int, max: Int) -> Int {
    return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}
查看更多
叛逆
4楼-- · 2019-03-14 13:57

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
}
查看更多
老娘就宠你
5楼-- · 2019-03-14 14:05

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

let randomInt = Int.random(in: 10...50)
查看更多
登录 后发表回答