0

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
TylerP
  • 9,600
  • 4
  • 39
  • 43

1 Answers1

1

Your expectation is not very clear from your question, but I guess you are beginner and need a help with processing randomly selected string.

@IBAction func random(_ sender: UIButton) {
            let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
            let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
            let randomlyPickedString = games[randomNumber]
            if randomlyPickedString == "Cards Against Humanity" {
                print("Print anything you want about Cards Against Humanity")
            }
            else if randomlyPickedString == "Mario Kart" {
                print("Print anything you want about Mario Kart")
            }
            else if randomlyPickedString == "Halo" {
                print("Print anything you want about Halo")
            }
            else {
                print("Print anything you want about Pixeljunk Monsters")
            }
        }

If its a finite set of values in array, you can even decide to use switch

Sandeep Bhandari
  • 19,999
  • 5
  • 45
  • 78