7

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?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Tom Fox
  • 897
  • 3
  • 14
  • 34

3 Answers3

7

Declare amountOfQuestions as a UInt32:

var amountOfQuestions: UInt32 = 2

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

yesthisisjoe
  • 1,987
  • 2
  • 16
  • 32
5

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

gaskbr
  • 368
  • 3
  • 12
  • Your second part, while partially true (it's true that you can't subtract a UInt32 from an Int), is irrelevant. In this case the 1 will automatically be the appropriate type, in this case an Int to match amountOfQuestions for the subtraction to work. The problem is that that Int can't be passed to arc4random_uniform, which expects a UInt32 argument. Note that it's perfectly valid to use `UInt32(2) - 1` and the result is also a UInt32 (which is why your actual fix works) – David Berry Feb 22 '16 at 20:13
  • The second part was used to complete the thought. In the code presented by the question, amountOfQuestions wasn't an UInt32. There was only one solution in my answer, I just broke in two for him to understand it better. What you said about being perfect valid to UInt32 is known and totally irrelevant too.... – gaskbr Feb 22 '16 at 20:40
4

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);
JAL
  • 41,701
  • 23
  • 172
  • 300
  • 2
    Furthermore, it's worth noting that if `amountOfQuestions` is computed, for instance from the size of an array, the appropriate answer might just be to cast it to UInt32 using the constructor, ie., UInt32(questions.count). – David Berry Feb 22 '16 at 20:15