How do you pick a random string from an array?

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