0Generating random numbers

suggest change

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.

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

Generation

First, import GameplayKit:

Swift

import GameplayKit

Objective-C

#import <GameplayKit/GameplayKit.h>

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

Swift

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

Objective-C

int randomNumber = [[GKRandomSource sharedRandom] nextInt];

Note

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:

Swift

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

Objective-C

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.

Swift

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:

Swift

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

Objective-C outdated

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents