The randomElement() method returns a random key-value pair from the dictionary.
Example
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()
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 returnsOptional((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()
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".