ChenSmile
ChenSmile

Reputation: 3441

Generating random values in Swift between two integer values

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.

Upvotes: 29

Views: 30912

Answers (5)

Dimas Prabowo
Dimas Prabowo

Reputation: 71

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

Upvotes: 1

Chris
Chris

Reputation: 4411

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.

Upvotes: 51

Rizwan Mehboob
Rizwan Mehboob

Reputation: 1373

more simple way of random number generator

func random(min: Int, max: Int) -> Int {
    return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}

Upvotes: 2

mattgabor
mattgabor

Reputation: 2084

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
}

Upvotes: 10

Bryan Chen
Bryan Chen

Reputation: 46598

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)

Upvotes: 68

Related Questions