0

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)."

screenshot

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?

Dima
  • 23,484
  • 6
  • 56
  • 83
tommsyeah
  • 17
  • 2
  • 9

1 Answers1

3

The UInt32 version of - has the signature: (UInt32, UInt32) -> UInt32.

7 - 9 is -2.

You can't express -2 with an unsigned type such as UInt32.

Try something like:

func random(inRange range: Range<Int>) -> Int {
    return range.lowerBound + Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound)))
}

func random(inRange range: ClosedRange<Int>) -> Int {
    return range.lowerBound + Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound + 1)))
}

print(random(inRange: 1..<10))
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • 2
    Your suggested function can (theoretically) crash as well, because `UInt32(max - min + 1)` can overflow. So either you have to check that as a precondition, or make it work with "large" integers, as e.g. in http://stackoverflow.com/questions/31391577/how-can-i-generate-large-ranged-random-numbers-in-swift. – Martin R Jun 20 '16 at 17:43
  • @AMomchilov I think you mean `7-9 is -2`. – D Stanley Jun 23 '16 at 18:45