-1

So I am working on my first personal project (includes a quiz feature), while at the same time taking a swift course. I am trying to figure out, how to randomize the arrays.

I've found a few videos explaining something similar, but nothing seems to work for me.

This is an example of one of my question banks that needs to be shuffled.

class ImageQuestionBank {
var list = [ImageQuestion] ()
init () {
    let item = ImageQuestion(qtext: "Example Question?", image: "image1", correctAnswer: true)
    list.append(item)
    list.append(ImageQuestion(qtext: "Example Question?", image: "image2", correctAnswer: false))
    list.append(ImageQuestion(qtext: "Example Question?", image: "image3", correctAnswer: true))
    }
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52

2 Answers2

2

As @Retterdesdialogs comment suggests, you can use shuffled() which returns the elements of the sequence, shuffled. or shuffle() for in place shuffle

But, instead of shuffling of an array, which is a costly operation, use Int random function to get random int between given range.

let randomInt = Int.random(in: 0..<list.count) // this will give a random int value between 0 and list count.

Now fetch item using randomInt

Suryakant Sharma
  • 3,852
  • 1
  • 25
  • 47
-1

Use arc4random_uniform(list.count) to generate the random index for list object. But to make sure a question will not repeat for that maintain a askedQuestionList. And before showing the question to user check question entry in askedQuestionList.

Another approach shuffle your question array, check this question.

Ravi Sharma
  • 975
  • 11
  • 29