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.

Thank you for reading this post, don't forget to subscribe!

Here’s the simplest way to accomplish this:

import UIKit

import Foundation

let ranNumber = Int (arc4random_uniform(100))

print (ranNumber)

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:

import UIKit

import Foundation

for i in 0…11

{

    let ranNumber = Int (arc4random_uniform(UInt32(i)))

    print (ranNumber)

}

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).

 

 

About Post Author

(Visited 115 times, 1 visits today)

Dan Uff
Senior Writer / Owner
https://www.compuscoop.com/