# Generating Random Numbers in Swift with GameplayKit

## Table of Contents

Many games have a need to generate random numbers. If you are making an iOS game with SpriteKit, the GameplayKit framework has classes for generating random numbers.

Generating random numbers has two steps.

- Create a random number generator
- Generate a random number

Create an instance of `GKRandomDistribution`

, which is GameplayKit’s class for generating random numbers. Supply the low and high values to define the range of numbers the generator can generate.

The following code demonstrates how to create a random number generator for rolling a die:

```
let randomGenerator = GKRandomDistribution(lowestValue: 1,
highestValue: 6)
```

After creating the random number generator, you can use it to generate random numbers. Call the generator’s `nextInt`

function to generate a random number.

The following code simulates a die roll:

```
let dieRoll = randomGenerator.nextInt()
```

I have a simple game prototype on GitHub that spawns objects at random starting points.

The `spawnFood`

function in the `GameScene.swift`

file has the random number code.