Random Numbers API in Swift 4.2

October 23rd 2018
Author profile picture

@p.gpt10Payal Gupta

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)   //5995714053130751044
UInt.random(in: 0..<10) //8
Double.random(in: 0...10) //0.4317509841160627
Float.random(in: 0...1) //0.05182791
Bool.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]

Further reading

Don’t forget to read my other articles:

  1. Everything about Codable in Swift 4
  2. Everything you’ve always wanted to know about notifications in iOS
  3. Deep copy vs. shallow copy — and how you can use them in Swift
  4. Coding for iOS 11: How to drag & drop into collections & tables
  5. All you need to know about Today Extensions (Widget) in iOS 10
  6. UICollectionViewCell selection made easy..!!

Feel free to leave comments in case you have any questions.



The Noonification banner

Subscribe to get your daily round-up of top tech stories!