The superclass for all basic randomization classes in GameplayKit.


In most cases you do not use this class directly; instead, use one of the subclasses listed below. On its own, a random source provides little control over the range or distribution of generated random numbers; to specify such options, use a random source in conjunction with one of the GKRandomDistribution classes.

When you create an instance of GKRandomSource or one of its subclasses, the resulting random source is both independent and deterministic—that is, the sequence of numbers generated by one instance has no effect on the sequence generated by another instance, and that sequence can be replicated when necessary. For details on replicating sequences, see each of the random source classes.

Your choice of random source class determines the algorithm used for random number generation:

  • The GKARC4RandomSource class uses an algorithm similar to that employed in arc4random family of C functions. (However, instances of this class are independent from calls to the arc4random functions.)

  • The GKLinearCongruentialRandomSource class uses an algorithm that is faster, but less random, than the GKARC4RandomSource class. (Specifically, the low bits of generated numbers repeat more often than the high bits.) Use this source when performance is more important than robust unpredictability.

  • The GKMersenneTwisterRandomSource class uses an algorithm that is slower, but more random, than the GKARC4RandomSource class. Use this source when it’s important that your use of random numbers not show repeating patterns and performance is of less concern.


Creating an Independent Random Source


Initializes a new random source object.

Randomly Shuffling an Array

func arrayByShufflingObjects(in: [Any])

Returns an array whose contents are the same as those of the specified array, but in a random order determined by the random source.

Using a Shared Random Source

class func sharedRandom()

Returns a shared instance that shares a system-wide random source.