Search code examples
arraysswiftdictionaryarc4random

Retrieving a random item out of an array within a dictionary in Swift 3


I have been trying to crack this for months and have finally gotten to the point where I feel that I need to ask for help.

Ultimately I am trying to randomise the key which is returned from my dictionary and then randomise the value returned from its values.

My dictionary is:

var kbDirectory: [String: [String]] = ["Squat": ["4 x 10", "3 x 15", "3 x 20"],
                                   "Deadlift": ["4 x 10", "3 x 15", "3 x 20"],
                                   "2 Handed Swing":["4 x 10", "3 x 15", "3 x 20"],
                                   "Press Up":["4 x 10", "3 x 15", "3 x 20"],
                                   "Pull up":["4 x 10", "3 x 15", "3 x 20"]]

I've attempted multiple times and tried learning from various sources but cannot seem to get it right. Any answers or being pointed in the right direction of what to search/learn would be greatly appreciated.

Cheers!


Solution

  • let randomIndex = Int(arc4random_uniform(UInt32(kbDirectory.count)))
    let dictValues = Array(kbDirectory.values)
    let randomArray = dictValues[randomIndex]
    let randomArrayIndex = Int(arc4random_uniform(UInt32(randomArray.count)))
    let randomValue = randomArray[randomArrayIndex]