Swift version: 5.4
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.
SPONSORED Join a FREE crash course for iOS devs who want to become complete senior developers — from October 18th to 24th. Learn how to apply iOS app architecture patterns through a series of lectures and practical coding sessions.
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.