Search code examples
iosswiftintegerarc4randomuint32

Cannot convert value of type 'Int' to expected argument type 'UInt32'


I am trying to generate a random number in Swift:

var amountOfQuestions = 2
var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1

but this results in the error:

Cannot convert value of type 'Int' to expected argument type 'UInt32'

What is the problem? Any ideas on what I can do to fix this error?


Solution

  • Make your amountOfQuestions variable an UInt32 rather than an Int inferred by the compiler.

    var amountOfQuestions: UInt32 = 2
    
    // ...
    
    var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
    

    arc4random_uniform requires a UInt32.

    From the Darwin docs:

    arc4random_uniform(u_int32_t upper_bound);