1. Create a structure
This allows you to ask a question and an array of answers that will be useful when shuffling later.
struct Question {
var id: Int
var questionText: String
var answers: [String]
}
var example = Question(id: 1, questionText: "Foo?", answers:["1", "2", "3", "4"])
var id = example.id
var questionText = example.questionText
var answers = example.answers
2. Now randomize the array of Questions using the Fisher-Yates Shuffle
Cool, because time is O (n).
var question1 = Question(id: 1, questionText: "Foo?", answers:["1", "2", "3", "4"])
var question2 = Question(id: 2, questionText: "Bar?", answers:["1", "2", "3", "4"])
var question3 = Question(id: 3, questionText: "Baz?", answers:["1", "2", "3", "4"])
var question4 = Question(id: 4, questionText: "What is after Baz?", answers:["1", "2", "3", "4"])
var questions = [question1, question2, question3, question4]
for i in 0..<questions.count-2 {
var rand = Int(arc4random_uniform(questions.count - i))
var copy = questions[i]
questions[i] = questions[rand]
questions[rand] = copy
}
print(questions)
source
share