I need to generate a random number.
It appears the arc4random
function no longer exists as well as the arc4random_uniform
function.
The options I have are arc4random_stir()
, arc4random_buf(UnsafeMutablePointer<Void>, Int)
, and arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32)
.
I can't find any docs on the functions and no comments in the header files give hints.
Put all the values you want into an array, generate a random number using arc4random_uniform(SIZEOFARRAY) and pull the index of the random value from the array, and then repeat this process until the array is empty.
In Swift, we can get a random element from an array by using randomELement() . If the array is empty, nil is returned.
As you know the function arc4random_uniform(_:) returns an integer between zero and the upper bound. If we use array. count as the upper bound, the function will return an index number within the bounds of the array!
let randomIntFrom0To10 = Int.random(in: 1..<10) let randomFloat = Float.random(in: 0..<1) // if you want to get a random element in an array let greetings = ["hey", "hi", "hello", "hola"] greetings.randomElement()
You could try as well:
let diceRoll = Int(arc4random_uniform(UInt32(6)))
I had to add "UInt32" to make it work.
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