Generating random numbers with Swift Generating random numbers with Swift swift swift

Generating random numbers with Swift


===== Swift 4.2 / Xcode 10 =====

let randomIntFrom0To10 = Int.random(in: 1..<10)let randomFloat = Float.random(in: 0..<1)// if you want to get a random element in an arraylet greetings = ["hey", "hi", "hello", "hola"]greetings.randomElement()

Under the hood Swift uses arc4random_buf to get job done.

===== Swift 4.1 / Xcode 9 =====

arc4random() returns a random number in the range of 0 to 4 294 967 295

drand48() returns a random number in the range of 0.0 to 1.0

arc4random_uniform(N) returns a random number in the range of 0 to N - 1

Examples:

arc4random() // => UInt32 = 2739058784arc4random() // => UInt32 = 2672503239arc4random() // => UInt32 = 3990537167arc4random() // => UInt32 = 2516511476arc4random() // => UInt32 = 3959558840drand48() // => Double = 0.88642843322303122drand48() // => Double = 0.015582849408328769drand48() // => Double = 0.58409022031727176drand48() // => Double = 0.15936862653180484drand48() // => Double = 0.38371587480719427arc4random_uniform(3) // => UInt32 = 0arc4random_uniform(3) // => UInt32 = 1arc4random_uniform(3) // => UInt32 = 0arc4random_uniform(3) // => UInt32 = 1arc4random_uniform(3) // => UInt32 = 2

arc4random_uniform() is recommended over constructions like arc4random() % upper_bound as it avoids "modulo bias" when the upper bound is not a power of two.


You could try as well:

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

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


Just call this function and provide minimum and maximum range of number and you will get a random number.

eg.like randomNumber(MIN: 0, MAX: 10) and You will get number between 0 to 9.

func randomNumber(MIN: Int, MAX: Int)-> Int{    return Int(arc4random_uniform(UInt32(MAX-MIN)) + UInt32(MIN));}

Note:- You will always get output an Integer number.