Swift3 swift 3中的模数运算符(%)是什么?

Swift3 swift 3中的模数运算符(%)是什么?,swift3,modulus,Swift3,Modulus,我有一句话: randomIndex = Int(drand48() % Double(alphabetColors.count)) Xcode 8(Swift 3)告诉我: '%' is unavailable: Use truncatingRemainder instead 没有接线员了吗?如何转换代码?您只需按照诊断信息操作即可: let randomIndex = Int(drand48().truncatingRemainder(dividingBy: Double(alphabe

我有一句话:

randomIndex = Int(drand48() % Double(alphabetColors.count))
Xcode 8(Swift 3)告诉我:

'%' is unavailable: Use truncatingRemainder instead

没有接线员了吗?如何转换代码?

您只需按照诊断信息操作即可:

let randomIndex = Int(drand48().truncatingRemainder(dividingBy: Double(alphabetColors.count)))
或者使用
arc4random\u uniform(:)
将是更好的选择

let randomIndex = Int(arc4random_uniform(UInt32(alphabetColors.count)))

这似乎对我是可用的,目前在Swift 3.1上,所以有可能它被添加回来

P>我猜它是在基础的地方,需要一个明确的<代码>导入基础< /COD> < /P> 更新

这仅适用于Int类型。对于double,似乎需要截断余数。

使用


如果您使用TruncingRequires(如其他注释中所述),那么它将首先将值设置为下限,这意味着3.14将变为3。

在mod之前将变量转换为Int

范例

let result = Int(value) % 3

根据新的指南Swift 5,它已更改

value.truncatingRemainder(dividingBy: 2)

%运算符是一个余数运算,而不是Swift中的模运算。下面是一些关于它的讨论:我是这样做的。。这很奇怪,我在Swift 3.1上找不到任何关于它的内容。你这方面有没有第三方图书馆可以诱发这种行为?哦,你是对的,我在官方文件中找到了一段关于它的内容,他们称之为“剩余经营者”