Swift Language Numbers Random number generation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

arc4random_uniform(someNumber: UInt32) -> UInt32

This gives you random integers in the range 0 to someNumber - 1.

The maximum value for UInt32 is 4,294,967,295 (that is, 2^32 - 1).

Examples:

  • Coin flip

      let flip = arc4random_uniform(2) // 0 or 1
    
  • Dice roll

      let roll = arc4random_uniform(6) + 1 // 1...6
    
  • Random day in October

      let day = arc4random_uniform(31) + 1 // 1...31
    
  • Random year in the 1990s

      let year = 1990 + arc4random_uniform(10)
    

General form:

let number = min + arc4random_uniform(max - min + 1)

where number, max, and min are UInt32.

Notes

  • There is a slight modulo bias with arc4random so arc4random_uniform is preferred.
  • You can cast a UInt32 value to an Int but just beware of going out of range.


Got any Swift Language Question?