1

I hope you are all well!

I am new in Coding and Swift.

I am making a quiz app and there are 2 things I would need help with.

The first one is : I want to randomise the options of the multiple choice answers for each question every time the game is played.

For example, if i define an array to contain the different answer options (the different colours), i want the question to retrieve 3 random answers together with the correct one like so:

let answers = [
    "Red",
    "Blue",
    "Green",
    "Yellow",
    "Orange",
    "Black",
    "Grey",
    "White"]


Question(q: "What colour is the ocean ?", a: ["Blue", "randomAnswer1", "randomAnswer2","randomAnswer3"], correctAnswer: "Blue"),

Question(q: "What colour are roses ?", a: ["randomAnswer1", "Red", "randomAnswer2","randomAnswer3"], correctAnswer: "Red"),

The 2nd part I would need help with is: If my quiz has 100 questions, how could I make the series of the questions to be RANDOM but UNIQUE every time the game is played?

Meaning that until the Quiz ends, each question would need to be displayed only once.

Thank you very much for your help!

1 Answers1

0

1: There is a method to get a random element from an array

let random = answers.randomElement()

2: You can iterate and delete the used element, so next time you get a random element the array does not consist it

answers = answers.filter { $0 != random }
ptfpn
  • 3
  • 3