user9775199
user9775199

Reputation:

Access Value in Dictionary using Random Number

I am trying to access the value from a dictionary using a random number, but I am lost, can someone please guide?

Here is what I have:

var themes = ["Halloween": "πŸ˜ˆπŸ’€πŸ€‘πŸ‘»πŸ€–πŸ‘½", "Sports": "πŸ‰πŸ“β›³οΈβš½οΈπŸŽ³πŸŽ±" , "Faces": "πŸ˜€πŸ˜πŸ˜¨πŸ€—πŸ˜€πŸ€€", "Animal": "πŸ¦“πŸ˜ΌπŸ˜ΊπŸ˜ΏπŸ™€πŸ™ˆ"]

// This Does not work for some reason?
lazy var themeRandomNumber = themes.count.arc4random
lazy var currentTheme = themes[themeRandomNumber]

//Cannot subscript a value of type[String : String]' with an index of type 'Int'

This makes sense since, I am trying to access the key using an Int when it is obviously a String, but not sure how to proceed?

lazy var currentEmoji = themes[currentTheme]

extension Int{
    var arc4random: Int{
        if self > 0 {
            return Int(arc4random_uniform(UInt32(self)))
        } else if self < 0 {
            return -Int(arc4random_uniform(UInt32(abs(self))))
        } else {
            return 0
        }
    }
} 

Upvotes: 4

Views: 74

Answers (2)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Just replace

lazy var currentEmoji = themes[currentTheme]

with

var currentTheme = themes.randomElement()
print(currentTheme?.value) //Optional("πŸ‰πŸ“β›³οΈβš½οΈπŸŽ³πŸŽ±")
print(currentTheme?.key)  //Optional("Sports")

Here randomElement is new property which you can use to get random element.

Upvotes: 4

10623169
10623169

Reputation: 1044

Because you're not accessing the key of your dictionary, you need to select "Halloween", "Sports", "Faces" or "Animal" - your themes dict's keys.

You can use some custom mapping method with Int.random(in: 0...3) or a Keys enum conforming to CaseIterable, and then you need to select a random character (emoji) in the String for your given Key (via a random number in the range 0..<string.length).

EDIT

With Swift 4.2+ (Xcode 10) you can use randomElement():

var themes = ["Halloween": "πŸ˜ˆπŸ’€πŸ€‘πŸ‘»πŸ€–πŸ‘½", "Sports": "πŸ‰πŸ“β›³οΈβš½οΈπŸŽ³πŸŽ±" , "Faces": "πŸ˜€πŸ˜πŸ˜¨πŸ€—πŸ˜€πŸ€€", "Animal": "πŸ¦“πŸ˜ΌπŸ˜ΊπŸ˜ΏπŸ™€πŸ™ˆ"]
var randomEmoji = themes.randomElement()?.value.randomElement()

Upvotes: 2

Related Questions