mardi 19 janvier 2021

How can I tie independent values to strings in an array (Swift)?

So I'm practicing coding and I've set up an array of strings. What I want to happen is to have a function randomly select a string and if a certain string is selected, it would print out one message, and if any of the other strings are selected, it would print out a different one. I think setting up the messages could be done w/an if-else function, but I'm stuck on the earlier step of figuring out how to identify which string is called.

I did some searching and found this thread Get Random String from an Array and I copied the randomization code from it. I'm a bit overwhelmed with where to go from there.

What type of function/identifier etc would I need to set up so that the strings are uniquely identified?

class ViewController: UIViewController {
    
    // Make collection of games and if Monsters is called, print "Take a break." If a diff string is called, print "Do your homework."
    @IBAction func random(_ sender: UIButton) {
        let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
        let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
        _ = games[randomNumber]
    }
} // end of class



Aucun commentaire:

Enregistrer un commentaire