Swift - An unexpected error in a simple if statement

I am new to Swift, so this may turn out to be very simple, but I will ask you anyway, as I cannot understand:

I played on the Playground and thought that I would write some lines of code to do this: generate a random number between two given values ​​(a, b). If, for example, a = 5 and b = 20, it is assumed that a random number between 5 and 20 should 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 (ba)> 0), it works fine.

If b = a, it prints an “error”, so it works correctly.

BUT, if a> b, so that (ba) <0, it gives this error: "Execution was aborted, reason: EXC_BAD_INSTRUCTION (code = EXC_l386_INVOP, subcode = 0x0)."

screenshot

: if (b-a) < 0 "else" if ""? ?

0
1

UInt32 - : (UInt32, UInt32) -> UInt32.

7 - 9 -2.

-2 , UInt32.

- :

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))
+3

All Articles