March 28, 2020

soltveit.org

..Geekish..

Random numbers in swift 2.0

Random numbers in swift

Random numbers in swift 2.0

Here is a short description on how to create random numbers in Swift 2.0.

To create random numbers in swift 2.0 you can use the arc4random_uniform function.
Check out the apple documentation for arc4random_uniform function which you can download at swift.org

Random numbers in swift 2.0 between 0 and 9

let rand = Int(arc4random_uniform(10))

So as you can see we type in 10 into the function. But the function will never return 10, it is up to 10 but never 10.

Random numbers in swift 2.0 between 0 and 10

let rand = Int(arc4random_uniform(11)) or you can type it like this if you find that easier.
let rand = Int(arc4random_uniform(10+1))

Random numbers in swift 2.0 between 5 and 10

let rand = Int(arc4random_uniform(6)) + 5 // This will return numbers between 5 and 10 (including 10)

Just remember when inserting the max limit into the function. It is the max range, but it always starts at zero.

If you need to create more than one random number in your program. Maybe you should consider to write a function for it. Here is an example for a function you could use in your program.

Example random function

func myRandomNumber(Max: UInt32, Min: Int) ->Int {
let rand = Int(arc4random_uniform((Max-UInt32(Min))+1)) + Min
return rand
}

The arc4random_uniform only take UInt32 numbers as parameters. That is why we need to declare Max as UInt32, and cast the Min variable as UInt32 when inside the arc4random_uniform function. We need to use Int to add the Min after the arc4random_uniform function.

A short example on how to use myRandomNumber function to create 10 numbers.

for var x in 0..10 {
let rand = myRandomNumber(10, Min: 5)
print(rand)
}

This code will create 10 random numbers between 5 and 10 and print them to the console.

So this is how you can create random numbers in swift 2.0.

Happy randomising!