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 nil is returned.

Code

The below code demonstrates how to use randomElement method to get random entry from the Dictionary.

import Swift
//create a Dictionary
var numbers:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
// print the Dictionary
print("The numbers dictionary is \(numbers)")
// get random element from dictionary
var randEle = numbers.randomElement()
print("\nThe random entry from dictionary is: \(randEle!)")

Explanation

In the code above:

  • In line 1: We have created a new Dictionary with name numbers. The numbers Dictionary can have Int type as a key and String type as a value.
  • In line 7: We have printed the numbers Dictionary.
  • In line 10: We have used the randomElement method of the Dictionary to get a random entry stored in the randEle variable. It will have an random entry from the Dictionary.

Free Resources