Is there a way to grab a totally random key in the NSDictionary?
NSString *key = [enumeratorForKeysInDictionary nextObject];
I have this code which iterates over the dictionary in a non-random way.
Should I add all the keys to an NSSet and then pull randomly from there?
Is there a more efficient way to do this?
Modern, one-line version of @BestCoder's answer:
Objective-C
Swift
You can also try something like this:
Then you can c method rand() to get a random index in the above NSArray to get the random key.
You can create a set and then grab any object from the set.
Same idea here, using a random index into keys, but a few improvements: (1) a dictionary category, (2) a block enumerator, like the native, (3) most important - to enumerate randomly, we must eliminate keys already visited. This will visit each key randomly, exactly once (unless the caller sets stop=YES in the block):
Call it like this:
SWIFT 4
you have a dictionary
get a random key value like this
get value of the random key like this