Generating random numbers in an app may seem like a waste of time, but you may have to create a random number generator for various projects such as an auto password generator or even a game.
Here’s the simplest way to accomplish this:
let ranNumber = Int (arc4random_uniform(100))
Lets take this step by step:
- Import Foundation as a habit when ever you work with numbers.
- Let the value of ranNum hold the random number once the computer selects a number.
- Since a number is an integer, let the program know this by adding the INT function.
- The arc4random_uniform statement is the very basic way to make Swift generate the number.
- The (100)) means to pick a number between 0 to 99.
- Print the answer to the Playground output.
That’s one way. Another way is:
for i in 0…11
let ranNumber = Int (arc4random_uniform(UInt32(i)))
Again, step by step:
- ranNum will select a number from 0 – 12.
- Print the results of ranNumber 12 times.
- Output: 5 9 2 6 1 3 4 8 6 7 0 (your numbers maybe different).