ios - 从 UInt32 转换为 Int 时溢出

标签 ios swift swift2

我在使用 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.maxUInt32.max 的值不相近。

如果有任何帮助,我正在使用 Xcode 7.0 beta 5 进行编译...因为我完全被难住了。

最佳答案

如果您为 32 位设备(例如 iPhone 5)编译,则会出现该错误, 因为 Intsigned 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/

相关文章:

ios - 在 Swiftui animate WithDuration 期间跟踪对象的坐标

ios - 如何使用 Swift 2 (SpriteKit) 以编程方式添加要查看的对象?

ios - 如何复合函数并持久化进度

ios - 不断使用 React Native 获取未定义的字体系列 - 链接矢量图标 - 构建告诉我取消链接

ios - 从核心数据实体获取属性值数组的有效方法是什么?

iOS - UITapGesture 是否开始和结束?

swift2 - 如何在 swift 中将底部边框作为子层添加到标签中?

ios - 我如何才能检测到用户是否仍然在 firebase 中有一个身份验证 session ?

swift - UILocalNotification 的 userInfo 对象的符合性要求

SwiftUI,使用 ForEach 的参数导致错误 "Unable to infer closure type"