无法将类型 'Int' 的值转换为预期的参数类型 'UInt32'

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

我正在尝试在 Swift 中生成一个随机数:

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

但这会导致错误:

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

有什么问题?关于如何解决此错误,我有什么想法吗?

使您的 amountOfQuestions 变量成为编译器推断的 UInt32 而不是 Int

var amountOfQuestions: UInt32 = 2

// ...

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

arc4random_uniform 需要 UInt32.

来自Darwin docs

arc4random_uniform(u_int32_t upper_bound);

将 amountOfQuestions 声明为 UInt32:

var amountOfQuestions: UInt32 = 2

PS:如果你想语法正确,那就是 个问题。

第一件事: 方法 "arc4random_uniform" 需要一个 UInt32 类型的参数,因此当您将减法放在那里时,它会将您写入的“1”转换为 UInt32。

第二件事:在 swift 中,您不能从 Int(在本例中为 'amountOfQuestions')中减去 UInt32(公式中的“1”)。

要解决所有问题,您必须考虑将 'amountOfQuestions' 的声明更改为:

var amountOfQuestions = UInt32(2)

这应该可以解决问题:)