arc4random_uniform infinite loop

I am trying to create random questions in my app that show users different question each time. I am trying to be sure about all answer is uniqe and different. The code that is below create question and check the answers is different from each other. But when instance of question is lower it create infinite loop. For example if I have 4 question instance it goes infinite. I have fixed that by increasing minimum number of question. Now I have at least 8 differen question at start and there is no problem.

var i = 0

while i < 4 {

var isInAnswers = false

let number = questions.count.random()

if i == idOfCorrectAnswer {

i += 1

} else {

let word = questions[number]

Answers.forEach{ if $0.currentTitle == word.name { isInAnswers = true}}

if !isInAnswers {

Answers[i].setTitle(word.name , for:.normal)

i += 1

}

}

}

In the above code, if 'isInAnswers' gets set to 'true', then the variable 'i' is no longer incremented, and the code will loop forever.


This sort of algorithm (looping on a variable that you change inside the loop based on some logical conditions) is always hard to follow. In this case, it also seems odd that you say you're trying to pick a random question, but your loop is all about the answers.


It would probably be worth trying to re-design the code so that it more clearly reflects what you're trying to do.

arc4random_uniform infinite loop
 
 
Q