我在使用 Swift/Xcode 时遇到了一个非常奇怪的问题(老实说,我不太确定来源在哪里)。
我必须遵循以下代码:
extension Int {
func random(min : Int = 0, max : Int = Int(UInt32.max - 1)) {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
}
当我在 Xcode 中构建这段代码时,它运行得非常好。但是,当我尝试使用 xcodebuild
构建它时,编译器会给我以下错误:
integer overflows when converted from 'UInt32' to 'Int'
public static func random(min : Int = 0, max : Int = Int(UInt32.max - 1)) -> Int {
这很奇怪,因为 Int.max
和 UInt32.max
的值不相近。
如果有任何帮助,我正在使用 Xcode 7.0 beta 5 进行编译...因为我完全被难住了。
最佳答案
如果您为 32 位设备(例如 iPhone 5)编译,则会出现该错误,
因为 Int
是 signed 32 位整数,并且 UInt32.max - 1
超出其范围。
另一个问题是UInt32(max - min + 1)
的计算,
由于溢出,它可能会在运行时崩溃,例如如果你打电话
random(min : Int.min, max : Int.max)
参见 How can I generate large, ranged random numbers in Swift?一个可能的解决方案,以避免 为任意范围生成随机数时溢出。
关于ios - 从 UInt32 转换为 Int 时溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32075019/