

How to generate a random number with GKRandomSource

Swift version: 5.0

Paul Hudson    @twostraws   

GameplayKit is a powerful new framework introduced in iOS 9.0, and one of the (many!) things it does is provide a number of ways to generate random numbers easily. To get started, import the framework into your code like this:

import GameplayKit

You can immediately start generating random numbers just by using this code:


That code produces a number between -2,147,483,648 and 2,147,483,647, so if you're happy with negative numbers then you're basically done. Alternatively, if you want a random number between and an upper bound (inclusive!), you should use this code instead:

print(GKRandomSource.sharedRandom().nextInt(upperBound: 10))

That will return a number between 0 and 10, including 0 and 10 themselves.


Available from iOS 9.0 – see Hacking with Swift tutorial 35

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base



Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>