We can use the randomElement
method to get a random entry from the Dictionary.
func randomElement() -> (key: Key, value: Value)?
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
nil
is returned.
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!)")
In the code above:
Dictionary
with name numbers
. The numbers
Dictionary can have Int
type as a key and String
type as a value.numbers
Dictionary.randomElement
method of the Dictionary to get a random entry stored in the randEle
variable. It will have an random entry from the Dictionary
.