Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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
        }
    }
} 
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar

0

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()
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda