Random number generation
suggest changearc4random_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
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