swiftarc4random

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.


Solution

  • 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()