iOS Generating random numbers


Although GameplayKit (which is introduced with iOS 9 SDK) is about implementing game logic, it could also be used to generate random numbers, which is very useful in apps and games.

Beside the GKRandomSource.sharedRandom which is used in the following chapters there are three additional types of GKRandomSource's out of the box.

  • GKARC4RandomSource Which uses the the ARC4 algorithm
  • GKLinearCongruentialRandomSource Which is a fast but not so random GKRandomSource
  • GKMersenneTwisterRandomSource Which implements a MersenneTwister algorithm. It is slower but more random.

In the following chapter we only use the nextInt() method of a GKRandomSource. In addition to this there is the nextBool() -> Bool and the nextUniform() -> Float


First, import GameplayKit:


import GameplayKit


#import <GameplayKit/GameplayKit.h>

Then, to generate a random number, use this code:


let randomNumber = GKRandomSource.sharedRandom().nextInt()


int randomNumber = [[GKRandomSource sharedRandom] nextInt];


The nextInt() function, when used without parameters, will return a random number between -2,147,483,648 and 2,147,483,647, including themselves, so we are not sure that it is always a positive or non-zero number.

Generating a number from 0 to n

To achieve this, you should give n to nextIntWithUpperBound() method:


let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: 10)


int randomNumber = [[GKRandomSource sharedRandom] nextIntWithUpperBound: 10];

This code will give us a number between 0 and 10, including themselves.

Generating a number from m to n

To do this you create a GKRandomDistribution object with a GKRandomSource and pass in the bounds. A GKRandomDistribution can be used to change the distribution behaviour like GKGaussianDistribution or GKShuffledDistribution.

After that the object can be used like every regular GKRandomSource since it does implement the GKRandom protocol too.


let randomizer = GKRandomDistribution(randomSource: GKRandomSource(), lowestValue: 0, highestValue: 6)
let randomNumberInBounds = randomizer.nextInt()

Objective-C outdated

int randomNumber = [[GKRandomSource sharedRandom] nextIntWithUpperBound: n - m] + m;

For example, to generate a random number between 3 and 10, you use this code:


let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: 7) + 3

Objective-C outdated

int randomNumber = [[GKRandomSource sharedRandom] nextIntWithUpperBound: 7] + 3;