Generating random values in Swift between two integer values
This is an option for Swift 4.2 and above using the random()
method, which makes it easy!
let randomInt = Int.random(in: 10...50)
The range can be a closed (a...b
) or half open (a..<b
) range.
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
}
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)