Why does the following code crash on an iPhone 5 but not an iPhone 5S?

后端 未结 2 1434
谎友^
谎友^ 2020-12-19 03:41
func rand(max: Int?) -> Int {
    var index = Int(arc4random())
    return max? != nil ? (index % max!) : index
}

I get an exception on the last

2条回答
  •  佛祖请我去吃肉
    2020-12-19 04:16

    The Int integer type is a 32-bit integer on the iPhone 5 and a 64-bit integer on the 5S. Since arc4random() returns a UInt32, which has twice the positive range of an Int on the iPhone 5, your first version basically has a 50% chance of crashing on this line:

    var index = Int(arc4random())
    

    Your modified version waits to convert until you take the modulo sum with max, so it's safe to convert to Int there. You should check out arc4random_uniform, which handles the modulo for you and avoids some bias inherent in your current implementation.

提交回复
热议问题