Swift version: 5.6
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.
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
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.
Link copied to your pasteboard.