Sllew Sllew - 4 years ago 177
Swift Question

Swift casting causes the app to crash

I've been having this odd error in a recent swift program of mine. It involves random occurrences, and to simulate this I assign an event 'odds,' then generate two random numbers (using these odds), and if the numbers are the same then the action occurs. But the program crashes, inexplicably, in the generation part. The only explanation I can think of is the overabundance of casting required, but I'm not sure why it only crashes once in a while. I'd appreciate any insight as to why the casting crashes and any suggestions for what to do to avoid such excessive casting.

My image shows the code and the error, and the code below is a generalization of my code.
Crash Error

let rand = [Int(arc4random_uniform(UInt32(someInt))), Int(arc4random_uniform(UInt32(someInt)))]
if (rand[0] == rand[1]) {
executeAction()
}

Answer Source

This occurs because your integer variable shootOdds, at some point, takes a negative value (or: less plausible, a value larger than 4,294,967,295), causing runtime error for cast to unsigned integer, UInt32(someInt). You can avoid this by making sure, prior to the let rand = ... row, that shootOdds >= 0 (or in your code example above, someInt >= 0), or that you number is not larger than the upper limit for UInt32.

Hence note that the error is not associated with the rand function, but specifically the negative integer cast to unsigned integer.

E.g., try the following example in your playground, to assert you get the same runtime error:

let a = -1
let b = UInt32(a)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download