27

I'm trying to generate random values between two integers. I've tried this, which starts from 0,

let randomNumber = arc4random_uniform(10)
println(randomNumber)

But I need a value between 10 and 50.

jscs
  • 63,694
  • 13
  • 151
  • 195
ChenSmile
  • 3,401
  • 4
  • 39
  • 69

5 Answers5

68

try this

let randomNumber = arc4random_uniform(40) + 10
println(randomNumber)

in general form

let lower : UInt32 = 10
let upper : UInt32 = 50
let randomNumber = arc4random_uniform(upper - lower) + lower
println(randomNumber)
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • 3
    add one to `upper - lower` in order to allow 50 as possible result here (since `arc4random_uniform(40)` will return integers in the range 0 -to- 39) – fqdn Jun 17 '14 at 05:58
  • 1
    @ackStOverflow that depends OP want `1..50` or `1...50` – Bryan Chen Jun 17 '14 at 06:01
48

This is an option for Swift 4.2 and above using the random() method, which makes it easy!

let randomInt = Int.random(in: 10...50)

The range can be a closed (a...b) or half open (a..<b) range.

Chris
  • 4,009
  • 3
  • 21
  • 52
10

If you want a reusable function with simple parameters:

func generateRandomNumber(min: Int, max: Int) -> Int {
    let randomNum = Int(arc4random_uniform(UInt32(max) - UInt32(min)) + UInt32(min))
    return randomNum
}
esreli
  • 4,993
  • 2
  • 26
  • 40
mattgabor
  • 2,064
  • 6
  • 25
  • 38
2

more simple way of random number generator

func random(min: Int, max: Int) -> Int {
    return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}
Rizwan Mehboob
  • 1,333
  • 17
  • 19
1

If you want to generate exclusively between 2 integers, you can use

func random(_ x: UInt32, _ y: UInt32) -> UInt32 {
    Bool.random() ? x : y 
}

But if you want to generate between 2 integers range, you can use

func random(_ lower: UInt32, _ upper: UInt32) -> UInt32 {
    Int.random(in: lower...upper)
}