Reputation: 27
I've created a simple quiz-app which will count how many questions the user has answered correct and put them in a label in another view. Problem is that when the user answers the last question(array) correct, it won't count up in my counter like it does with the other questions, but only switch view. So instead of showing 4 correct in the next view, it will only show 3, if the last question was answered correctly. Still haven't figured. Any help? My code:
func pickQuestion(){
if questions.count > 0{
qNumber = random() % questions.count
questions.shuffleInPlace()
qLabel.text = questions[qNumber].question
answerNumber = questions[qNumber].answer
for i in 0..<buttons.count{
buttons[i].setTitle(questions[qNumber].answers[i], forState: .Normal)
}
questions.removeAtIndex(qNumber)
}
else {
NSLog("done")
self.performSegueWithIdentifier("Segue1", sender: self)
}
}
Button code, where I check whether the answer is correct or not:
@IBAction func btn1(sender: AnyObject) {
if answerNumber == 0 {
pickQuestion()
count += 1
}
else {
NSLog("Wrong")
pickQuestion()
}
}
After a bit of debugging I found out that questions.removeAtIndex(qNumber) is the one removing the array (removeAtIndex is used to prevent questions appear again when already answered)
I am declaring qNumber as:
qNumber = random() % questions.count
How can I set qNumber to be as the current array that gets removed after it has been answered?
I am switching the view in:
else {
NSLog("done")
self.performSegueWithIdentifier("Segue1", sender: self)
}
Upvotes: 2
Views: 194
Reputation: 5616
After displaying the last question, you remove it from the array, making the array empty. Then, upon answering, you have:
if answerNumber == 0 {
pickQuestion()
count += 1
}
The code in the function checks to see if questions.count is greater than 0, which it isn't, and performs the segue. The segue happens before the count gets updated. Try changing the block to allow the count to be updated first:
if answerNumber == 0 {
count += 1
pickQuestion()
}
Upvotes: 1