Swift version: 5.1
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:
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:
That will return a number between 0 and 10, including 0 and 10 themselves.
LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!
Available from iOS 9.0 – see Hacking with Swift tutorial 35
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.