swift 3 中的取模运算符 (%) 是多少?

What is the modulus operator (%) in swift 3?

我有这条线:

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_uniform(_:) 会是更好的选择。

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

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

我的猜测是它在 Foundation 的某个地方并且需要一个明确的 import Foundation

更新

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

使用https://developer.apple.com/documentation/swift/double/2884269-remainder

如果您使用 truncatingRemainder(如其他评论中所述),那么它将首先降低该值,这意味着 3.14 将变为 3。

在 mod

之前将您的变量转换为 Int

例子

let result = Int(value) % 3

根据新指南Swift 5,已更改

value.truncatingRemainder(dividingBy: 2)