How to get random elements from Dictionary in Swift
We can use the randomElement method to get a random entry from the Dictionary.
Syntax
func randomElement() -> (key: Key, value: Value)?
randomElement Syntax
This method doesn't take any argument. This method returns an random element from the collection.
This method doesn’t take any argument. It returns a random element from the collection.
If the collection is empty, then
nilis returned.
Code
The below code demonstrates how to use randomElement method to get random entry from the Dictionary.
import Swift//create a Dictionaryvar numbers:[Int:String] = [1:"One", 2:"Two", 3:"Three"]// print the Dictionaryprint("The numbers dictionary is \(numbers)")// get random element from dictionaryvar randEle = numbers.randomElement()print("\nThe random entry from dictionary is: \(randEle!)")
Explanation
In the code above:
- In line 1: We have created a new
Dictionarywith namenumbers. ThenumbersDictionary can haveInttype as a key andStringtype as a value. - In line 7: We have printed the
numbersDictionary. - In line 10: We have used the
randomElementmethod of the Dictionary to get a random entry stored in therandElevariable. It will have an random entry from theDictionary.