How to Generate Random Numbers in Swift 4 & 5
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 116 times, 1 visits today)
Discover more from CompuScoop.com
Subscribe to get the latest posts sent to your email.