Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one generate a random number in Apple's Swift language?

Tags:

random

swift

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one's own program? Or is there a library that does this that we can use now?

like image 522
door_number_three Avatar asked Jun 03 '14 04:06

door_number_three


People also ask

How do you generate random numbers 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 is random number generated?

Random number generation is a process by which, often by means of a random number generator (RNG), a sequence of numbers or symbols that cannot be reasonably predicted better than by random chance is generated.

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.


1 Answers

Swift 4.2+

Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You can call the random() method on numeric types.

let randomInt = Int.random(in: 0..<6) let randomDouble = Double.random(in: 2.71828...3.14159) let randomBool = Bool.random() 
like image 159
Catfish_Man Avatar answered Sep 20 '22 02:09

Catfish_Man