Coding

iOS: Random Number Generation

Use the arc4random function to generate random numbers in a range.

Suppose you have to generate a random number from 0 to 99. Do:
int randomNum0to99 = arc4random() % 100;
Or:
int randomNum0to99 = arc4random_uniform(100);

Between the 2 codes, the latter is preferred because:


arc4random_uniform() will return a uniformly distributed random number less than upper_bound.
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.

If you have to generate a random number from 11 to 30, add some math into your code:
int randomNum0to99 = arc4random_uniform(20) + 11; // For 20 numbers and minimum 11.



Leave a Reply

Your email address will not be published. Required fields are marked *