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