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.
To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.
In Swift, we can get a random element from an array by using randomELement() . If the array is empty, nil is returned.
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)
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With