Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random values in Swift between two integer values

Tags:

random

swift

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.

like image 850
ChenSmile Avatar asked Jun 17 '14 05:06

ChenSmile


People also ask

How do you generate a random integer in Swift?

To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.

How do I generate a random array in Swift?

In Swift, we can get a random element from an array by using randomELement() . If the array is empty, nil is returned.


2 Answers

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) 
like image 199
Bryan Chen Avatar answered Sep 23 '22 08:09

Bryan Chen


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.

like image 43
Chris Avatar answered Sep 24 '22 08:09

Chris