-1

I want to develop a quiz app in ios. I saw a tutorial which used switch case .Now that I have more than hundreds of questions.How can I implement it and I need my questions to be random.

  • Create a text file and put your 100 questions as JSON format.it will be easy to Modify.Read the file display your questions using random number between 1 to 100. – Dharma Jun 13 '17 at 04:33
  • This question might end up being closed because it doesn't meet SO guidelines. Here's their guidance, which might help you improve it: stackoverflow.com/help/how-to-ask - A small sample of code showing what you've tried might improve the question and increase your chance of a better answer. – Joe Mayo Jun 13 '17 at 05:54

2 Answers2

1
let randomIndex = Int(arc4random_uniform(UInt32(questionsArray.count)))
print(questionsArray[randomIndex])

Use above code to pick random questions from an array

Developer
  • 822
  • 9
  • 23
0

You can use the shuffle function here to shuffle your questions. Simply use it as

var nums = [1, 2, 3, 4, 5]
nums.shuffle() // this will mutate and changed to shuffled array [5, 3, 1, 2, 4]

The exact extension used is below:

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            swap(&self[firstUnshuffled], &self[i])
        }
    }
}
xmhafiz
  • 3,482
  • 1
  • 18
  • 26