Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a random element in a dictionary in Swift

I got the following code:

var myDic = [String: Customer]()
let s1 = Customer("nameee", "email1")
let s2 = Customer("nameee2", "email2")
let s3 = Customer("nameee3", "email3")
myDic[s1.name] = s1
myDic[s2.name] = s2
myDic[s3.name] = s3

How can I select a random element from the dictionary? I think I should use arc4random_uniform but couldn't find any documentation on it.

like image 275
user1113314 Avatar asked Aug 22 '14 21:08

user1113314


People also ask

How do you get random items from a dictionary?

If you want to get a random key from a dictionary, you can use the dictionary keys() function instead. If you want to get a random key/value pair from a dictionary, you can use the dictionary items() function.

How do you select a random element in a list in Swift?

In Swift, we can get a random element from an array by using randomELement() . If the array is empty, nil is returned.

How do you check if a value is in a dictionary Swift?

Swift – Check if Specific Key is Present in Dictionary To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.


2 Answers

You have to cast some things around, but this seems to work.

var dict:[String:Int] = ["A":123, "B": 234, "C": 345]
let index: Int = Int(arc4random_uniform(UInt32(dict.count)))
let randomVal = Array(dict.values)[index] # 123 or 234 or 345

Basically, generate a random index value between zero and the total item count. Get the values of the dictionary as an array and then fetch the random index.

You could even wrap that in an extension for easy access.

like image 52
Alex Wayne Avatar answered Sep 20 '22 05:09

Alex Wayne


Swift 4.2+ (Xcode 10+) introduces two simple possibilities.

Either randomElement:

let randomVal = myDict.values.randomElement()

Or randomElement:

let randomVal = myDict.randomElement().value
like image 33
Cœur Avatar answered Sep 21 '22 05:09

Cœur