Use arc4random_uniform(x)
. This does it for you.
According to the man page:
arc4random_uniform()
will return a uniformly distributed random number less thanupper_bound
.arc4random_uniform()
is recommended over constructions likearc4random() % upper_bound
as it avoids “modulo bias” when the upper bound is not a power of two.