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

28,737

Solution 1

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);

Solution 2

Declare amountOfQuestions as a UInt32:

var amountOfQuestions: UInt32 = 2

PS: If you want to be grammatically correct it's number of questions.

Solution 3

First thing: The method "arc4random_uniform" expects an argument of type UInt32, so when you put that subtraction there, it converted the '1' you wrote to UInt32.

Second thing: In swift you can't subtract a UInt32 (the '1' in your formula) from an Int (in this case 'amountOfQuestions').

To solve it all, you'll have to consider changing the declaration of 'amountOfQuestions' to:

var amountOfQuestions = UInt32(2)

That should do the trick :)

Share:
28,737
Tom Fox
Author by

Tom Fox

Aspiring entrepreneur, Apple WWDC 2015 Scholarship recipient, hobbyist iOS developer, Parse Platform fan & contributor.

Updated on July 09, 2022

Comments

  • Tom Fox
    Tom Fox almost 2 years

    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?