How do you pick a random string from an array?

Hello there, how do you pick a random string in Swift from an array? for example;

let names = [“Timmy”, “Von”, “Bimmy”]

Thank you.

Guess this could be an option:

// For example:
let names = ["Timmy", "Von", "Bimmy", "Ray", "Wenderlich"]
let randomNumber = Int.random(in: 0..<names.count)

print("Random string:", names[randomNumber])

Run this a few times.

1 Like

It worked, thank you so much! If you wouldn’t mind answering another question, how would you print the result in the message of an alert?

Not sure what you mean by that, like in an alert popup? Might want to provide some context and I’ll see what I can do :slight_smile:

Yeah, I meant in an alert popup. Sorry about that!

For example:

You know how you create an alert with an UIAlertController and you can specify the title, and message, and preferredStyle. I would like the random string to show in the message of the alert.

No worries. Yeah you’ll have to do so like the following, for example:

let names = ["Timmy", "Von", "Bimmy", "Ray", "Wenderlich"]

@IBAction func showAlert() { 
    // ^ Hook this up to a button via Interface Builder

    let randomNumber = Int.random(in: 0..<names.count)
    
    let alertController = UIAlertController(title: nil, message: names[randomNumber], preferredStyle: .alert)
    let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertController.addAction(alertAction)
    
    self.present(alertController, animated: true, completion: nil)
}

Example project : Click me to download
Hope this is what you’re looking for, if not, contact me via Twitter @PieterVelghe

1 Like

That’s awesome! thank you so much :slightly_smiling_face:

Hi @tjl037,
a couple of things for you

  1. If you want to get a random string from an array then the newer release of Swift has made it simple, you can simply use the randomElement() function on the array - as in
  let names = ["timmy", "tommy", "tammy", "tabby", "tubby", "tooby"]
  print(names.randomElement()!)
  1. You want to display alerts you can create an extension that can allow you to display the alert or a function that can have a signature like
  func showAlert(title: String = "", message: String) { ... }

this way you can pass it a title and or a message

cheers,

Jayant

This topic was automatically closed after 166 days. New replies are no longer allowed.