Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random numbers with Swift

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.

like image 207
Big_Mac Avatar asked Sep 13 '15 17:09

Big_Mac


People also ask

How do you generate a random number without duplicates in Swift?

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.

How do I generate a random array in Swift?

In Swift, we can get a random element from an array by using randomELement() . If the array is empty, nil is returned.

What is arc4random_uniform?

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!


2 Answers

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() 
like image 185
Arsen Avatar answered Sep 22 '22 02:09

Arsen


You could try as well:

let diceRoll = Int(arc4random_uniform(UInt32(6))) 

I had to add "UInt32" to make it work.

like image 20
Fernando Cardenas Avatar answered Sep 26 '22 02:09

Fernando Cardenas