Home > Enterprise >  How to address a current random element of an array?
How to address a current random element of an array?

Time:12-15

I have an array of different tasks for a game:

var tasksArray = ["Find a star", "Find a cloud", "Find a book", "Find a sun", "Find a moon", "Find a flame", "Find eyes", "Find a case", "Find a globe"]

This task text is shown in a label and picked randomly:

myLabel.text = tasksArray.randomElement()

How do I address the same element picked randomly? What should I insert instead of "???????" that I put after array point?

startLabel.text = "WRONG! TRY AGAIN. \(tasksArray.???????)"

If I type like that:

startLabel.text = "WRONG! TRY AGAIN. \(tasksArray.randomElement()!)"

it gives a new random element.

CodePudding user response:

Instead of storing the results of randomElement directly into a label, save it to an instance variable, and use it later. Something like this:

class Foo {

   let tasksArray = ["Find a star", "Find a cloud", "Find a book", "Find a sun", "Find a moon", "Find a flame", "Find eyes", "Find a case", "Find a globe"]
   var randomString = ""

    func updateRandom {
        randomString = tasksArray.randomElement()
        myLabel.text = randomString
    }

    func badGuess {
        startLabel.text = "WRONG! TRY AGAIN. \(randomString)"
    }
}

(I wrapped stuff in a class so I had a place to put an instance variable, and put the code in functions so it made sense. Your code structure will be different, but this shows the idea.)

If it's important to remember the specific array item rather than just save it's string value you could save an integer index instead of the string. (Say your tasks are a struct rather than an array of Strings.)

class Foo {

   let tasksArray = ["Find a star", "Find a cloud", "Find a book", "Find a sun", "Find a moon", "Find a flame", "Find eyes", "Find a case", "Find a globe"]
   var randomIndex = 0

    func updateRandom {
        let randomIndex = Int.random(0..<tasksArray.count))
        randomString = tasksArray[randomIndex]
        myLabel.text = randomString
    }

    func badGuess {
        startLabel.text = "WRONG! TRY AGAIN. \(tasksArray[randomIndex])"
    }
}

CodePudding user response:

You can get the index of the random element like below

let yourArray : [String] = ["as","dsa","asd","dfsdf"]
    
let yourRandomString = yourArray.randomElement()
    
if let indexOfRandomString = yourArray.firstIndex(of: yourRandomString ?? "") {
    //here you have the index of your random element and you can access it like below
    let b = yourArray[indexOfRandomString]

    }
    
  • Related