Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Acceder al valor en el diccionario usando un número aleatorio

Estoy tratando de acceder al valor de un diccionario usando un número aleatorio, pero estoy perdido, ¿alguien puede guiarme?

Esto es lo que tengo:

 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'

Esto tiene sentido ya que estoy tratando de acceder a la clave usando un Int cuando obviamente es un String , pero no estoy seguro de cómo proceder.

 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 answers
Answer question

0

solo reemplaza

 lazy var currentEmoji = themes[currentTheme]

con

 var currentTheme = themes.randomElement() print(currentTheme?.value) //Optional("🏉🏓⛳️⚽️🎳🎱") print(currentTheme?.key) //Optional("Sports")

Aquí randomElement es una propiedad nueva que puede usar para obtener un elemento aleatorio.

over 4 years ago · Santiago Trujillo Report

0

Debido a que no está accediendo a la clave de su diccionario, debe seleccionar "Halloween" , "Sports" , "Faces" o "Animal" : las claves de su diccionario de themes .

Puede usar algún método de mapeo personalizado con Int.random(in: 0...3) o una enumeración de Keys conforme a CaseIterable , y luego debe seleccionar un carácter aleatorio (emoji) en la String para su clave dada (a través de un número aleatorio en el rango 0..<string.length ).

EDITAR

Con Swift 4.2+ (Xcode 10) puedes usar randomElement() :

 var themes = ["Halloween": "😈💀🤡👻🤖👽", "Sports": "🏉🏓⛳️⚽️🎳🎱" , "Faces": "😀😍😨🤗😤🤤", "Animal": "🦓😼😺😿🙀🙈"] var randomEmoji = themes.randomElement()?.value.randomElement()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!