I'm new to Swift so this might turn out to be very simple, but I'll ask you anyway since I can't figure it out:
I was playing on the Playground and thought I'd write some lines of code in order to do this: generate a random number between two given values (a,b). If, for example, a = 5 and b = 20, a random number between 5 and 20 is supposed to be generated. But I get an unexpected error! I wrote these lines of code
var a = UInt32()
var b = UInt32()
var randomNumberInBetween = Int()
a = 5
b = 20
if (b - a) > 0 {
randomNumberInBetween = Int(arc4random_uniform(b - a) + a)
} else {
print("error", terminator: "")
}
Now:
If b > a (so that (b-a)>0 ) it works just fine.
If b = a it prints "error", so it works correctly.
BUT if a > b, so that (b-a)<0, it gives this error : "Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_l386_INVOP, subcode=0x0)."
My question is: If (b-a)<0 shouldn't it just run the "else" part of the if statement and just print "error" ? Why does this error occur?
Aucun commentaire:
Enregistrer un commentaire