4

I made a quiz app in Swift 2 I'm trying to update the syntax from random to arc4random...

if Questions.count > 0 && counter <= 15 {
            QNumber = arc4random()% Questions.count
            QLabel.text = Questions[QNumber].Question

        AnswerNumber = Questions[QNumber].Answer

        for i in 0..<Buttons.count{
            Buttons[i].setTitle(Questions[QNumber].Answers[i], for: UIControlState())
        }
        Questions.remove(at: QNumber)
    }
vadian
  • 274,689
  • 30
  • 353
  • 361
Johnd
  • 584
  • 2
  • 6
  • 21
  • 2
    I'm not sure I understand your question. (Also, there's no need for the modulo; you should use `arc4random_uniform` instead, with a parameter, as that will [avoid modulo bias](http://stackoverflow.com/questions/3420581/how-to-select-range-of-values-when-using-arc4random)) – Matt Gibson Nov 15 '16 at 16:12
  • 2
    Please consider to conform to the naming convention that variable names start with a lowercase letter. Your code is very hard to read. – vadian Nov 15 '16 at 16:19

2 Answers2

4

It's recommended to use arc4random_uniform instead of simple arc4random.

arc4random_uniform expects an UInt32 parameter so you have to convert the values back and forth

qNumber = Int(arc4random_uniform(UInt32(questions.count)))
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Does the upper bound get included in the possible results? For example, if questions.count were 100, would arc4random_uniform generate a random number between 0-99 inclusive, or 1-100 inclusive? – zeeple Feb 18 '17 at 05:36
  • From the documentation: *The arc4random() function returns pseudo-random numbers in the range of 0 to (2**32)-1* so if you need 1-100 pass 99 and add 1. – vadian Feb 18 '17 at 05:41
2

Here's an example using arc4random_uniform(). That function wants to communicate with UInt32s, which requires some casting between types.

let questions = ["What is love?", "What's the capital of Mongolia?"]
let index = Int(arc4random_uniform(UInt32(questions.count)))
print(questions[index])
jjs
  • 1,338
  • 7
  • 19