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.
GKRandomSource
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];
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.
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.
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()
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
int randomNumber = [[GKRandomSource sharedRandom] nextIntWithUpperBound: 7] + 3;