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
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
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
3. Shuffling the elements of a Collection
Elements in collection can be shuffled using
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]
Don’t forget to read my other articles:
- Everything about Codable in Swift 4
- Everything you’ve always wanted to know about notifications in iOS
- Deep copy vs. shallow copy — and how you can use them in Swift
- Coding for iOS 11: How to drag & drop into collections & tables
- All you need to know about Today Extensions (Widget) in iOS 10
- UICollectionViewCell selection made easy..!!
Feel free to leave comments in case you have any questions.