Swift Dictionary randomElement()

The randomElement() method returns a random key-value pair from the dictionary.

Example

// Create a dictionary with three elements
var information = ["Charlie": 54, "Harvey": 38, "Donna": 34]

// get random element using randomElement() var result = information.randomElement()!
// print updated dictionary print(result) // Output: (key: "Harvey", value: 38)

randomElement() Syntax

The syntax of the randomElement() method is:

dictionary.randomElement()

Here, dictionary is an object of the Dictionary class.


randomElement() Parameters

The randomElement() method doesn't take any parameter.


randomElement() Return Value

  • The randomElement() method returns a random element from the dictionary.

Note: The randomElement() method returns an optional value, so we need to unwrap it. There are different techniques to unwrap optionals. To learn more about optionals, visit Swift Optionals.


Example 1: Swift randomElement()

// Create a dictionary with three elements
var information = ["Carlos": 1999, "Judy": 1992, "Nelson": 1987]

// get random element without unwrapping optionals print(information.randomElement())
// get random element after unwrapping optionals print(information.randomElement()!)

Output

Optional((key: "Carlos", value: 1999))
(key: "Carlos", value: 1999)

In the above example, we have created a dictionary named information. Notice the following:

  • information.randomElement() - since we have not unwrapped the optional, the method returns Optional((key: "Carlos", value: 1999))
  • information.randomElement()! - since we have used ! to force unwrap the optional, the method returns (key: "Carlos", value: 1999)

To learn more about forced unwrapping, visit Optional Forced Unwrapping.


Example 2: Using ?? Operator With randomElement()

// create a dictionary with two elements
var info1 = ["Uikit": 2001, "Swiftui": 2019]

// return random element from info1 print(info1.randomElement() ?? "Empty")
// create empty dictionary var info2 = [String:Int]()
// return random element from info2 print(info2.randomElement() ?? "Empty")

Output

(key: "Swiftui", value: 2019)
Empty

Here, the nil-coalescing operator ?? unwraps the optional dictionary info1 and info2 if they contain a value else it returns the default value "Empty".

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges