Random number generation
suggest changearc4random_uniform(_: UInt32) -> UInt32
This C function, from Darwin, gives random integers in the range 0 to upperBound - 1. Swift 4.2 and later can use Int.random(in:) instead. The calls below pass the bound with no argument label.
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, and max - min + 1 fits in a UInt32.
Notes
- There is a slight modulo bias with
arc4randomsoarc4random_uniformis preferred. - You can cast a
UInt32value to anIntbut just beware of going out of range.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents