func rand(max: Int?) -> Int {
var index = Int(arc4random())
return max? != nil ? (index % max!) : index
}
I get an exception on the last
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.