Home > Enterprise >  After button click move from array index 0 to 1 and so on
After button click move from array index 0 to 1 and so on

Time:11-16

I've an array of struct, after clicking the correct answer( code below ) I want to change the array index from questions[0] to questions[1], I meant to move through arrays. is it possible in any simple ways ?

any solution will be appericated

    var questions:[EasyQuestions] = [
        EasyQuestions(question: "1   1", optionA: "5", optionB: "2", hint: "3-1", correctAnswer: 1),
        EasyQuestions(question: "2   2", optionA: "4", optionB: "3", hint: "5-1", correctAnswer: 0)
    ].shuffled()
    override func viewDidLoad() {
        super.viewDidLoad()
        configure(with: questions[0])
    }
        @IBAction func buttonClicked(_ sender: UIButton) {
        if sender.tag == questions[0].correctAnswer {
            print("The answer is correct") // after printing this I want to move on the next element of questions array
        }
    }
    
    func configure(with question: EasyQuestions){
        self.Question.text = question.question
        self.button1.setTitle(question.optionA, for: .normal)
        self.button2.setTitle(question.optionB, for: .normal)
    }

CodePudding user response:

You can try

var currentIndex = 0
override func viewDidLoad() {
    super.viewDidLoad()
    configure()
}
@IBAction func buttonClicked(_ sender: UIButton) {
    if sender.tag == questions[currentIndex].correctAnswer {
        print("The answer is correct")
        configure()
    }
}
func configure(){
    if currentIndex < questions.count {
        let question = questions[currentIndex]
        self.question.text = question.question
        self.button1.setTitle(question.optionA, for: .normal)
        self.button2.setTitle(question.optionB, for: .normal) 
        currentIndex  = 1
    }

}

make sure to set tags of button1 and button2 to 0,1 respectively

  • Related