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
}
}
}
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.
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()