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.
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:)](https://developer.apple.com/documentation/swift/int/2995648-random)
— 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
Getting a random element from a collection i.e. array, dictionary or sets
, is something we come across very frequently.
[randomElement()](https://developer.apple.com/documentation/swift/array/2994747-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
.
Elements in collection can be shuffled using shuffled()
or shuffle()
methods.
[shuffle()](https://developer.apple.com/documentation/swift/array/2994753-shuffle)
— Shuffles the collection in place.
[shuffled()](https://developer.apple.com/documentation/swift/array/2994757-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]
Don’t forget to read my other articles:
Feel free to leave comments in case you have any questions.