Generating a Random Number in Swift
Generating a random number in swift is easy. This tutorial will cover generating a random int, double, float and CGFloat using simple functions.
To generate a random integer use the following function
func randomInt(min: Int, max: Int) -> Int { return min + Int(arc4random_uniform(UInt32(max - min + 1))) }
Then you simply can generate a random integer (Int) as follows, the rInt constant will be assigned a random number and will print out any number from 1-6 to the console. In our source code we have it in the viewDidLoad() so we can verify the number is being generated.
let rInt = randomInt(1, max: 6) print(rInt) // Will print a random ing from 1-6 to the console
You can easily change the min and max number to generate a random number in any range of numbers you desire.
To generate a random Double, Float or CGFloat use the following functions.
func randomDouble(min: Double, max: Double) -> Double { return (Double(arc4random()) / 0xFFFFFFFF) * (max - min) + min } func randomFloat(min: Float, max: Float) -> Float { return (Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min } func randomCGFloat(min: CGFloat, max: CGFloat) -> CGFloat { return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (max - min) + min }
And you just simply assign a variable or constant to call the function with the minimum and maximum value you want.
let randDouble = randomDouble(1, max: 10) let randFloat = randomFloat(1, max: 10) let randCGFloat = randomCGFloat(1, max: 10) print(randDouble) print(randFloat) print(randCGFloat)
The source code has all of this in one function and will output examples to the console if you wish to take a look at it all in action.