Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
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]
Further reading
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.
Random Numbers API in Swift 4.2 was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.