# Random Numbers API in Swift 4.2

October 23rd 2018

## Random is Good…🎳

With the release of Swift 4.2, Apple introduced a new random API SE-0202 in swift’s standard library.

Let’s look at the details on how we can use this API for different use-cases.

#### 1. Random number from the given Range

A `random(in:)` method is provided for each numeric data type, i.e. `Int, UInt, Float, Double` and also for `Bool` data type.

`random(in:)` — Returns a random value within the specified range.

`Int.random(in: -10...10)   //-6 : Random number in range -10 to 10`

Similarly, we can get a random number for other numeric data types too.

`Int.random(in: Int.min...Int.max)   //5995714053130751044UInt.random(in: 0..<10)             //8Double.random(in: 0...10)           //0.4317509841160627Float.random(in: 0...1)             //0.05182791Bool.random()                       //false `

#### 2. Random element from a Collection

Getting a random element from a collection i.e. `array, dictionary or sets`, is something we come across very frequently.

`randomElement()`— Returns a random element of the collection.

This method is available on each collection type in swift.

`var arr = [1, 2, 4]arr.randomElement()      //Returns an element from arr randomly`
`var dict = ["one": 1, "two": 2, "three": 3]dict.randomElement() //Returns an element from dict randomly`
`(0...10).randomElement() //Returns an element from range randomly`

In case the collection is empty, the `randomElement()` returns `nil`.

#### 3. Shuffling the elements of a Collection

Elements in collection can be shuffled using `shuffled()` or `shuffle()` methods.

`shuffle()` — Shuffles the collection in place.

`shuffled()` — Returns the elements of the sequence, shuffled.

These methods are also available on each collection type in swift.

`var arr = [1, 2, 4]arr.shuffled()      //returns a new array - [4, 2, 1]arr.shuffle()       //shuffles elements in arr itself - [4, 1, 2]`
`(0...10).shuffled()   //[3, 2, 5, 7, 10, 9, 1, 6, 8, 4, 0]`