Hello there, how do you pick a random string in Swift from an array? for example;
let names = [“Timmy”, “Von”, “Bimmy”]
Thank you.
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.
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
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
That’s awesome! thank you so much
Hi @tjl037,
a couple of things for you
let names = ["timmy", "tommy", "tammy", "tabby", "tubby", "tooby"]
print(names.randomElement()!)
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.